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.TransformingList;
25 import com.hughes.util.raf.RAFList;
26 import com.hughes.util.raf.RAFSerializable;
27 import com.hughes.util.raf.RAFSerializer;
28 import com.hughes.util.raf.SerializableSerializer;
29 import com.hughes.util.raf.UniformRAFList;
30 import com.ibm.icu.text.Collator;
31 import com.ibm.icu.text.Transliterator;
33 import java.io.IOException;
34 import java.io.PrintStream;
35 import java.io.RandomAccessFile;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.EnumMap;
40 import java.util.HashSet;
41 import java.util.LinkedHashMap;
42 import java.util.LinkedHashSet;
43 import java.util.List;
46 import java.util.concurrent.atomic.AtomicBoolean;
47 import java.util.regex.Pattern;
49 public final class Index implements RAFSerializable<Index> {
51 static final int CACHE_SIZE = 5000;
53 public final Dictionary dict;
55 public final String shortName; // Typically the ISO code for the language.
56 public final String longName;
58 // persisted: tells how the entries are sorted.
59 public final Language sortLanguage;
60 final String normalizerRules;
62 // Built from the two above.
63 private Transliterator normalizer;
66 public final List<IndexEntry> sortedIndexEntries;
69 public final Set<String> stoplist;
74 public final List<RowBase> rows;
75 public final boolean swapPairEntries;
78 int mainTokenCount = -1;
80 // --------------------------------------------------------------------------
82 public Index(final Dictionary dict, final String shortName, final String longName, final Language sortLanguage, final String normalizerRules, final boolean swapPairEntries, final Set<String> stoplist) {
84 this.shortName = shortName;
85 this.longName = longName;
86 this.sortLanguage = sortLanguage;
87 this.normalizerRules = normalizerRules;
88 this.swapPairEntries = swapPairEntries;
89 sortedIndexEntries = new ArrayList<IndexEntry>();
90 this.stoplist = stoplist;
91 rows = new ArrayList<RowBase>();
97 * Deferred initialization because it can be slow.
99 public synchronized Transliterator normalizer() {
100 if (normalizer == null) {
101 normalizer = Transliterator.createFromRules("", normalizerRules, Transliterator.FORWARD);
107 * Note that using this comparator probably involves doing too many text normalizations.
109 public NormalizeComparator getSortComparator() {
110 return new NormalizeComparator(normalizer(), sortLanguage.getCollator());
113 public Index(final Dictionary dict, final RandomAccessFile raf) throws IOException {
115 shortName = raf.readUTF();
116 longName = raf.readUTF();
117 final String languageCode = raf.readUTF();
118 sortLanguage = Language.lookup(languageCode);
119 normalizerRules = raf.readUTF();
120 swapPairEntries = raf.readBoolean();
121 if (sortLanguage == null) {
122 throw new IOException("Unsupported language: " + languageCode);
124 if (dict.dictFileVersion >= 2) {
125 mainTokenCount = raf.readInt();
127 sortedIndexEntries = CachingList.create(RAFList.create(raf, indexEntrySerializer, raf.getFilePointer()), CACHE_SIZE);
128 if (dict.dictFileVersion >= 4) {
129 stoplist = new SerializableSerializer<Set<String>>().read(raf);
131 stoplist = Collections.emptySet();
133 rows = CachingList.create(UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()), CACHE_SIZE);
137 public void write(final RandomAccessFile raf) throws IOException {
138 raf.writeUTF(shortName);
139 raf.writeUTF(longName);
140 raf.writeUTF(sortLanguage.getIsoCode());
141 raf.writeUTF(normalizerRules);
142 raf.writeBoolean(swapPairEntries);
143 if (dict.dictFileVersion >= 2) {
144 raf.writeInt(mainTokenCount);
146 RAFList.write(raf, sortedIndexEntries, indexEntrySerializer);
147 new SerializableSerializer<Set<String>>().write(raf, stoplist);
148 UniformRAFList.write(raf, (Collection<RowBase>) rows, new RowBase.Serializer(this), 5 /* bytes per entry */);
151 public void print(final PrintStream out) {
152 for (final RowBase row : rows) {
157 private final RAFSerializer<IndexEntry> indexEntrySerializer = new RAFSerializer<IndexEntry> () {
159 public IndexEntry read(RandomAccessFile raf) throws IOException {
160 return new IndexEntry(Index.this, raf);
163 public void write(RandomAccessFile raf, IndexEntry t) throws IOException {
168 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
169 private final Index index;
170 public final String token;
171 private final String normalizedToken;
172 public final int startRow;
173 public final int numRows; // doesn't count the token row!
174 public final List<HtmlEntry> htmlEntries;
177 public IndexEntry(final Index index, final String token, final String normalizedToken, final int startRow, final int numRows) {
179 assert token.equals(token.trim());
180 assert token.length() > 0;
182 this.normalizedToken = normalizedToken;
183 this.startRow = startRow;
184 this.numRows = numRows;
185 this.htmlEntries = new ArrayList<HtmlEntry>();
188 public IndexEntry(final Index index, final RandomAccessFile raf) throws IOException {
190 token = raf.readUTF();
191 startRow = raf.readInt();
192 numRows = raf.readInt();
193 final boolean hasNormalizedForm = raf.readBoolean();
194 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
195 if (index.dict.dictFileVersion >= 6) {
196 this.htmlEntries = CachingList.create(RAFList.create(raf, index.dict.htmlEntryIndexSerializer, raf.getFilePointer()), 1);
198 this.htmlEntries = Collections.emptyList();
202 public void write(RandomAccessFile raf) throws IOException {
204 raf.writeInt(startRow);
205 raf.writeInt(numRows);
206 final boolean hasNormalizedForm = !token.equals(normalizedToken);
207 raf.writeBoolean(hasNormalizedForm);
208 if (hasNormalizedForm) {
209 raf.writeUTF(normalizedToken);
211 RAFList.write(raf, htmlEntries, index.dict.htmlEntryIndexSerializer);
214 public String toString() {
215 return String.format("%s@%d(%d)", token, startRow, numRows);
218 public String normalizedToken() {
219 return normalizedToken;
223 static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
225 public String transform(IndexEntry t1) {
230 public IndexEntry findExact(final String exactToken) {
231 final int result = Collections.binarySearch(TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken, getSortComparator());
233 return sortedIndexEntries.get(result);
238 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
239 final int index = findInsertionPointIndex(token, interrupted);
240 return index != -1 ? sortedIndexEntries.get(index) : null;
243 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
244 token = normalizeToken(token);
247 int end = sortedIndexEntries.size();
249 final Collator sortCollator = sortLanguage.getCollator();
250 while (start < end) {
251 final int mid = (start + end) / 2;
252 if (interrupted.get()) {
255 final IndexEntry midEntry = sortedIndexEntries.get(mid);
257 final int comp = sortCollator.compare(token, midEntry.normalizedToken());
259 final int result = windBackCase(token, mid, interrupted);
261 } else if (comp < 0) {
262 System.out.println("Upper bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
265 System.out.println("Lower bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
270 // If we search for a substring of a string that's in there, return that.
271 int result = Math.min(start, sortedIndexEntries.size() - 1);
272 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
276 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
277 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
279 if (interrupted.get()) {
286 public IndexInfo getIndexInfo() {
287 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
290 private static final int MAX_SEARCH_ROWS = 1000;
292 private final Map<String,Integer> prefixToNumRows = new LinkedHashMap<String, Integer>();
293 private synchronized final int getUpperBoundOnRowsStartingWith(final String normalizedPrefix, final int maxRows, final AtomicBoolean interrupted) {
294 final Integer numRows = prefixToNumRows.get(normalizedPrefix);
295 if (numRows != null) {
298 final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
301 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
302 if (interrupted.get()) { return -1; }
303 final IndexEntry indexEntry = sortedIndexEntries.get(index);
304 if (!indexEntry.normalizedToken.startsWith(normalizedPrefix)) {
307 rowCount += indexEntry.numRows;
308 if (rowCount > maxRows) {
309 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
313 prefixToNumRows.put(normalizedPrefix, numRows);
318 public final List<RowBase> multiWordSearch(final List<String> searchTokens, final AtomicBoolean interrupted) {
319 final long startMills = System.currentTimeMillis();
320 final List<RowBase> result = new ArrayList<RowBase>();
322 final Set<String> normalizedNonStoplist = new LinkedHashSet<String>();
324 String bestPrefix = null;
325 int leastRows = Integer.MAX_VALUE;
326 final StringBuilder regex = new StringBuilder();
327 for (int i = 0; i < searchTokens.size(); ++i) {
328 if (interrupted.get()) { return null; }
329 final String searchToken = searchTokens.get(i);
330 final String normalized = normalizeToken(searchTokens.get(i));
331 // Normalize them all.
332 searchTokens.set(i, normalized);
334 if (!stoplist.contains(searchToken)) {
335 if (normalizedNonStoplist.add(normalized)) {
336 final int numRows = getUpperBoundOnRowsStartingWith(normalized, MAX_SEARCH_ROWS, interrupted);
337 if (numRows != -1 && numRows < leastRows) {
339 // We really are done here.
340 return Collections.emptyList();
343 bestPrefix = normalized;
348 if (regex.length() > 0) {
349 regex.append("[\\s]*");
351 regex.append(Pattern.quote(normalized));
353 final Pattern pattern = Pattern.compile(regex.toString());
355 if (bestPrefix == null) {
356 bestPrefix = searchTokens.get(0);
357 System.out.println("Everything was in the stoplist!");
359 System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows + ", searchTokens=" + searchTokens);
361 // Place to store the things that match.
362 final Map<RowMatchType,List<RowBase>> matches = new EnumMap<RowMatchType, List<RowBase>>(RowMatchType.class);
363 for (final RowMatchType rowMatchType : RowMatchType.values()) {
364 if (rowMatchType != RowMatchType.NO_MATCH) {
365 matches.put(rowMatchType, new ArrayList<RowBase>());
370 final Set<RowKey> cachedRowKeys = new HashSet<RowBase.RowKey>();
372 // for (final String searchToken : searchTokens) {
373 final String searchToken = bestPrefix;
375 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
377 for (int index = insertionPointIndex; index < sortedIndexEntries.size() && matchCount < MAX_SEARCH_ROWS; ++index) {
378 if (interrupted.get()) { return null; }
379 final IndexEntry indexEntry = sortedIndexEntries.get(index);
380 if (!indexEntry.normalizedToken.startsWith(searchToken)) {
384 // System.out.println("Searching indexEntry: " + indexEntry.token);
386 // Extra +1 to skip token row.
387 for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1 + indexEntry.numRows && rowIndex < rows.size(); ++rowIndex) {
388 if (interrupted.get()) { return null; }
389 final RowBase row = rows.get(rowIndex);
390 final RowBase.RowKey rowKey = row.getRowKey();
391 if (cachedRowKeys.contains(rowKey)) {
394 cachedRowKeys.add(rowKey);
395 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(), swapPairEntries);
396 if (matchType != RowMatchType.NO_MATCH) {
397 matches.get(matchType).add(row);
404 // Sort them into a reasonable order.
405 final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(swapPairEntries);
406 for (final Collection<RowBase> rows : matches.values()) {
407 final List<RowBase> ordered = new ArrayList<RowBase>(rows);
408 Collections.sort(ordered, lengthComparator);
409 result.addAll(ordered);
412 //System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
416 private String normalizeToken(final String searchToken) {
417 if (TransliteratorManager.init(null)) {
418 final Transliterator normalizer = normalizer();
419 return normalizer.transliterate(searchToken);
421 // Do our best since the Transliterators aren't up yet.
422 return searchToken.toLowerCase();