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