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 java.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.Comparator;
45 import java.util.EnumMap;
46 import java.util.HashSet;
47 import java.util.LinkedHashMap;
48 import java.util.LinkedHashSet;
49 import java.util.List;
52 import java.util.concurrent.atomic.AtomicBoolean;
53 import java.util.regex.Pattern;
55 public final class Index implements RAFSerializable<Index> {
57 static final int CACHE_SIZE = 5000;
59 public final Dictionary dict;
61 public final String shortName; // Typically the ISO code for the language.
62 public final String longName;
64 // persisted: tells how the entries are sorted.
65 public final Language sortLanguage;
66 final String normalizerRules;
68 // Built from the two above.
69 private Transliterator normalizer;
72 public final List<IndexEntry> sortedIndexEntries;
75 public final Set<String> stoplist;
80 public final List<RowBase> rows;
81 public final boolean swapPairEntries;
84 int mainTokenCount = -1;
86 // --------------------------------------------------------------------------
88 public Index(final Dictionary dict, final String shortName, final String longName,
89 final Language sortLanguage, final String normalizerRules,
90 final boolean swapPairEntries, final Set<String> stoplist) {
92 this.shortName = shortName;
93 this.longName = longName;
94 this.sortLanguage = sortLanguage;
95 this.normalizerRules = normalizerRules;
96 this.swapPairEntries = swapPairEntries;
97 sortedIndexEntries = new ArrayList<IndexEntry>();
98 this.stoplist = stoplist;
99 rows = new ArrayList<RowBase>();
105 * Deferred initialization because it can be slow.
107 public synchronized Transliterator normalizer() {
108 if (normalizer == null) {
109 normalizer = TransliteratorManager.get(normalizerRules);
115 * Note that using this comparator probably involves doing too many text
118 public NormalizeComparator getSortComparator() {
119 return new NormalizeComparator(normalizer(), sortLanguage.getCollator(), dict.dictFileVersion);
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(),
139 dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE);
140 if (dict.dictFileVersion >= 7) {
141 int count = StringUtil.readVarInt(raf);
142 stoplist = new HashSet<String>(count);
143 for (int i = 0; i < count; ++i) {
144 stoplist.add(raf.readUTF());
146 } else if (dict.dictFileVersion >= 4) {
147 stoplist = new SerializableSerializer<Set<String>>().read(raf);
149 stoplist = Collections.emptySet();
151 rows = CachingList.create(
152 UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
157 public void write(final DataOutput out) throws IOException {
158 RandomAccessFile raf = (RandomAccessFile)out;
159 raf.writeUTF(shortName);
160 raf.writeUTF(longName);
161 raf.writeUTF(sortLanguage.getIsoCode());
162 raf.writeUTF(normalizerRules);
163 raf.writeBoolean(swapPairEntries);
164 if (dict.dictFileVersion >= 2) {
165 raf.writeInt(mainTokenCount);
167 RAFList.write(raf, sortedIndexEntries, indexEntrySerializer, 32, true);
168 StringUtil.writeVarInt(raf, stoplist.size());
169 for (String i : stoplist) {
172 UniformRAFList.write(raf, rows, new RowBase.Serializer(this), 3 /* bytes per entry */);
175 public void print(final PrintStream out) {
176 for (final RowBase row : rows) {
181 private final RAFSerializer<IndexEntry> indexEntrySerializer = new RAFSerializer<IndexEntry>() {
183 public IndexEntry read(DataInput raf) throws IOException {
184 return new IndexEntry(Index.this, raf);
188 public void write(DataOutput raf, IndexEntry t) throws IOException {
193 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
194 public final String token;
195 private final String normalizedToken;
196 public final int startRow;
197 public final int numRows; // doesn't count the token row!
198 public List<HtmlEntry> htmlEntries;
200 public IndexEntry(final Index index, final String token, final String normalizedToken,
201 final int startRow, final int numRows) {
202 assert token.equals(token.trim());
203 assert token.length() > 0;
205 this.normalizedToken = normalizedToken;
206 this.startRow = startRow;
207 this.numRows = numRows;
208 this.htmlEntries = new ArrayList<HtmlEntry>();
211 public IndexEntry(final Index index, final DataInput raf) throws IOException {
212 token = raf.readUTF();
213 if (index.dict.dictFileVersion >= 7) {
214 startRow = StringUtil.readVarInt(raf);
215 numRows = StringUtil.readVarInt(raf);
217 startRow = raf.readInt();
218 numRows = raf.readInt();
220 final boolean hasNormalizedForm = raf.readBoolean();
221 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
222 if (index.dict.dictFileVersion >= 7) {
223 int size = StringUtil.readVarInt(raf);
224 final int[] 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,
242 index.dict.dictInfo + " htmlEntries: "), 1);
244 this.htmlEntries = Collections.emptyList();
248 public void write(DataOutput raf) throws IOException {
250 StringUtil.writeVarInt(raf, startRow);
251 StringUtil.writeVarInt(raf, numRows);
252 final boolean hasNormalizedForm = !token.equals(normalizedToken);
253 raf.writeBoolean(hasNormalizedForm);
254 if (hasNormalizedForm) {
255 raf.writeUTF(normalizedToken);
257 StringUtil.writeVarInt(raf, htmlEntries.size());
258 for (HtmlEntry e : htmlEntries)
259 StringUtil.writeVarInt(raf, e.index());
262 public String toString() {
263 return String.format("%s@%d(%d)", token, startRow, numRows);
266 public String normalizedToken() {
267 return normalizedToken;
271 static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
273 public String transform(IndexEntry t1) {
278 public IndexEntry findExact(final String exactToken) {
279 final int result = Collections.binarySearch(
280 TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
281 getSortComparator());
283 return sortedIndexEntries.get(result);
288 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
289 final int index = findInsertionPointIndex(token, interrupted);
290 return index != -1 ? sortedIndexEntries.get(index) : null;
293 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
294 token = normalizeToken(token);
297 int end = sortedIndexEntries.size();
299 final Comparator sortCollator = sortLanguage.getCollator();
300 while (start < end) {
301 final int mid = (start + end) / 2;
302 if (interrupted.get()) {
305 final IndexEntry midEntry = sortedIndexEntries.get(mid);
307 int comp = NormalizeComparator.compareWithoutDash(token, midEntry.normalizedToken(), sortCollator, dict.dictFileVersion);
309 comp = sortCollator.compare(token, midEntry.normalizedToken());
311 final int result = windBackCase(token, mid, interrupted);
313 } else if (comp < 0) {
314 // System.out.println("Upper bound: " + midEntry + ", norm=" +
315 // midEntry.normalizedToken() + ", mid=" + mid);
318 // System.out.println("Lower bound: " + midEntry + ", norm=" +
319 // midEntry.normalizedToken() + ", mid=" + mid);
324 // If we search for a substring of a string that's in there, return
326 int result = Math.min(start, sortedIndexEntries.size() - 1);
327 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
331 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
332 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
334 if (interrupted.get()) {
341 public IndexInfo getIndexInfo() {
342 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
345 private static final int MAX_SEARCH_ROWS = 1000;
347 private final Map<String, Integer> prefixToNumRows = new LinkedHashMap<String, Integer>();
349 private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
350 final int maxRows, final AtomicBoolean interrupted) {
351 final Integer numRows = prefixToNumRows.get(normalizedPrefix);
352 if (numRows != null) {
355 final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
358 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
359 if (interrupted.get()) {
362 final IndexEntry indexEntry = sortedIndexEntries.get(index);
363 if (!indexEntry.normalizedToken.startsWith(normalizedPrefix)) {
366 rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
367 if (rowCount > maxRows) {
368 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
372 prefixToNumRows.put(normalizedPrefix, numRows);
376 public final List<RowBase> multiWordSearch(
377 final String searchText, final List<String> searchTokens,
378 final AtomicBoolean interrupted) {
379 final long startMills = System.currentTimeMillis();
380 final List<RowBase> result = new ArrayList<RowBase>();
382 final Set<String> normalizedNonStoplist = new LinkedHashSet<String>();
384 String bestPrefix = null;
385 int leastRows = Integer.MAX_VALUE;
386 final StringBuilder searchTokensRegex = new StringBuilder();
387 for (int i = 0; i < searchTokens.size(); ++i) {
388 if (interrupted.get()) {
391 final String searchToken = searchTokens.get(i);
392 final String normalized = normalizeToken(searchTokens.get(i));
393 // Normalize them all.
394 searchTokens.set(i, normalized);
396 if (!stoplist.contains(searchToken)) {
397 if (normalizedNonStoplist.add(normalized)) {
398 final int numRows = getUpperBoundOnRowsStartingWith(normalized,
399 MAX_SEARCH_ROWS, interrupted);
400 if (numRows != -1 && numRows < leastRows) {
402 // We really are done here.
403 return Collections.emptyList();
406 bestPrefix = normalized;
411 if (searchTokensRegex.length() > 0) {
412 searchTokensRegex.append("[\\s]*");
414 searchTokensRegex.append(Pattern.quote(normalized));
416 final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
418 if (bestPrefix == null) {
419 bestPrefix = searchTokens.get(0);
420 System.out.println("Everything was in the stoplist!");
422 System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
423 + ", searchTokens=" + searchTokens);
425 // Place to store the things that match.
426 final Map<RowMatchType, List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(
428 for (final RowMatchType rowMatchType : RowMatchType.values()) {
429 if (rowMatchType != RowMatchType.NO_MATCH) {
430 matches.put(rowMatchType, new ArrayList<RowBase>());
436 final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
437 if (exactMatchIndex != -1) {
438 final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
439 if (pattern.matcher(exactMatch.token).find()) {
440 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
444 final String searchToken = bestPrefix;
445 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
446 final Set<RowKey> rowsAlreadySeen = new HashSet<RowBase.RowKey>();
447 for (int index = insertionPointIndex; index < sortedIndexEntries.size()
448 && matchCount < MAX_SEARCH_ROWS; ++index) {
449 if (interrupted.get()) {
452 final IndexEntry indexEntry = sortedIndexEntries.get(index);
453 if (!indexEntry.normalizedToken.startsWith(searchToken)) {
457 // System.out.println("Searching indexEntry: " + indexEntry.token);
459 // Extra +1 to skip token row.
460 for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
462 && rowIndex < rows.size(); ++rowIndex) {
463 if (interrupted.get()) {
466 final RowBase row = rows.get(rowIndex);
467 final RowBase.RowKey rowKey = row.getRowKey();
468 if (rowsAlreadySeen.contains(rowKey)) {
471 rowsAlreadySeen.add(rowKey);
472 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
474 if (matchType != RowMatchType.NO_MATCH) {
475 matches.get(matchType).add(row);
482 // Sort them into a reasonable order.
483 final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
485 for (final Collection<RowBase> rows : matches.values()) {
486 final List<RowBase> ordered = new ArrayList<RowBase>(rows);
487 Collections.sort(ordered, lengthComparator);
488 result.addAll(ordered);
491 System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
495 private String normalizeToken(final String searchToken) {
496 if (TransliteratorManager.init(null)) {
497 final Transliterator normalizer = normalizer();
498 return normalizer.transliterate(searchToken);
500 // Do our best since the Transliterators aren't up yet.
501 return searchToken.toLowerCase();