1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 package com.hughes.android.dictionary.engine;
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;
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;
51 import java.util.concurrent.atomic.AtomicBoolean;
52 import java.util.regex.Pattern;
54 public final class Index implements RAFSerializable<Index> {
56 static final int CACHE_SIZE = 5000;
58 public final Dictionary dict;
60 public final String shortName; // Typically the ISO code for the language.
61 public final String longName;
63 // persisted: tells how the entries are sorted.
64 public final Language sortLanguage;
65 final String normalizerRules;
67 // Built from the two above.
68 private Transliterator normalizer;
71 public final List<IndexEntry> sortedIndexEntries;
74 public final Set<String> stoplist;
79 public final List<RowBase> rows;
80 public final boolean swapPairEntries;
83 int mainTokenCount = -1;
85 // --------------------------------------------------------------------------
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) {
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>();
104 * Deferred initialization because it can be slow.
106 public synchronized Transliterator normalizer() {
107 if (normalizer == null) {
108 normalizer = Transliterator
109 .createFromRules("", normalizerRules, Transliterator.FORWARD);
115 * Note that using this comparator probably involves doing too many text
118 public NormalizeComparator getSortComparator() {
119 return new NormalizeComparator(normalizer(), sortLanguage.getCollator());
122 public Index(final Dictionary dict, final DataInput inp) throws IOException {
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);
134 if (dict.dictFileVersion >= 2) {
135 mainTokenCount = raf.readInt();
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);
143 stoplist = Collections.emptySet();
145 rows = CachingList.create(
146 UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
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);
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), 5 /*
170 public void print(final PrintStream out) {
171 for (final RowBase row : rows) {
176 private final RAFSerializer<IndexEntry> indexEntrySerializer = new RAFSerializer<IndexEntry>() {
178 public IndexEntry read(DataInput raf) throws IOException {
179 return new IndexEntry(Index.this, raf);
183 public void write(DataOutput raf, IndexEntry t) throws IOException {
188 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
189 private final Index index;
190 public final String token;
191 private final String normalizedToken;
192 public final int startRow;
193 public final int numRows; // doesn't count the token row!
194 public List<HtmlEntry> htmlEntries;
195 private int[] htmlEntryIndices;
197 public IndexEntry(final Index index, final String token, final String normalizedToken,
198 final int startRow, final int numRows) {
200 assert token.equals(token.trim());
201 assert token.length() > 0;
203 this.normalizedToken = normalizedToken;
204 this.startRow = startRow;
205 this.numRows = numRows;
206 this.htmlEntries = new ArrayList<HtmlEntry>();
209 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);
216 startRow = raf.readInt();
217 numRows = raf.readInt();
219 final boolean hasNormalizedForm = raf.readBoolean();
220 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
221 htmlEntryIndices = null;
222 if (index.dict.dictFileVersion >= 7) {
223 int size = StringUtil.readVarInt(raf);
224 htmlEntryIndices = new int[size];
225 for (int i = 0; i < size; ++i) {
226 htmlEntryIndices[i] = StringUtil.readVarInt(raf);
228 this.htmlEntries = CachingList.create(new AbstractList<HtmlEntry>() {
230 public HtmlEntry get(int i) {
231 return index.dict.htmlEntries.get(htmlEntryIndices[i]);
235 return htmlEntryIndices.length;
238 } else if (index.dict.dictFileVersion >= 6) {
239 this.htmlEntries = CachingList.create(
240 RAFList.create((RandomAccessFile)raf, index.dict.htmlEntryIndexSerializer,
241 ((RandomAccessFile)raf).getFilePointer(), index.dict.dictFileVersion), 1);
243 this.htmlEntries = Collections.emptyList();
247 public void write(DataOutput raf) throws IOException {
249 StringUtil.writeVarInt(raf, startRow);
250 StringUtil.writeVarInt(raf, numRows);
251 final boolean hasNormalizedForm = !token.equals(normalizedToken);
252 raf.writeBoolean(hasNormalizedForm);
253 if (hasNormalizedForm) {
254 raf.writeUTF(normalizedToken);
256 StringUtil.writeVarInt(raf, htmlEntries.size());
257 for (HtmlEntry e : htmlEntries)
258 StringUtil.writeVarInt(raf, e.index());
261 public String toString() {
262 return String.format("%s@%d(%d)", token, startRow, numRows);
265 public String normalizedToken() {
266 return normalizedToken;
270 static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
272 public String transform(IndexEntry t1) {
277 public IndexEntry findExact(final String exactToken) {
278 final int result = Collections.binarySearch(
279 TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
280 getSortComparator());
282 return sortedIndexEntries.get(result);
287 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
288 final int index = findInsertionPointIndex(token, interrupted);
289 return index != -1 ? sortedIndexEntries.get(index) : null;
292 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
293 token = normalizeToken(token);
296 int end = sortedIndexEntries.size();
298 final Collator sortCollator = sortLanguage.getCollator();
299 while (start < end) {
300 final int mid = (start + end) / 2;
301 if (interrupted.get()) {
304 final IndexEntry midEntry = sortedIndexEntries.get(mid);
306 final int comp = sortCollator.compare(token, midEntry.normalizedToken());
308 final int result = windBackCase(token, mid, interrupted);
310 } else if (comp < 0) {
311 // System.out.println("Upper bound: " + midEntry + ", norm=" +
312 // midEntry.normalizedToken() + ", mid=" + mid);
315 // System.out.println("Lower bound: " + midEntry + ", norm=" +
316 // midEntry.normalizedToken() + ", mid=" + mid);
321 // If we search for a substring of a string that's in there, return
323 int result = Math.min(start, sortedIndexEntries.size() - 1);
324 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
328 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
329 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
331 if (interrupted.get()) {
338 public IndexInfo getIndexInfo() {
339 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
342 private static final int MAX_SEARCH_ROWS = 1000;
344 private final Map<String, Integer> prefixToNumRows = new LinkedHashMap<String, Integer>();
346 private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
347 final int maxRows, final AtomicBoolean interrupted) {
348 final Integer numRows = prefixToNumRows.get(normalizedPrefix);
349 if (numRows != null) {
352 final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
355 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
356 if (interrupted.get()) {
359 final IndexEntry indexEntry = sortedIndexEntries.get(index);
360 if (!indexEntry.normalizedToken.startsWith(normalizedPrefix)) {
363 rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
364 if (rowCount > maxRows) {
365 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
369 prefixToNumRows.put(normalizedPrefix, numRows);
373 public final List<RowBase> multiWordSearch(
374 final String searchText, final List<String> searchTokens,
375 final AtomicBoolean interrupted) {
376 final long startMills = System.currentTimeMillis();
377 final List<RowBase> result = new ArrayList<RowBase>();
379 final Set<String> normalizedNonStoplist = new LinkedHashSet<String>();
381 String bestPrefix = null;
382 int leastRows = Integer.MAX_VALUE;
383 final StringBuilder searchTokensRegex = new StringBuilder();
384 for (int i = 0; i < searchTokens.size(); ++i) {
385 if (interrupted.get()) {
388 final String searchToken = searchTokens.get(i);
389 final String normalized = normalizeToken(searchTokens.get(i));
390 // Normalize them all.
391 searchTokens.set(i, normalized);
393 if (!stoplist.contains(searchToken)) {
394 if (normalizedNonStoplist.add(normalized)) {
395 final int numRows = getUpperBoundOnRowsStartingWith(normalized,
396 MAX_SEARCH_ROWS, interrupted);
397 if (numRows != -1 && numRows < leastRows) {
399 // We really are done here.
400 return Collections.emptyList();
403 bestPrefix = normalized;
408 if (searchTokensRegex.length() > 0) {
409 searchTokensRegex.append("[\\s]*");
411 searchTokensRegex.append(Pattern.quote(normalized));
413 final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
415 if (bestPrefix == null) {
416 bestPrefix = searchTokens.get(0);
417 System.out.println("Everything was in the stoplist!");
419 System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
420 + ", searchTokens=" + searchTokens);
422 // Place to store the things that match.
423 final Map<RowMatchType, List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(
425 for (final RowMatchType rowMatchType : RowMatchType.values()) {
426 if (rowMatchType != RowMatchType.NO_MATCH) {
427 matches.put(rowMatchType, new ArrayList<RowBase>());
433 final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
434 if (exactMatchIndex != -1) {
435 final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
436 if (pattern.matcher(exactMatch.token).find()) {
437 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
441 final String searchToken = bestPrefix;
442 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
443 final Set<RowKey> rowsAlreadySeen = new HashSet<RowBase.RowKey>();
444 for (int index = insertionPointIndex; index < sortedIndexEntries.size()
445 && matchCount < MAX_SEARCH_ROWS; ++index) {
446 if (interrupted.get()) {
449 final IndexEntry indexEntry = sortedIndexEntries.get(index);
450 if (!indexEntry.normalizedToken.startsWith(searchToken)) {
454 // System.out.println("Searching indexEntry: " + indexEntry.token);
456 // Extra +1 to skip token row.
457 for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
459 && rowIndex < rows.size(); ++rowIndex) {
460 if (interrupted.get()) {
463 final RowBase row = rows.get(rowIndex);
464 final RowBase.RowKey rowKey = row.getRowKey();
465 if (rowsAlreadySeen.contains(rowKey)) {
468 rowsAlreadySeen.add(rowKey);
469 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
471 if (matchType != RowMatchType.NO_MATCH) {
472 matches.get(matchType).add(row);
479 // Sort them into a reasonable order.
480 final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
482 for (final Collection<RowBase> rows : matches.values()) {
483 final List<RowBase> ordered = new ArrayList<RowBase>(rows);
484 Collections.sort(ordered, lengthComparator);
485 result.addAll(ordered);
488 System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
492 private String normalizeToken(final String searchToken) {
493 if (TransliteratorManager.init(null)) {
494 final Transliterator normalizer = normalizer();
495 return normalizer.transliterate(searchToken);
497 // Do our best since the Transliterators aren't up yet.
498 return searchToken.toLowerCase();