]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/engine/Index.java
db44b41546569ee39e178511fdbf5f5bf92b4bea
[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.RAFSerializable;
45 import com.hughes.util.raf.RAFSerializer;
46 import com.hughes.util.raf.SerializableSerializer;
47 import com.hughes.util.raf.UniformRAFList;
48 import com.ibm.icu.text.Transliterator;
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     public 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     public 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 DataInputBuffer 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 (dict.dictFileVersion >= 2) {
129             mainTokenCount = raf.readInt();
130         }
131         sortedIndexEntries = CachingList.create(
132                                  RAFList.create(raf, new IndexEntrySerializer(),
133                                                 dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE, true);
134         if (dict.dictFileVersion >= 7) {
135             int count = StringUtil.readVarInt(raf);
136             stoplist = new HashSet<>(count);
137             for (int i = 0; i < count; ++i) {
138                 stoplist.add(raf.readUTF());
139             }
140         } else if (dict.dictFileVersion >= 4) {
141             stoplist = new SerializableSerializer<Set<String>>().read(raf);
142         } else {
143             stoplist = Collections.emptySet();
144         }
145         rows = CachingList.create(
146                    UniformRAFList.create(raf, new RowBase.Serializer(this)),
147                    CACHE_SIZE, true);
148     }
149
150     @Override
151     public void write(final DataOutput out) throws IOException {
152         RandomAccessFile raf = (RandomAccessFile)out;
153         raf.writeUTF(shortName);
154         raf.writeUTF(longName);
155         raf.writeUTF(sortLanguage.getIsoCode());
156         raf.writeUTF(normalizerRules);
157         raf.writeBoolean(swapPairEntries);
158         raf.writeInt(mainTokenCount);
159         RAFList.write(raf, sortedIndexEntries, new IndexEntrySerializer(), 32, true);
160         StringUtil.writeVarInt(raf, stoplist.size());
161         for (String i : stoplist) {
162             raf.writeUTF(i);
163         }
164         UniformRAFList.write(raf, rows, new RowBase.Serializer(this), 3 /* bytes per entry */);
165     }
166
167     public void print(final PrintStream out) {
168         for (final RowBase row : rows) {
169             row.print(out);
170         }
171     }
172
173     private final class IndexEntrySerializer implements RAFSerializer<IndexEntry> {
174         @Override
175         public IndexEntry read(DataInput raf) throws IOException {
176             return new IndexEntry(Index.this, raf);
177         }
178
179         @Override
180         public void write(DataOutput raf, IndexEntry t) throws IOException {
181             t.write(raf);
182         }
183     }
184
185     public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
186         public final String token;
187         private final String normalizedToken;
188         public final int startRow;
189         final int numRows; // doesn't count the token row!
190         public List<HtmlEntry> htmlEntries;
191
192         public IndexEntry(final Index index, final String token, final String normalizedToken,
193                           final int startRow, final int numRows) {
194             assert token.equals(token.trim());
195             assert token.length() > 0;
196             this.token = token;
197             this.normalizedToken = normalizedToken;
198             this.startRow = startRow;
199             this.numRows = numRows;
200             this.htmlEntries = new ArrayList<>();
201         }
202
203         IndexEntry(final Index index, final DataInput raf) throws IOException {
204             token = raf.readUTF();
205             if (index.dict.dictFileVersion >= 7) {
206                 startRow = StringUtil.readVarInt(raf);
207                 numRows = StringUtil.readVarInt(raf);
208             } else {
209                 startRow = raf.readInt();
210                 numRows = raf.readInt();
211             }
212             final boolean hasNormalizedForm = raf.readBoolean();
213             normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
214             if (index.dict.dictFileVersion >= 7) {
215                 int size = StringUtil.readVarInt(raf);
216                 if (size == 0) {
217                     this.htmlEntries = Collections.emptyList();
218                 } else {
219                     final int[] htmlEntryIndices = new int[size];
220                     for (int i = 0; i < size; ++i) {
221                         htmlEntryIndices[i] = StringUtil.readVarInt(raf);
222                     }
223                     this.htmlEntries = new AbstractList<HtmlEntry>() {
224                         @Override
225                         public HtmlEntry get(int i) {
226                             return index.dict.htmlEntries.get(htmlEntryIndices[i]);
227                         }
228                         @Override
229                         public int size() {
230                             return htmlEntryIndices.length;
231                         }
232                     };
233                 }
234             } else if (index.dict.dictFileVersion >= 6) {
235                 this.htmlEntries = CachingList.create(
236                                        RAFList.create((DataInputBuffer)raf, index.dict.htmlEntryIndexSerializer,
237                                                       index.dict.dictFileVersion,
238                                                       index.dict.dictInfo + " htmlEntries: "), 1, false);
239             } else {
240                 this.htmlEntries = Collections.emptyList();
241             }
242         }
243
244         public void write(DataOutput raf) throws IOException {
245             raf.writeUTF(token);
246             StringUtil.writeVarInt(raf, startRow);
247             StringUtil.writeVarInt(raf, numRows);
248             final boolean hasNormalizedForm = !token.equals(normalizedToken);
249             raf.writeBoolean(hasNormalizedForm);
250             if (hasNormalizedForm) {
251                 raf.writeUTF(normalizedToken);
252             }
253             StringUtil.writeVarInt(raf, htmlEntries.size());
254             for (HtmlEntry e : htmlEntries)
255                 StringUtil.writeVarInt(raf, e.index());
256         }
257
258         public String toString() {
259             return String.format("%s@%d(%d)", token, startRow, numRows);
260         }
261
262         String normalizedToken() {
263             return normalizedToken;
264         }
265     }
266
267     private static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
268         @Override
269         public String transform(IndexEntry t1) {
270             return t1.token;
271         }
272     };
273
274     public IndexEntry findExact(final String exactToken) {
275         final int result = Collections.binarySearch(
276                                TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
277                                getSortComparator());
278         if (result >= 0) {
279             return sortedIndexEntries.get(result);
280         }
281         return null;
282     }
283
284     public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
285         final int index = findInsertionPointIndex(token, interrupted);
286         return index != -1 ? sortedIndexEntries.get(index) : null;
287     }
288
289     private int compareIdx(String token, final Comparator<Object> sortCollator, int idx) {
290         final IndexEntry entry = sortedIndexEntries.get(idx);
291         return NormalizeComparator.compareWithoutDash(token, entry.normalizedToken(), sortCollator, dict.dictFileVersion);
292     }
293
294     private int findMatchLen(final Comparator<Object> sortCollator, String a, String b) {
295         int start = 0;
296         int end = Math.min(a.length(), b.length());
297         while (start < end)
298         {
299             int mid = (start + end + 1) / 2;
300             if (sortCollator.compare(a.substring(0, mid), b.substring(0, mid)) == 0)
301                 start = mid;
302             else
303                 end = mid - 1;
304         }
305         return start;
306     }
307
308     private int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
309         token = normalizeToken(token);
310
311         int start = 0;
312         int end = sortedIndexEntries.size();
313
314         final Comparator<Object> sortCollator = sortLanguage.getCollator();
315         while (start < end) {
316             final int mid = (start + end) / 2;
317             if (interrupted.get()) {
318                 return -1;
319             }
320             final IndexEntry midEntry = sortedIndexEntries.get(mid);
321
322             int comp = NormalizeComparator.compareWithoutDash(token, midEntry.normalizedToken(), sortCollator, dict.dictFileVersion);
323             if (comp == 0)
324                 comp = sortCollator.compare(token, midEntry.normalizedToken());
325             if (comp == 0) {
326                 return windBackCase(token, mid, interrupted);
327             } else if (comp < 0) {
328                 // System.out.println("Upper bound: " + midEntry + ", norm=" +
329                 // midEntry.normalizedToken() + ", mid=" + mid);
330
331                 // Hack for robustness if sort order is broken
332                 if (mid + 2 < end &&
333                     compareIdx(token, sortCollator, mid + 1) > 0 &&
334                     compareIdx(token, sortCollator, mid + 2) > 0) {
335                     start = mid;
336                 } else {
337                     end = mid;
338                 }
339             } else {
340                 // System.out.println("Lower bound: " + midEntry + ", norm=" +
341                 // midEntry.normalizedToken() + ", mid=" + mid);
342
343                 // Hack for robustness if sort order is broken
344                 if (mid - 2 >= start &&
345                     compareIdx(token, sortCollator, mid - 1) < 0 &&
346                     compareIdx(token, sortCollator, mid - 2) < 0) {
347                     end = mid + 1;
348                 } else {
349                     start = mid + 1;
350                 }
351             }
352         }
353
354         // if the word before is the better match, move
355         // our result to it
356         if (start > 0 && start < sortedIndexEntries.size()) {
357             String prev = sortedIndexEntries.get(start - 1).normalizedToken();
358             String next = sortedIndexEntries.get(start).normalizedToken();
359             if (findMatchLen(sortCollator, token, prev) >= findMatchLen(sortCollator, token, next))
360                 start--;
361         }
362
363         // If we search for a substring of a string that's in there, return
364         // that.
365         int result = Math.min(start, sortedIndexEntries.size() - 1);
366         result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
367         return result;
368     }
369
370     private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
371         while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
372             --result;
373             if (interrupted.get()) {
374                 return result;
375             }
376         }
377         return result;
378     }
379
380     public IndexInfo getIndexInfo() {
381         return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
382     }
383
384     private static final int MAX_SEARCH_ROWS = 1000;
385
386     private final Map<String, Integer> prefixToNumRows = new HashMap<>();
387
388     private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
389             final int maxRows, final AtomicBoolean interrupted) {
390         final Integer numRows = prefixToNumRows.get(normalizedPrefix);
391         if (numRows != null) {
392             return numRows;
393         }
394         final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
395
396         int rowCount = 0;
397         for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
398             if (interrupted.get()) {
399                 return -1;
400             }
401             final IndexEntry indexEntry = sortedIndexEntries.get(index);
402             if (!indexEntry.normalizedToken.startsWith(normalizedPrefix) &&
403                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(normalizedPrefix)) {
404                 break;
405             }
406             rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
407             if (rowCount > maxRows) {
408                 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
409                 break;
410             }
411         }
412         prefixToNumRows.put(normalizedPrefix, rowCount);
413         return rowCount;
414     }
415
416     public final List<RowBase> multiWordSearch(
417         final String searchText, final List<String> searchTokens,
418         final AtomicBoolean interrupted) {
419         final long startMills = System.currentTimeMillis();
420         final List<RowBase> result = new ArrayList<>();
421
422         final Set<String> normalizedNonStoplist = new HashSet<>();
423
424         String bestPrefix = null;
425         int leastRows = Integer.MAX_VALUE;
426         final StringBuilder searchTokensRegex = new StringBuilder();
427         for (int i = 0; i < searchTokens.size(); ++i) {
428             if (interrupted.get()) {
429                 return null;
430             }
431             final String searchToken = searchTokens.get(i);
432             final String normalized = normalizeToken(searchTokens.get(i));
433             // Normalize them all.
434             searchTokens.set(i, normalized);
435
436             if (!stoplist.contains(searchToken)) {
437                 if (normalizedNonStoplist.add(normalized)) {
438                     final int numRows = getUpperBoundOnRowsStartingWith(normalized,
439                                         MAX_SEARCH_ROWS, interrupted);
440                     if (numRows != -1 && numRows < leastRows) {
441                         if (numRows == 0) {
442                             // We really are done here.
443                             return Collections.emptyList();
444                         }
445                         leastRows = numRows;
446                         bestPrefix = normalized;
447                     }
448                 }
449             }
450
451             if (searchTokensRegex.length() > 0) {
452                 searchTokensRegex.append("[\\s]*");
453             }
454             searchTokensRegex.append(Pattern.quote(normalized));
455         }
456         final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
457
458         if (bestPrefix == null) {
459             bestPrefix = searchTokens.get(0);
460             System.out.println("Everything was in the stoplist!");
461         }
462         System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
463                            + ", searchTokens=" + searchTokens);
464
465         // Place to store the things that match.
466         final Map<RowMatchType, List<RowBase>> matches = new EnumMap<>(
467                 RowMatchType.class);
468         for (final RowMatchType rowMatchType : RowMatchType.values()) {
469             if (rowMatchType != RowMatchType.NO_MATCH) {
470                 matches.put(rowMatchType, new ArrayList<RowBase>());
471             }
472         }
473
474         int matchCount = 0;
475
476         final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
477         if (exactMatchIndex != -1) {
478             final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
479             if (pattern.matcher(exactMatch.token).find()) {
480                 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
481             }
482         }
483
484         final String searchToken = bestPrefix;
485         final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
486         final Set<RowKey> rowsAlreadySeen = new HashSet<>();
487         for (int index = insertionPointIndex; index < sortedIndexEntries.size()
488                 && matchCount < MAX_SEARCH_ROWS; ++index) {
489             if (interrupted.get()) {
490                 return null;
491             }
492             final IndexEntry indexEntry = sortedIndexEntries.get(index);
493             if (!indexEntry.normalizedToken.startsWith(searchToken) &&
494                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(searchToken)) {
495                 break;
496             }
497
498             // System.out.println("Searching indexEntry: " + indexEntry.token);
499
500             // Extra +1 to skip token row.
501             for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
502                     + indexEntry.numRows
503                     && rowIndex < rows.size(); ++rowIndex) {
504                 if (interrupted.get()) {
505                     return null;
506                 }
507                 final RowBase row = rows.get(rowIndex);
508                 final RowBase.RowKey rowKey = row.getRowKey();
509                 if (rowsAlreadySeen.contains(rowKey)) {
510                     continue;
511                 }
512                 rowsAlreadySeen.add(rowKey);
513                 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
514                                                swapPairEntries);
515                 if (matchType != RowMatchType.NO_MATCH) {
516                     matches.get(matchType).add(row);
517                     ++matchCount;
518                 }
519             }
520         }
521         // } // searchTokens
522
523         // Sort them into a reasonable order.
524         final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
525             swapPairEntries);
526         for (final Collection<RowBase> rows : matches.values()) {
527             final List<RowBase> ordered = new ArrayList<>(rows);
528             Collections.sort(ordered, lengthComparator);
529             result.addAll(ordered);
530         }
531
532         System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
533         return result;
534     }
535
536     private String normalizeToken(final String searchToken) {
537         if (TransliteratorManager.init(null, null)) {
538             final Transliterator normalizer = normalizer();
539             return normalizer.transliterate(searchToken);
540         } else {
541             // Do our best since the Transliterators aren't up yet.
542             return searchToken.toLowerCase();
543         }
544     }
545
546 }