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.TransformingList;
26 import com.hughes.util.raf.RAFList;
27 import com.hughes.util.raf.RAFSerializable;
28 import com.hughes.util.raf.RAFSerializer;
29 import com.hughes.util.raf.SerializableSerializer;
30 import com.hughes.util.raf.UniformRAFList;
31 import com.ibm.icu.text.Collator;
32 import com.ibm.icu.text.Transliterator;
34 import java.io.DataInput;
35 import java.io.DataOutput;
36 import java.io.IOException;
37 import java.io.PrintStream;
38 import java.io.RandomAccessFile;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.EnumMap;
43 import java.util.HashSet;
44 import java.util.LinkedHashMap;
45 import java.util.LinkedHashSet;
46 import java.util.List;
49 import java.util.concurrent.atomic.AtomicBoolean;
50 import java.util.regex.Pattern;
52 public final class Index implements RAFSerializable<Index> {
54 static final int CACHE_SIZE = 5000;
56 public final Dictionary dict;
58 public final String shortName; // Typically the ISO code for the language.
59 public final String longName;
61 // persisted: tells how the entries are sorted.
62 public final Language sortLanguage;
63 final String normalizerRules;
65 // Built from the two above.
66 private Transliterator normalizer;
69 public final List<IndexEntry> sortedIndexEntries;
72 public final Set<String> stoplist;
77 public final List<RowBase> rows;
78 public final boolean swapPairEntries;
81 int mainTokenCount = -1;
83 // --------------------------------------------------------------------------
85 public Index(final Dictionary dict, final String shortName, final String longName,
86 final Language sortLanguage, final String normalizerRules,
87 final boolean swapPairEntries, final Set<String> stoplist) {
89 this.shortName = shortName;
90 this.longName = longName;
91 this.sortLanguage = sortLanguage;
92 this.normalizerRules = normalizerRules;
93 this.swapPairEntries = swapPairEntries;
94 sortedIndexEntries = new ArrayList<IndexEntry>();
95 this.stoplist = stoplist;
96 rows = new ArrayList<RowBase>();
102 * Deferred initialization because it can be slow.
104 public synchronized Transliterator normalizer() {
105 if (normalizer == null) {
106 normalizer = Transliterator
107 .createFromRules("", normalizerRules, Transliterator.FORWARD);
113 * Note that using this comparator probably involves doing too many text
116 public NormalizeComparator getSortComparator() {
117 return new NormalizeComparator(normalizer(), sortLanguage.getCollator());
120 public Index(final Dictionary dict, final DataInput inp) throws IOException {
122 RandomAccessFile raf = (RandomAccessFile)inp;
123 shortName = raf.readUTF();
124 longName = raf.readUTF();
125 final String languageCode = raf.readUTF();
126 sortLanguage = Language.lookup(languageCode);
127 normalizerRules = raf.readUTF();
128 swapPairEntries = raf.readBoolean();
129 if (sortLanguage == null) {
130 throw new IOException("Unsupported language: " + languageCode);
132 if (dict.dictFileVersion >= 2) {
133 mainTokenCount = raf.readInt();
135 sortedIndexEntries = CachingList.create(
136 RAFList.create(raf, indexEntrySerializer, raf.getFilePointer()), CACHE_SIZE);
137 if (dict.dictFileVersion >= 4) {
138 stoplist = new SerializableSerializer<Set<String>>().read(raf);
140 stoplist = Collections.emptySet();
142 rows = CachingList.create(
143 UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()),
148 public void write(final DataOutput out) throws IOException {
149 RandomAccessFile raf = (RandomAccessFile)out;
150 raf.writeUTF(shortName);
151 raf.writeUTF(longName);
152 raf.writeUTF(sortLanguage.getIsoCode());
153 raf.writeUTF(normalizerRules);
154 raf.writeBoolean(swapPairEntries);
155 if (dict.dictFileVersion >= 2) {
156 raf.writeInt(mainTokenCount);
158 RAFList.write(raf, sortedIndexEntries, indexEntrySerializer);
159 new SerializableSerializer<Set<String>>().write(raf, stoplist);
160 UniformRAFList.write(raf, rows, new RowBase.Serializer(this), 5 /*
167 public void print(final PrintStream out) {
168 for (final RowBase row : rows) {
173 private final RAFSerializer<IndexEntry> indexEntrySerializer = new RAFSerializer<IndexEntry>() {
175 public IndexEntry read(DataInput raf) throws IOException {
176 return new IndexEntry(Index.this, raf);
180 public void write(DataOutput raf, IndexEntry t) throws IOException {
185 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
186 private final Index index;
187 public final String token;
188 private final String normalizedToken;
189 public final int startRow;
190 public final int numRows; // doesn't count the token row!
191 public final List<HtmlEntry> htmlEntries;
193 public IndexEntry(final Index index, final String token, final String normalizedToken,
194 final int startRow, final int numRows) {
196 assert token.equals(token.trim());
197 assert token.length() > 0;
199 this.normalizedToken = normalizedToken;
200 this.startRow = startRow;
201 this.numRows = numRows;
202 this.htmlEntries = new ArrayList<HtmlEntry>();
205 public IndexEntry(final Index index, final DataInput inp) throws IOException {
207 RandomAccessFile raf = (RandomAccessFile)inp;
208 token = raf.readUTF();
209 startRow = raf.readInt();
210 numRows = raf.readInt();
211 final boolean hasNormalizedForm = raf.readBoolean();
212 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
213 if (index.dict.dictFileVersion >= 6) {
214 this.htmlEntries = CachingList.create(
215 RAFList.create(raf, index.dict.htmlEntryIndexSerializer,
216 raf.getFilePointer()), 1);
218 this.htmlEntries = Collections.emptyList();
222 public void write(DataOutput out) throws IOException {
223 RandomAccessFile raf = (RandomAccessFile)out;
225 raf.writeInt(startRow);
226 raf.writeInt(numRows);
227 final boolean hasNormalizedForm = !token.equals(normalizedToken);
228 raf.writeBoolean(hasNormalizedForm);
229 if (hasNormalizedForm) {
230 raf.writeUTF(normalizedToken);
232 RAFList.write(raf, htmlEntries, index.dict.htmlEntryIndexSerializer);
235 public String toString() {
236 return String.format("%s@%d(%d)", token, startRow, numRows);
239 public String normalizedToken() {
240 return normalizedToken;
244 static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
246 public String transform(IndexEntry t1) {
251 public IndexEntry findExact(final String exactToken) {
252 final int result = Collections.binarySearch(
253 TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
254 getSortComparator());
256 return sortedIndexEntries.get(result);
261 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
262 final int index = findInsertionPointIndex(token, interrupted);
263 return index != -1 ? sortedIndexEntries.get(index) : null;
266 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
267 token = normalizeToken(token);
270 int end = sortedIndexEntries.size();
272 final Collator sortCollator = sortLanguage.getCollator();
273 while (start < end) {
274 final int mid = (start + end) / 2;
275 if (interrupted.get()) {
278 final IndexEntry midEntry = sortedIndexEntries.get(mid);
280 final int comp = sortCollator.compare(token, midEntry.normalizedToken());
282 final int result = windBackCase(token, mid, interrupted);
284 } else if (comp < 0) {
285 // System.out.println("Upper bound: " + midEntry + ", norm=" +
286 // midEntry.normalizedToken() + ", mid=" + mid);
289 // System.out.println("Lower bound: " + midEntry + ", norm=" +
290 // midEntry.normalizedToken() + ", mid=" + mid);
295 // If we search for a substring of a string that's in there, return
297 int result = Math.min(start, sortedIndexEntries.size() - 1);
298 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
302 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
303 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
305 if (interrupted.get()) {
312 public IndexInfo getIndexInfo() {
313 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
316 private static final int MAX_SEARCH_ROWS = 1000;
318 private final Map<String, Integer> prefixToNumRows = new LinkedHashMap<String, Integer>();
320 private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
321 final int maxRows, final AtomicBoolean interrupted) {
322 final Integer numRows = prefixToNumRows.get(normalizedPrefix);
323 if (numRows != null) {
326 final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
329 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
330 if (interrupted.get()) {
333 final IndexEntry indexEntry = sortedIndexEntries.get(index);
334 if (!indexEntry.normalizedToken.startsWith(normalizedPrefix)) {
337 rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
338 if (rowCount > maxRows) {
339 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
343 prefixToNumRows.put(normalizedPrefix, numRows);
347 public final List<RowBase> multiWordSearch(
348 final String searchText, final List<String> searchTokens,
349 final AtomicBoolean interrupted) {
350 final long startMills = System.currentTimeMillis();
351 final List<RowBase> result = new ArrayList<RowBase>();
353 final Set<String> normalizedNonStoplist = new LinkedHashSet<String>();
355 String bestPrefix = null;
356 int leastRows = Integer.MAX_VALUE;
357 final StringBuilder searchTokensRegex = new StringBuilder();
358 for (int i = 0; i < searchTokens.size(); ++i) {
359 if (interrupted.get()) {
362 final String searchToken = searchTokens.get(i);
363 final String normalized = normalizeToken(searchTokens.get(i));
364 // Normalize them all.
365 searchTokens.set(i, normalized);
367 if (!stoplist.contains(searchToken)) {
368 if (normalizedNonStoplist.add(normalized)) {
369 final int numRows = getUpperBoundOnRowsStartingWith(normalized,
370 MAX_SEARCH_ROWS, interrupted);
371 if (numRows != -1 && numRows < leastRows) {
373 // We really are done here.
374 return Collections.emptyList();
377 bestPrefix = normalized;
382 if (searchTokensRegex.length() > 0) {
383 searchTokensRegex.append("[\\s]*");
385 searchTokensRegex.append(Pattern.quote(normalized));
387 final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
389 if (bestPrefix == null) {
390 bestPrefix = searchTokens.get(0);
391 System.out.println("Everything was in the stoplist!");
393 System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
394 + ", searchTokens=" + searchTokens);
396 // Place to store the things that match.
397 final Map<RowMatchType, List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(
399 for (final RowMatchType rowMatchType : RowMatchType.values()) {
400 if (rowMatchType != RowMatchType.NO_MATCH) {
401 matches.put(rowMatchType, new ArrayList<RowBase>());
407 final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
408 if (exactMatchIndex != -1) {
409 final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
410 if (pattern.matcher(exactMatch.token).find()) {
411 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
415 final String searchToken = bestPrefix;
416 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
417 final Set<RowKey> rowsAlreadySeen = new HashSet<RowBase.RowKey>();
418 for (int index = insertionPointIndex; index < sortedIndexEntries.size()
419 && matchCount < MAX_SEARCH_ROWS; ++index) {
420 if (interrupted.get()) {
423 final IndexEntry indexEntry = sortedIndexEntries.get(index);
424 if (!indexEntry.normalizedToken.startsWith(searchToken)) {
428 // System.out.println("Searching indexEntry: " + indexEntry.token);
430 // Extra +1 to skip token row.
431 for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
433 && rowIndex < rows.size(); ++rowIndex) {
434 if (interrupted.get()) {
437 final RowBase row = rows.get(rowIndex);
438 final RowBase.RowKey rowKey = row.getRowKey();
439 if (rowsAlreadySeen.contains(rowKey)) {
442 rowsAlreadySeen.add(rowKey);
443 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
445 if (matchType != RowMatchType.NO_MATCH) {
446 matches.get(matchType).add(row);
453 // Sort them into a reasonable order.
454 final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
456 for (final Collection<RowBase> rows : matches.values()) {
457 final List<RowBase> ordered = new ArrayList<RowBase>(rows);
458 Collections.sort(ordered, lengthComparator);
459 result.addAll(ordered);
462 System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
466 private String normalizeToken(final String searchToken) {
467 if (TransliteratorManager.init(null)) {
468 final Transliterator normalizer = normalizer();
469 return normalizer.transliterate(searchToken);
471 // Do our best since the Transliterators aren't up yet.
472 return searchToken.toLowerCase();