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