+ @SuppressWarnings("WeakerAccess")
+ public static String formatQuickdicUrl(final String indexShortName, final String text) {
+ assert !indexShortName.contains(":");
+ assert text.length() > 0;
+ return String.format("q://d?%s&%s", indexShortName, StringUtil.encodeForUrl(text));
+ }
+
+ public static boolean isQuickdicUrl(String url) {
+ return url.startsWith("q://d?");
+ }
+
+ // --------------------------------------------------------------------
+
+ @SuppressWarnings("WeakerAccess")
+ public static final class LazyHtmlLoader {
+ final DataInput raf;
+ final FileChannel ch;
+ final long offset;
+ final int numBytes;
+ final int numZipBytes;
+ final List<byte[]> data;
+ final int index;
+
+ // Not sure this volatile is right, but oh well.
+ volatile SoftReference<String> htmlRef = new SoftReference<>(null);
+
+ private LazyHtmlLoader(FileChannel ch, final DataInput inp, List<byte[]> data, int index) throws IOException {
+ this.data = data;
+ this.index = index;
+ if (data != null) {
+ this.raf = null;
+ this.ch = null;
+ this.offset = 0;
+ this.numBytes = -1;
+ this.numZipBytes = -1;
+ return;
+ }
+ raf = inp;
+ this.ch = ch;
+ numBytes = Math.min(raf.readInt(), 20 * 1024 * 1024);
+ numZipBytes = Math.min(raf.readInt(), 20 * 1024 * 1024);
+ offset = ch.position();
+ raf.skipBytes(numZipBytes);
+ }
+
+ String getHtml() {
+ String html = htmlRef.get();
+ if (html != null) {
+ return html;
+ }
+ if (data != null) {
+ html = new String(data.get(index), StandardCharsets.UTF_8);
+ htmlRef = new SoftReference<>(html);
+ return html;
+ }
+ System.out.println("Loading Html: numBytes=" + numBytes + ", numZipBytes="
+ + numZipBytes);
+ final byte[] zipBytes = new byte[numZipBytes];
+ synchronized (ch) {
+ try {
+ ch.position(offset);
+ raf.readFully(zipBytes);
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to read HTML data from dictionary", e);
+ }
+ }
+ try {
+ final byte[] bytes = StringUtil.unzipFully(zipBytes, numBytes);
+ html = new String(bytes, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new RuntimeException("Dictionary HTML data corrupted", e);
+ }
+ htmlRef = new SoftReference<>(html);
+ return html;
+ }
+ }
+