2 package com.hughes.android.dictionary.engine;
4 import com.hughes.util.StringUtil;
5 import com.hughes.util.raf.RAFListSerializer;
6 import com.hughes.util.raf.RAFListSerializerSkippable;
7 import com.ibm.icu.text.Transliterator;
9 import java.io.DataInput;
10 import java.io.DataOutput;
11 import java.io.IOException;
12 import java.io.PrintStream;
13 import java.io.UnsupportedEncodingException;
14 import java.lang.ref.SoftReference;
15 import java.nio.channels.FileChannel;
16 import java.nio.charset.StandardCharsets;
17 import java.util.List;
18 import java.util.regex.Pattern;
20 public class HtmlEntry extends AbstractEntry implements Comparable<HtmlEntry> {
22 // Title is not HTML escaped.
23 public final String title;
24 private final LazyHtmlLoader lazyHtmlLoader;
25 @SuppressWarnings("WeakerAccess")
28 public HtmlEntry(final EntrySource entrySource, String title) {
31 lazyHtmlLoader = null;
34 public HtmlEntry(Dictionary dictionary, FileChannel ch, DataInput raf, final int index)
36 super(dictionary, raf, index);
37 title = raf.readUTF();
38 lazyHtmlLoader = new LazyHtmlLoader(ch, raf, dictionary.htmlData, index);
42 private void writeBase(DataOutput raf) throws IOException {
47 private void writeData(DataOutput raf) throws IOException {
48 final byte[] bytes = getHtml().getBytes(StandardCharsets.UTF_8);
49 StringUtil.writeVarInt(raf, bytes.length);
53 private static byte[] readData(DataInput raf) throws IOException {
54 int len = StringUtil.readVarInt(raf);
55 final byte[] bytes = new byte[Math.min(len, 20 * 1024 * 1024)];
61 return html != null ? html : lazyHtmlLoader.getHtml();
65 public void addToDictionary(Dictionary dictionary) {
67 dictionary.htmlEntries.add(this);
68 index = dictionary.htmlEntries.size() - 1;
72 public RowBase CreateRow(int rowIndex, Index dictionaryIndex) {
73 return new Row(this.index, rowIndex, dictionaryIndex);
76 static final class Serializer implements RAFListSerializerSkippable<HtmlEntry> {
78 final Dictionary dictionary;
81 Serializer(Dictionary dictionary, FileChannel ch) {
82 this.dictionary = dictionary;
87 public HtmlEntry read(DataInput raf, final int index) throws IOException {
88 return new HtmlEntry(dictionary, ch, raf, index);
92 public void skip(DataInput raf, final int index) throws IOException {
93 if (dictionary.dictFileVersion >= 7)
95 StringUtil.readVarInt(raf);
101 int l = raf.readUnsignedShort();
106 public void write(DataOutput raf, HtmlEntry t) throws IOException {
111 static final class DataSerializer implements RAFListSerializer<HtmlEntry> {
113 public HtmlEntry read(DataInput raf, final int index) {
119 public void write(DataOutput raf, HtmlEntry t) throws IOException {
124 static final class DataDeserializer implements RAFListSerializer<byte[]> {
126 public byte[] read(DataInput raf, final int index) throws IOException {
127 return HtmlEntry.readData(raf);
131 public void write(DataOutput raf, byte[] t) {
136 private String getRawText(final boolean compact) {
137 return title + ":\n" + getHtml();
141 public int compareTo(/*@NonNull*/ HtmlEntry another) {
142 if (title.compareTo(another.title) != 0) {
143 return title.compareTo(another.title);
145 return getHtml().compareTo(another.getHtml());
149 public String toString() {
150 return getRawText(false);
153 // --------------------------------------------------------------------
155 public static class Row extends RowBase {
157 Row(final DataInput raf, final int thisRowIndex,
158 final Index index, int extra) throws IOException {
159 super(raf, thisRowIndex, index, extra);
162 Row(final int referenceIndex, final int thisRowIndex,
164 super(referenceIndex, thisRowIndex, index);
168 public String toString() {
169 return getRawText(false);
172 public HtmlEntry getEntry() {
173 return index.dict.htmlEntries.get(referenceIndex);
177 public void print(PrintStream out) {
178 final HtmlEntry entry = getEntry();
179 out.println("See also HtmlEntry:" + entry.title);
183 public String getRawText(boolean compact) {
184 final HtmlEntry entry = getEntry();
185 return entry.getRawText(compact);
189 public RowMatchType matches(final List<String> searchTokens,
190 final Pattern orderedMatchPattern, final Transliterator normalizer,
191 final boolean swapPairEntries) {
192 final String text = normalizer.transform(getRawText(false));
193 if (orderedMatchPattern.matcher(text).find()) {
194 return RowMatchType.ORDERED_MATCH;
196 for (int i = searchTokens.size() - 1; i >= 0; --i) {
197 final String searchToken = searchTokens.get(i);
198 if (!text.contains(searchToken)) {
199 return RowMatchType.NO_MATCH;
202 return RowMatchType.BAG_OF_WORDS_MATCH;
206 public static String htmlBody(final List<HtmlEntry> htmlEntries, final String indexShortName) {
207 final StringBuilder result = new StringBuilder();
208 for (final HtmlEntry htmlEntry : htmlEntries) {
209 final String titleEscaped = StringUtil.escapeUnicodeToPureHtml(htmlEntry.title);
210 result.append(String.format("<h1><a href=\"%s\">%s</a></h1>\n<p>%s\n",
211 formatQuickdicUrl(indexShortName, htmlEntry.title), titleEscaped,
212 htmlEntry.getHtml()));
214 return result.toString();
217 @SuppressWarnings("WeakerAccess")
218 public static String formatQuickdicUrl(final String indexShortName, final String text) {
219 assert !indexShortName.contains(":");
220 assert text.length() > 0;
221 return String.format("q://d?%s&%s", indexShortName, StringUtil.encodeForUrl(text));
224 public static boolean isQuickdicUrl(String url) {
225 return url.startsWith("q://d?");
228 // --------------------------------------------------------------------
230 @SuppressWarnings("WeakerAccess")
231 public static final class LazyHtmlLoader {
233 final FileChannel ch;
236 final int numZipBytes;
237 final List<byte[]> data;
240 // Not sure this volatile is right, but oh well.
241 volatile SoftReference<String> htmlRef = new SoftReference<>(null);
243 private LazyHtmlLoader(FileChannel ch, final DataInput inp, List<byte[]> data, int index) throws IOException {
251 this.numZipBytes = -1;
256 numBytes = Math.min(raf.readInt(), 20 * 1024 * 1024);
257 numZipBytes = Math.min(raf.readInt(), 20 * 1024 * 1024);
258 offset = ch.position();
259 raf.skipBytes(numZipBytes);
263 String html = htmlRef.get();
268 html = new String(data.get(index), StandardCharsets.UTF_8);
269 htmlRef = new SoftReference<>(html);
272 System.out.println("Loading Html: numBytes=" + numBytes + ", numZipBytes="
274 final byte[] zipBytes = new byte[numZipBytes];
278 raf.readFully(zipBytes);
279 } catch (IOException e) {
280 throw new RuntimeException("Failed to read HTML data from dictionary", e);
284 final byte[] bytes = StringUtil.unzipFully(zipBytes, numBytes);
285 html = new String(bytes, StandardCharsets.UTF_8);
286 } catch (IOException e) {
287 throw new RuntimeException("Dictionary HTML data corrupted", e);
289 htmlRef = new SoftReference<>(html);