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