]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/engine/Index.java
Fix reading of oldest v6 dictionaries.
[Dictionary.git] / src / com / hughes / android / dictionary / engine / Index.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.engine;
16
17 import java.io.DataInput;
18 import java.io.DataOutput;
19 import java.io.IOException;
20 import java.io.PrintStream;
21 import java.io.RandomAccessFile;
22 import java.util.AbstractList;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.EnumMap;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.concurrent.atomic.AtomicBoolean;
34 import java.util.regex.Pattern;
35
36 import com.hughes.android.dictionary.DictionaryInfo;
37 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
38 import com.hughes.android.dictionary.engine.RowBase.RowKey;
39 import com.hughes.util.CachingList;
40 import com.hughes.util.DataInputBuffer;
41 import com.hughes.util.StringUtil;
42 import com.hughes.util.TransformingList;
43 import com.hughes.util.raf.RAFList;
44 import com.hughes.util.raf.RAFSerializer;
45 import com.hughes.util.raf.UniformRAFList;
46 import com.ibm.icu.text.Transliterator;
47
48 public final class Index {
49
50     private static final int CACHE_SIZE = 5000;
51
52     public final Dictionary dict;
53
54     public final String shortName; // Typically the ISO code for the language.
55     public final String longName;
56
57     // persisted: tells how the entries are sorted.
58     public final Language sortLanguage;
59     public final String normalizerRules;
60
61     // Built from the two above.
62     private Transliterator normalizer;
63
64     // persisted
65     public final List<IndexEntry> sortedIndexEntries;
66
67     // persisted.
68     public final Set<String> stoplist;
69
70     // One big list!
71     // Various sub-types.
72     // persisted
73     public final List<RowBase> rows;
74     public final boolean swapPairEntries;
75
76     // Version 2:
77     @SuppressWarnings("WeakerAccess")
78     public int mainTokenCount = -1;
79
80     // --------------------------------------------------------------------------
81
82     public Index(final Dictionary dict, final String shortName, final String longName,
83                  final Language sortLanguage, final String normalizerRules,
84                  final boolean swapPairEntries, final Set<String> stoplist) {
85         this.dict = dict;
86         this.shortName = shortName;
87         this.longName = longName;
88         this.sortLanguage = sortLanguage;
89         this.normalizerRules = normalizerRules;
90         this.swapPairEntries = swapPairEntries;
91         sortedIndexEntries = new ArrayList<>();
92         this.stoplist = stoplist;
93         rows = new ArrayList<>();
94
95         normalizer = null;
96     }
97
98     /**
99      * Deferred initialization because it can be slow.
100      */
101     @SuppressWarnings("WeakerAccess")
102     public synchronized Transliterator normalizer() {
103         if (normalizer == null) {
104             normalizer = TransliteratorManager.get(normalizerRules);
105         }
106         return normalizer;
107     }
108
109     /**
110      * Note that using this comparator probably involves doing too many text
111      * normalizations.
112      */
113     @SuppressWarnings("WeakerAccess")
114     public NormalizeComparator getSortComparator() {
115         return new NormalizeComparator(normalizer(), sortLanguage.getCollator(), dict.dictFileVersion);
116     }
117
118     public Index(final Dictionary dict, final DataInputBuffer raf) throws IOException {
119         this.dict = dict;
120         shortName = raf.readUTF();
121         longName = raf.readUTF();
122         final String languageCode = raf.readUTF();
123         sortLanguage = Language.lookup(languageCode);
124         normalizerRules = raf.readUTF();
125         swapPairEntries = raf.readBoolean();
126         if (dict.dictFileVersion >= 2) {
127             mainTokenCount = raf.readInt();
128         }
129         sortedIndexEntries = CachingList.create(
130                                  RAFList.create(raf, new IndexEntrySerializer(),
131                                                 dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE, true);
132         if (dict.dictFileVersion >= 7) {
133             int count = StringUtil.readVarInt(raf);
134             stoplist = new HashSet<>(count);
135             for (int i = 0; i < count; ++i) {
136                 stoplist.add(raf.readUTF());
137             }
138         } else if (dict.dictFileVersion >= 4) {
139             stoplist = new HashSet<>();
140             raf.readInt(); // length
141             raf.skipBytes(18);
142             byte b = raf.readByte();
143             raf.skipBytes(b == 'L' ? 71 : 33);
144             while ((b = raf.readByte()) == 0x74) {
145                 stoplist.add(raf.readUTF());
146             }
147             if (b != 0x78) throw new IOException("Invalid data in dictionary stoplist!");
148         } else {
149             stoplist = Collections.emptySet();
150         }
151         rows = CachingList.create(
152                    UniformRAFList.create(raf, new RowBase.Serializer(this)),
153                    CACHE_SIZE, true);
154     }
155
156     public void write(final DataOutput out) throws IOException {
157         RandomAccessFile raf = (RandomAccessFile)out;
158         raf.writeUTF(shortName);
159         raf.writeUTF(longName);
160         raf.writeUTF(sortLanguage.getIsoCode());
161         raf.writeUTF(normalizerRules);
162         raf.writeBoolean(swapPairEntries);
163         raf.writeInt(mainTokenCount);
164         RAFList.write(raf, sortedIndexEntries, new IndexEntrySerializer(), 32, true);
165         StringUtil.writeVarInt(raf, stoplist.size());
166         for (String i : stoplist) {
167             raf.writeUTF(i);
168         }
169         UniformRAFList.write(raf, rows, new RowBase.Serializer(this), 3 /* bytes per entry */);
170     }
171
172     public void print(final PrintStream out) {
173         for (final RowBase row : rows) {
174             row.print(out);
175         }
176     }
177
178     private final class IndexEntrySerializer implements RAFSerializer<IndexEntry> {
179         @Override
180         public IndexEntry read(DataInput raf) throws IOException {
181             return new IndexEntry(Index.this, raf);
182         }
183
184         @Override
185         public void write(DataOutput raf, IndexEntry t) throws IOException {
186             t.write(raf);
187         }
188     }
189
190     public static final class IndexEntry {
191         public final String token;
192         private final String normalizedToken;
193         public final int startRow;
194         final int numRows; // doesn't count the token row!
195         public List<HtmlEntry> htmlEntries;
196
197         public IndexEntry(final Index index, final String token, final String normalizedToken,
198                           final int startRow, final int numRows) {
199             assert token.equals(token.trim());
200             assert token.length() > 0;
201             this.token = token;
202             this.normalizedToken = normalizedToken;
203             this.startRow = startRow;
204             this.numRows = numRows;
205             this.htmlEntries = new ArrayList<>();
206         }
207
208         IndexEntry(final Index index, final DataInput raf) throws IOException {
209             token = raf.readUTF();
210             if (index.dict.dictFileVersion >= 7) {
211                 startRow = StringUtil.readVarInt(raf);
212                 numRows = StringUtil.readVarInt(raf);
213             } else {
214                 startRow = raf.readInt();
215                 numRows = raf.readInt();
216             }
217             final boolean hasNormalizedForm = raf.readBoolean();
218             normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
219             if (index.dict.dictFileVersion >= 7) {
220                 int size = StringUtil.readVarInt(raf);
221                 if (size == 0) {
222                     this.htmlEntries = Collections.emptyList();
223                 } else {
224                     final int[] htmlEntryIndices = new int[size];
225                     for (int i = 0; i < size; ++i) {
226                         htmlEntryIndices[i] = StringUtil.readVarInt(raf);
227                     }
228                     this.htmlEntries = new AbstractList<HtmlEntry>() {
229                         @Override
230                         public HtmlEntry get(int i) {
231                             return index.dict.htmlEntries.get(htmlEntryIndices[i]);
232                         }
233
234                         @Override
235                         public int size() {
236                             return htmlEntryIndices.length;
237                         }
238                     };
239                 }
240             } else if (index.dict.dictFileVersion >= 6) {
241                 this.htmlEntries = CachingList.create(
242                                        RAFList.create((DataInputBuffer)raf, index.dict.htmlEntryIndexSerializer,
243                                                       index.dict.dictFileVersion,
244                                                       index.dict.dictInfo + " htmlEntries: "), 1, false);
245             } else {
246                 this.htmlEntries = Collections.emptyList();
247             }
248         }
249
250         public void write(DataOutput raf) throws IOException {
251             raf.writeUTF(token);
252             StringUtil.writeVarInt(raf, startRow);
253             StringUtil.writeVarInt(raf, numRows);
254             final boolean hasNormalizedForm = !token.equals(normalizedToken);
255             raf.writeBoolean(hasNormalizedForm);
256             if (hasNormalizedForm) {
257                 raf.writeUTF(normalizedToken);
258             }
259             StringUtil.writeVarInt(raf, htmlEntries.size());
260             for (HtmlEntry e : htmlEntries)
261                 StringUtil.writeVarInt(raf, e.index());
262         }
263
264         public String toString() {
265             return String.format("%s@%d(%d)", token, startRow, numRows);
266         }
267
268         String normalizedToken() {
269             return normalizedToken;
270         }
271     }
272
273     private static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
274         @Override
275         public String transform(IndexEntry t1) {
276             return t1.token;
277         }
278     };
279
280     public IndexEntry findExact(final String exactToken) {
281         final int result = Collections.binarySearch(
282                                TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
283                                getSortComparator());
284         if (result >= 0) {
285             return sortedIndexEntries.get(result);
286         }
287         return null;
288     }
289
290     public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
291         final int index = findInsertionPointIndex(token, interrupted);
292         return index != -1 ? sortedIndexEntries.get(index) : null;
293     }
294
295     private int compareIdx(String token, final Comparator<Object> sortCollator, int idx) {
296         final IndexEntry entry = sortedIndexEntries.get(idx);
297         return NormalizeComparator.compareWithoutDash(token, entry.normalizedToken(), sortCollator, dict.dictFileVersion);
298     }
299
300     private int findMatchLen(final Comparator<Object> sortCollator, String a, String b) {
301         int start = 0;
302         int end = Math.min(a.length(), b.length());
303         while (start < end)
304         {
305             int mid = (start + end + 1) / 2;
306             if (sortCollator.compare(a.substring(0, mid), b.substring(0, mid)) == 0)
307                 start = mid;
308             else
309                 end = mid - 1;
310         }
311         return start;
312     }
313
314     private int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
315         token = normalizeToken(token);
316
317         int start = 0;
318         int end = sortedIndexEntries.size();
319
320         final Comparator<Object> sortCollator = sortLanguage.getCollator();
321         while (start < end) {
322             final int mid = (start + end) / 2;
323             if (interrupted.get()) {
324                 return -1;
325             }
326             final IndexEntry midEntry = sortedIndexEntries.get(mid);
327
328             int comp = NormalizeComparator.compareWithoutDash(token, midEntry.normalizedToken(), sortCollator, dict.dictFileVersion);
329             if (comp == 0)
330                 comp = sortCollator.compare(token, midEntry.normalizedToken());
331             if (comp == 0) {
332                 return windBackCase(token, mid, interrupted);
333             } else if (comp < 0) {
334                 // System.out.println("Upper bound: " + midEntry + ", norm=" +
335                 // midEntry.normalizedToken() + ", mid=" + mid);
336
337                 // Hack for robustness if sort order is broken
338                 if (mid + 2 < end &&
339                     compareIdx(token, sortCollator, mid + 1) > 0 &&
340                     compareIdx(token, sortCollator, mid + 2) > 0) {
341                     start = mid;
342                 } else {
343                     end = mid;
344                 }
345             } else {
346                 // System.out.println("Lower bound: " + midEntry + ", norm=" +
347                 // midEntry.normalizedToken() + ", mid=" + mid);
348
349                 // Hack for robustness if sort order is broken
350                 if (mid - 2 >= start &&
351                     compareIdx(token, sortCollator, mid - 1) < 0 &&
352                     compareIdx(token, sortCollator, mid - 2) < 0) {
353                     end = mid + 1;
354                 } else {
355                     start = mid + 1;
356                 }
357             }
358         }
359
360         // if the word before is the better match, move
361         // our result to it
362         if (start > 0 && start < sortedIndexEntries.size()) {
363             String prev = sortedIndexEntries.get(start - 1).normalizedToken();
364             String next = sortedIndexEntries.get(start).normalizedToken();
365             if (findMatchLen(sortCollator, token, prev) >= findMatchLen(sortCollator, token, next))
366                 start--;
367         }
368
369         // If we search for a substring of a string that's in there, return
370         // that.
371         int result = Math.min(start, sortedIndexEntries.size() - 1);
372         result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
373         return result;
374     }
375
376     private int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
377         while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
378             --result;
379             if (interrupted.get()) {
380                 return result;
381             }
382         }
383         return result;
384     }
385
386     public IndexInfo getIndexInfo() {
387         return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
388     }
389
390     private static final int MAX_SEARCH_ROWS = 1000;
391
392     private final Map<String, Integer> prefixToNumRows = new HashMap<>();
393
394     private synchronized int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
395                                                              final int maxRows, final AtomicBoolean interrupted) {
396         final Integer numRows = prefixToNumRows.get(normalizedPrefix);
397         if (numRows != null) {
398             return numRows;
399         }
400         final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
401
402         int rowCount = 0;
403         for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
404             if (interrupted.get()) {
405                 return -1;
406             }
407             final IndexEntry indexEntry = sortedIndexEntries.get(index);
408             if (!indexEntry.normalizedToken.startsWith(normalizedPrefix) &&
409                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(normalizedPrefix)) {
410                 break;
411             }
412             rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
413             if (rowCount > maxRows) {
414                 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
415                 break;
416             }
417         }
418         prefixToNumRows.put(normalizedPrefix, rowCount);
419         return rowCount;
420     }
421
422     public final List<RowBase> multiWordSearch(
423         final String searchText, final List<String> searchTokens,
424         final AtomicBoolean interrupted) {
425         final long startMills = System.currentTimeMillis();
426         final List<RowBase> result = new ArrayList<>();
427
428         final Set<String> normalizedNonStoplist = new HashSet<>();
429
430         String bestPrefix = null;
431         int leastRows = Integer.MAX_VALUE;
432         final StringBuilder searchTokensRegex = new StringBuilder();
433         for (int i = 0; i < searchTokens.size(); ++i) {
434             if (interrupted.get()) {
435                 return null;
436             }
437             final String searchToken = searchTokens.get(i);
438             final String normalized = normalizeToken(searchTokens.get(i));
439             // Normalize them all.
440             searchTokens.set(i, normalized);
441
442             if (!stoplist.contains(searchToken)) {
443                 if (normalizedNonStoplist.add(normalized)) {
444                     final int numRows = getUpperBoundOnRowsStartingWith(normalized,
445                                         MAX_SEARCH_ROWS, interrupted);
446                     if (numRows != -1 && numRows < leastRows) {
447                         if (numRows == 0) {
448                             // We really are done here.
449                             return Collections.emptyList();
450                         }
451                         leastRows = numRows;
452                         bestPrefix = normalized;
453                     }
454                 }
455             }
456
457             if (searchTokensRegex.length() > 0) {
458                 searchTokensRegex.append("[\\s]*");
459             }
460             searchTokensRegex.append(Pattern.quote(normalized));
461         }
462         final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
463
464         if (bestPrefix == null) {
465             bestPrefix = searchTokens.get(0);
466             System.out.println("Everything was in the stoplist!");
467         }
468         System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
469                            + ", searchTokens=" + searchTokens);
470
471         // Place to store the things that match.
472         final Map<RowMatchType, List<RowBase>> matches = new EnumMap<>(
473                 RowMatchType.class);
474         for (final RowMatchType rowMatchType : RowMatchType.values()) {
475             if (rowMatchType != RowMatchType.NO_MATCH) {
476                 matches.put(rowMatchType, new ArrayList<RowBase>());
477             }
478         }
479
480         int matchCount = 0;
481
482         final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
483         if (exactMatchIndex != -1) {
484             final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
485             if (pattern.matcher(exactMatch.token).find()) {
486                 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
487             }
488         }
489
490         final String searchToken = bestPrefix;
491         final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
492         final Set<RowKey> rowsAlreadySeen = new HashSet<>();
493         for (int index = insertionPointIndex; index < sortedIndexEntries.size()
494                 && matchCount < MAX_SEARCH_ROWS; ++index) {
495             if (interrupted.get()) {
496                 return null;
497             }
498             final IndexEntry indexEntry = sortedIndexEntries.get(index);
499             if (!indexEntry.normalizedToken.startsWith(searchToken) &&
500                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(searchToken)) {
501                 break;
502             }
503
504             // System.out.println("Searching indexEntry: " + indexEntry.token);
505
506             // Extra +1 to skip token row.
507             for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
508                     + indexEntry.numRows
509                     && rowIndex < rows.size(); ++rowIndex) {
510                 if (interrupted.get()) {
511                     return null;
512                 }
513                 final RowBase row = rows.get(rowIndex);
514                 final RowBase.RowKey rowKey = row.getRowKey();
515                 if (rowsAlreadySeen.contains(rowKey)) {
516                     continue;
517                 }
518                 rowsAlreadySeen.add(rowKey);
519                 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
520                                                swapPairEntries);
521                 if (matchType != RowMatchType.NO_MATCH) {
522                     matches.get(matchType).add(row);
523                     ++matchCount;
524                 }
525             }
526         }
527         // } // searchTokens
528
529         // Sort them into a reasonable order.
530         final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
531             swapPairEntries);
532         for (final Collection<RowBase> rows : matches.values()) {
533             final List<RowBase> ordered = new ArrayList<>(rows);
534             Collections.sort(ordered, lengthComparator);
535             result.addAll(ordered);
536         }
537
538         System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
539         return result;
540     }
541
542     private String normalizeToken(final String searchToken) {
543         if (TransliteratorManager.init(null, null)) {
544             final Transliterator normalizer = normalizer();
545             return normalizer.transliterate(searchToken);
546         } else {
547             // Do our best since the Transliterators aren't up yet.
548             return searchToken.toLowerCase();
549         }
550     }
551
552 }