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 java.io.IOException;
21 import java.io.PrintStream;
22 import java.io.RandomAccessFile;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.EnumMap;
26 import java.util.LinkedHashSet;
27 import java.util.List;
30 import java.util.concurrent.atomic.AtomicBoolean;
32 import com.hughes.android.dictionary.DictionaryInfo;
33 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
34 import com.hughes.util.CachingList;
35 import com.hughes.util.raf.RAFList;
36 import com.hughes.util.raf.RAFSerializable;
37 import com.hughes.util.raf.RAFSerializer;
38 import com.hughes.util.raf.UniformRAFList;
39 import com.ibm.icu.text.Collator;
40 import com.ibm.icu.text.Transliterator;
42 public final class Index implements RAFSerializable<Index> {
44 static final int CACHE_SIZE = 5000;
46 final Dictionary dict;
48 public final String shortName; // Typically the ISO code for the language.
49 public final String longName;
51 // persisted: tells how the entries are sorted.
52 public final Language sortLanguage;
53 final String normalizerRules;
55 // Built from the two above.
56 private Transliterator normalizer;
59 public final List<IndexEntry> sortedIndexEntries;
64 public final List<RowBase> rows;
65 public final boolean swapPairEntries;
68 int mainTokenCount = -1;
70 // --------------------------------------------------------------------------
72 public Index(final Dictionary dict, final String shortName, final String longName, final Language sortLanguage, final String normalizerRules, final boolean swapPairEntries) {
74 this.shortName = shortName;
75 this.longName = longName;
76 this.sortLanguage = sortLanguage;
77 this.normalizerRules = normalizerRules;
78 this.swapPairEntries = swapPairEntries;
79 sortedIndexEntries = new ArrayList<IndexEntry>();
80 rows = new ArrayList<RowBase>();
85 public synchronized Transliterator normalizer() {
86 if (normalizer == null) {
87 normalizer = Transliterator.createFromRules("", normalizerRules, Transliterator.FORWARD);
92 public Index(final Dictionary dict, final RandomAccessFile raf) throws IOException {
94 shortName = raf.readUTF();
95 longName = raf.readUTF();
96 final String languageCode = raf.readUTF();
97 sortLanguage = Language.lookup(languageCode);
98 normalizerRules = raf.readUTF();
99 swapPairEntries = raf.readBoolean();
100 if (sortLanguage == null) {
101 throw new IOException("Unsupported language: " + languageCode);
103 if (dict.dictFileVersion >= 2) {
104 mainTokenCount = raf.readInt();
106 sortedIndexEntries = CachingList.create(RAFList.create(raf, IndexEntry.SERIALIZER, raf.getFilePointer()), CACHE_SIZE);
107 rows = CachingList.create(UniformRAFList.create(raf, new RowBase.Serializer(this), raf.getFilePointer()), CACHE_SIZE);
111 public void write(final RandomAccessFile raf) throws IOException {
112 raf.writeUTF(shortName);
113 raf.writeUTF(longName);
114 raf.writeUTF(sortLanguage.getIsoCode());
115 raf.writeUTF(normalizerRules);
116 raf.writeBoolean(swapPairEntries);
117 if (dict.dictFileVersion >= 2) {
118 raf.writeInt(mainTokenCount);
120 RAFList.write(raf, sortedIndexEntries, IndexEntry.SERIALIZER);
121 UniformRAFList.write(raf, (Collection<RowBase>) rows, new RowBase.Serializer(this), 5);
124 public void print(final PrintStream out) {
125 for (final RowBase row : rows) {
130 public static final class IndexEntry implements RAFSerializable<Index.IndexEntry> {
131 public final String token;
132 private final String normalizedToken;
133 public final int startRow;
134 public final int numRows;
137 static final RAFSerializer<IndexEntry> SERIALIZER = new RAFSerializer<IndexEntry> () {
139 public IndexEntry read(RandomAccessFile raf) throws IOException {
140 return new IndexEntry(raf);
143 public void write(RandomAccessFile raf, IndexEntry t) throws IOException {
147 public IndexEntry(final String token, final String normalizedToken, final int startRow, final int numRows) {
148 assert token.equals(token.trim());
149 assert token.length() > 0;
151 this.normalizedToken = normalizedToken;
152 this.startRow = startRow;
153 this.numRows = numRows;
156 public IndexEntry(final RandomAccessFile raf) throws IOException {
157 token = raf.readUTF();
158 startRow = raf.readInt();
159 numRows = raf.readInt();
160 final boolean hasNormalizedForm = raf.readBoolean();
161 normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
164 public void write(RandomAccessFile raf) throws IOException {
166 raf.writeInt(startRow);
167 raf.writeInt(numRows);
168 final boolean hasNormalizedForm = !token.equals(normalizedToken);
169 raf.writeBoolean(hasNormalizedForm);
170 if (hasNormalizedForm) {
171 raf.writeUTF(normalizedToken);
175 public String toString() {
176 return String.format("%s@%d(%d)", token, startRow, numRows);
179 public String normalizedToken() {
180 return normalizedToken;
184 public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
185 final int index = findInsertionPointIndex(token, interrupted);
186 return index != -1 ? sortedIndexEntries.get(index) : null;
189 public int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
190 token = normalizeToken(token);
193 int end = sortedIndexEntries.size();
195 final Collator sortCollator = sortLanguage.getCollator();
196 while (start < end) {
197 final int mid = (start + end) / 2;
198 if (interrupted.get()) {
201 final IndexEntry midEntry = sortedIndexEntries.get(mid);
203 final int comp = sortCollator.compare(token, midEntry.normalizedToken());
205 final int result = windBackCase(token, mid, interrupted);
207 } else if (comp < 0) {
208 //System.out.println("Upper bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
211 //System.out.println("Lower bound: " + midEntry + ", norm=" + midEntry.normalizedToken() + ", mid=" + mid);
216 // If we search for a substring of a string that's in there, return that.
217 int result = Math.min(start, sortedIndexEntries.size() - 1);
218 result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
222 private final int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
223 while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
225 if (interrupted.get()) {
232 public IndexInfo getIndexInfo() {
233 return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
236 final List<RowBase> multiWordSearch(final List<String> searchTokens, final AtomicBoolean interrupted) {
237 final List<RowBase> result = new ArrayList<RowBase>();
239 // Heuristic: use the longest searchToken as the base.
240 String searchToken = null;
241 for (int i = 0; i < searchTokens.size(); ++i) {
242 if (interrupted.get()) { return null; }
243 final String normalized = normalizeToken(searchTokens.get(i));
244 // Normalize them all.
245 searchTokens.set(i, normalized);
246 if (searchToken == null || normalized.length() > searchToken.length()) {
247 searchToken = normalized;
251 final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
252 if (insertionPointIndex == -1 || interrupted.get()) {
256 // The things that match.
258 final Map<RowMatchType,Set<RowBase>> matches = new EnumMap<RowMatchType, Set<RowBase>>(RowMatchType.class);
259 for (final RowMatchType rowMatchType : RowMatchType.values()) {
260 matches.put(rowMatchType, new LinkedHashSet<RowBase>());
263 for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
264 if (interrupted.get()) { return null; }
265 final IndexEntry indexEntry = sortedIndexEntries.get(index);
266 if (!indexEntry.normalizedToken.equals(searchToken)) {
270 for (int rowIndex = indexEntry.startRow; rowIndex < indexEntry.startRow + indexEntry.numRows; ++rowIndex) {
271 if (interrupted.get()) { return null; }
272 final RowBase row = rows.get(rowIndex);
273 final RowMatchType matchType = row.matches(searchTokens, normalizer, swapPairEntries);
274 if (matchType != RowMatchType.NO_MATCH) {
275 matches.get(matchType).add(row);
280 for (final Set<RowBase> rows : matches.values()) {
287 private String normalizeToken(final String searchToken) {
288 if (TransliteratorManager.init(null)) {
289 final Transliterator normalizer = normalizer();
290 return normalizer.transliterate(searchToken);
292 // Do our best since the Transliterators aren't up yet.
293 return searchToken.toLowerCase();