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.
18 package com.hughes.android.dictionary.engine;
20 import com.hughes.android.dictionary.DictionaryInfo;
21 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
22 import com.hughes.android.dictionary.engine.RowBase.RowKey;
23 import com.hughes.util.CachingList;
24 import com.hughes.util.CollectionUtil;
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.IOException;
35 import java.io.PrintStream;
36 import java.io.RandomAccessFile;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.EnumMap;
41 import java.util.HashSet;
42 import java.util.LinkedHashMap;
43 import java.util.LinkedHashSet;
44 import java.util.List;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 import java.util.regex.Pattern;
50 public final class Index implements RAFSerializable<Index> {
52 static final int CACHE_SIZE = 5000;
54 public final Dictionary dict;
56 public final String shortName; // Typically the ISO code for the language.
57 public final String longName;
59 // persisted: tells how the entries are sorted.
60 public final Language sortLanguage;
61 final String normalizerRules;
63 // Built from the two above.
64 private Transliterator normalizer;
67 public final List<IndexEntry> sortedIndexEntries;
70 public final Set<String> stoplist;
75 public final List<RowBase> rows;
76 public final boolean swapPairEntries;
79 int mainTokenCount = -1;
81 // --------------------------------------------------------------------------
83 public Index(final Dictionary dict, final String shortName, final String longName, final Language sortLanguage, final String normalizerRules, final boolean swapPairEntries, final Set<String> stoplist) {
85 this.shortName = shortName;
86 this.longName = longName;
87 this.sortLanguage = sortLanguage;
88 this.normalizerRules = normalizerRules;
89 this.swapPairEntries = swapPairEntries;
90 sortedIndexEntries = new ArrayList<IndexEntry>();
91 this.stoplist = stoplist;
92 rows = new ArrayList<RowBase>();
98 * Deferred initialization because it can be slow.
100 public synchronized Transliterator normalizer() {
101 if (normalizer == null) {
102 normalizer = Transliterator.createFromRules("", normalizerRules, Transliterator.FORWARD);
108 * Note that using this comparator probably involves doing too many text normalizations.
110 public NormalizeComparator getSortComparator() {
111 return new NormalizeComparator(normalizer(), sortLanguage.getCollator());
114 public Index(final Dictionary dict, final RandomAccessFile raf) throws IOException {
116 shortName = raf.readUTF();
117 longName = raf.readUTF();
118 final String languageCode = raf.readUTF();
119 sortLanguage = Language.lookup(languageCode);
120 normalizerRules = raf.readUTF();
121 swapPairEntries = raf.readBoolean();
122 if (sortLanguage == null) {
123 throw new IOException("Unsupported language: " + languageCode);
125 if (dict.dictFileVersion >= 2) {
126 mainTokenCount = raf.readInt();
128 sortedIndexEntries = CachingList.create(RAFList.create(raf, indexEntrySerializer, raf.getFilePointer()), CACHE_SIZE);
129 if (dict.dictFileVersion >= 4) {
130 stoplist = new SerializableSerializer<Set<String>>().read(raf);
132 stoplist = Collections.emptySet();
134 rows = CachingList.create(UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()), CACHE_SIZE);
138 public void write(final RandomAccessFile raf) throws IOException {
139 raf.writeUTF(shortName);
140 raf.writeUTF(longName);
141 raf.writeUTF(sortLanguage.getIsoCode());
142 raf.writeUTF(normalizerRules);
143 raf.writeBoolean(swapPairEntries);
144 if (dict.dictFileVersion >= 2) {
145 raf.writeInt(mainTokenCount);
147 RAFList.write(raf, sortedIndexEntries, indexEntrySerializer);
148 new SerializableSerializer<Set<String>>().write(raf, stoplist);
149 UniformRAFList.write(raf, (Collection<RowBase>) rows, new RowBase.Serializer(this), 5 /* bytes per entry */);
152 public void print(final PrintStream out) {
153 for (final RowBase row : rows) {
158 private final RAFSerializer<IndexEntry> indexEntrySerializer = new RAFSerializer<IndexEntry> () {
160 public IndexEntry read(RandomAccessFile raf) throws IOException {
161 return new IndexEntry(Index.this, raf);
164 public void write(RandomAccessFile raf, IndexEntry t) throws IOException {
169 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
170 private final Index index;
171 public final String token;
172 private final String normalizedToken;
173 public final int startRow;
174 public final int numRows; // doesn't count the token row!
175 public final List<HtmlEntry> htmlEntries;
178 public IndexEntry(final Index index, final String token, final String normalizedToken, final int startRow, final int numRows) {
180 assert token.equals(token.trim());
181 assert token.length() > 0;
183 this.normalizedToken = normalizedToken;
184 this.startRow = startRow;
185 this.numRows = numRows;
186 this.htmlEntries = new ArrayList<HtmlEntry>();
189 public IndexEntry(final Index index, final RandomAccessFile raf) throws IOException {
191 token = raf.readUTF();
192 startRow = raf.readInt();
193 numRows = raf.readInt();
194 final boolean hasNormalizedForm = raf.readBoolean();
195 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
196 if (index.dict.dictFileVersion >= 6) {
197 this.htmlEntries = CachingList.create(RAFList.create(raf, index.dict.htmlEntryIndexSerializer, raf.getFilePointer()), 1);
199 this.htmlEntries = Collections.emptyList();
203 public void write(RandomAccessFile raf) throws IOException {
205 raf.writeInt(startRow);
206 raf.writeInt(numRows);
207 final boolean hasNormalizedForm = !token.equals(normalizedToken);
208 raf.writeBoolean(hasNormalizedForm);
209 if (hasNormalizedForm) {
210 raf.writeUTF(normalizedToken);
212 RAFList.write(raf, htmlEntries, index.dict.htmlEntryIndexSerializer);
215 public String toString() {
216 return String.format("%s@%d(%d)", token, startRow, numRows);
219 public String normalizedToken() {
220 return normalizedToken;
224 static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
226 public String transform(IndexEntry t1) {
231 public IndexEntry findExact(final String exactToken) {
232 final int result = Collections.binarySearch(TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken, getSortComparator());
234 return sortedIndexEntries.get(result);
239 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
240 final int index = findInsertionPointIndex(token, interrupted);
241 return index != -1 ? sortedIndexEntries.get(index) : null;
244 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
245 token = normalizeToken(token);
248 int end = sortedIndexEntries.size();
250 final Collator sortCollator = sortLanguage.getCollator();
251 while (start < end) {
252 final int mid = (start + end) / 2;
253 if (interrupted.get()) {
256 final IndexEntry midEntry = sortedIndexEntries.get(mid);
258 final int comp = sortCollator.compare(token, midEntry.normalizedToken());
260 final int result = windBackCase(token, mid, interrupted);
262 } else if (comp < 0) {
263 // System.out.println("Upper bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
266 // System.out.println("Lower bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
271 // If we search for a substring of a string that's in there, return that.
272 int result = Math.min(start, sortedIndexEntries.size() - 1);
273 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
277 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
278 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
280 if (interrupted.get()) {
287 public IndexInfo getIndexInfo() {
288 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
291 private static final int MAX_SEARCH_ROWS = 1000;
293 private final Map<String,Integer> prefixToNumRows = new LinkedHashMap<String, Integer>();
294 private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix, final int maxRows, final AtomicBoolean interrupted) {
295 final Integer numRows = prefixToNumRows.get(normalizedPrefix);
296 if (numRows != null) {
299 final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
302 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
303 if (interrupted.get()) { return -1; }
304 final IndexEntry indexEntry = sortedIndexEntries.get(index);
305 if (!indexEntry.normalizedToken.startsWith(normalizedPrefix)) {
308 rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
309 if (rowCount > maxRows) {
310 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
314 prefixToNumRows.put(normalizedPrefix, numRows);
319 public final List<RowBase> multiWordSearch(
320 final String searchText, final List<String> searchTokens, final AtomicBoolean interrupted) {
321 final long startMills = System.currentTimeMillis();
322 final List<RowBase> result = new ArrayList<RowBase>();
324 final Set<String> normalizedNonStoplist = new LinkedHashSet<String>();
326 String bestPrefix = null;
327 int leastRows = Integer.MAX_VALUE;
328 final StringBuilder searchTokensRegex = new StringBuilder();
329 for (int i = 0; i < searchTokens.size(); ++i) {
330 if (interrupted.get()) { return null; }
331 final String searchToken = searchTokens.get(i);
332 final String normalized = normalizeToken(searchTokens.get(i));
333 // Normalize them all.
334 searchTokens.set(i, normalized);
336 if (!stoplist.contains(searchToken)) {
337 if (normalizedNonStoplist.add(normalized)) {
338 final int numRows = getUpperBoundOnRowsStartingWith(normalized, MAX_SEARCH_ROWS, interrupted);
339 if (numRows != -1 && numRows < leastRows) {
341 // We really are done here.
342 return Collections.emptyList();
345 bestPrefix = normalized;
350 if (searchTokensRegex.length() > 0) {
351 searchTokensRegex.append("[\\s]*");
353 searchTokensRegex.append(Pattern.quote(normalized));
355 final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
357 if (bestPrefix == null) {
358 bestPrefix = searchTokens.get(0);
359 System.out.println("Everything was in the stoplist!");
361 System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows + ", searchTokens=" + searchTokens);
363 // Place to store the things that match.
364 final Map<RowMatchType,List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(RowMatchType.class);
365 for (final RowMatchType rowMatchType : RowMatchType.values()) {
366 if (rowMatchType != RowMatchType.NO_MATCH) {
367 matches.put(rowMatchType, new ArrayList<RowBase>());
373 final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
374 if (exactMatchIndex != -1) {
375 final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
376 if (pattern.matcher(exactMatch.token).matches()) {
377 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
381 final String searchToken = bestPrefix;
382 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
383 final Set<RowKey> rowsAlreadySeen = new HashSet<RowBase.RowKey>();
384 for (int index = insertionPointIndex;
385 index < sortedIndexEntries.size() && matchCount < MAX_SEARCH_ROWS;
387 if (interrupted.get()) { return null; }
388 final IndexEntry indexEntry = sortedIndexEntries.get(index);
389 if (!indexEntry.normalizedToken.startsWith(searchToken)) {
393 // System.out.println("Searching indexEntry: " + indexEntry.token);
395 // Extra +1 to skip token row.
396 for (int rowIndex = indexEntry.startRow + 1;
397 rowIndex < indexEntry.startRow + 1 + indexEntry.numRows && rowIndex < rows.size();
399 if (interrupted.get()) { return null; }
400 final RowBase row = rows.get(rowIndex);
401 final RowBase.RowKey rowKey = row.getRowKey();
402 if (rowsAlreadySeen.contains(rowKey)) {
405 rowsAlreadySeen.add(rowKey);
406 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(), swapPairEntries);
407 if (matchType != RowMatchType.NO_MATCH) {
408 matches.get(matchType).add(row);
415 // Sort them into a reasonable order.
416 final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(swapPairEntries);
417 for (final Collection<RowBase> rows : matches.values()) {
418 final List<RowBase> ordered = new ArrayList<RowBase>(rows);
419 Collections.sort(ordered, lengthComparator);
420 result.addAll(ordered);
423 System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
427 private String normalizeToken(final String searchToken) {
428 if (TransliteratorManager.init(null)) {
429 final Transliterator normalizer = normalizer();
430 return normalizer.transliterate(searchToken);
432 // Do our best since the Transliterators aren't up yet.
433 return searchToken.toLowerCase();