From 0f47403d0220757fed189b76e2071e25b1025cb8 Mon Sep 17 00:00:00 2001 From: Runemoro Date: Wed, 3 Jun 2020 13:39:42 -0400 Subject: Split GUI code to separate module (#242) * Split into modules * Post merge compile fixes Co-authored-by: modmuss50 --- src/main/java/cuchaz/enigma/utils/I18n.java | 102 ------ .../java/cuchaz/enigma/utils/LFPrintWriter.java | 16 - src/main/java/cuchaz/enigma/utils/Message.java | 392 --------------------- src/main/java/cuchaz/enigma/utils/Pair.java | 26 -- .../java/cuchaz/enigma/utils/ReadableToken.java | 30 -- src/main/java/cuchaz/enigma/utils/Utils.java | 179 ---------- .../cuchaz/enigma/utils/search/SearchEntry.java | 17 - .../cuchaz/enigma/utils/search/SearchUtil.java | 268 -------------- 8 files changed, 1030 deletions(-) delete mode 100644 src/main/java/cuchaz/enigma/utils/I18n.java delete mode 100644 src/main/java/cuchaz/enigma/utils/LFPrintWriter.java delete mode 100644 src/main/java/cuchaz/enigma/utils/Message.java delete mode 100644 src/main/java/cuchaz/enigma/utils/Pair.java delete mode 100644 src/main/java/cuchaz/enigma/utils/ReadableToken.java delete mode 100644 src/main/java/cuchaz/enigma/utils/Utils.java delete mode 100644 src/main/java/cuchaz/enigma/utils/search/SearchEntry.java delete mode 100644 src/main/java/cuchaz/enigma/utils/search/SearchUtil.java (limited to 'src/main/java/cuchaz/enigma/utils') diff --git a/src/main/java/cuchaz/enigma/utils/I18n.java b/src/main/java/cuchaz/enigma/utils/I18n.java deleted file mode 100644 index f91c916..0000000 --- a/src/main/java/cuchaz/enigma/utils/I18n.java +++ /dev/null @@ -1,102 +0,0 @@ -package cuchaz.enigma.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.stream.Stream; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import com.google.common.reflect.ClassPath; -import com.google.common.reflect.ClassPath.ResourceInfo; -import com.google.gson.Gson; - -import cuchaz.enigma.config.Config; - -public class I18n { - public static final String DEFAULT_LANGUAGE = "en_us"; - private static final Gson GSON = new Gson(); - private static Map translations = Maps.newHashMap(); - private static Map defaultTranslations = Maps.newHashMap(); - private static Map languageNames = Maps.newHashMap(); - - static { - translations = load(Config.getInstance().language); - defaultTranslations = load(DEFAULT_LANGUAGE); - } - - @SuppressWarnings("unchecked") - public static Map load(String language) { - try (InputStream inputStream = I18n.class.getResourceAsStream("/lang/" + language + ".json")) { - if (inputStream != null) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { - return GSON.fromJson(reader, Map.class); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - return Collections.emptyMap(); - } - - public static String translate(String key) { - String value = translations.get(key); - if (value != null) { - return value; - } - value = defaultTranslations.get(key); - if (value != null) { - return value; - } - return key; - } - - public static String getLanguageName(String language) { - return languageNames.get(language); - } - - public static void setLanguage(String language) { - Config.getInstance().language = language; - try { - Config.getInstance().saveConfig(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static ArrayList getAvailableLanguages() { - ArrayList list = new ArrayList(); - - try { - ImmutableList resources = ClassPath.from(Thread.currentThread().getContextClassLoader()).getResources().asList(); - Stream dirStream = resources.stream(); - dirStream.forEach(context -> { - String file = context.getResourceName(); - if (file.startsWith("lang/") && file.endsWith(".json")) { - String fileName = file.substring(5, file.length() - 5); - list.add(fileName); - loadLanguageName(fileName); - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - return list; - } - - private static void loadLanguageName(String fileName) { - try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lang/" + fileName + ".json")) { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { - Map map = GSON.fromJson(reader, Map.class); - languageNames.put(fileName, map.get("language").toString()); - } - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/cuchaz/enigma/utils/LFPrintWriter.java b/src/main/java/cuchaz/enigma/utils/LFPrintWriter.java deleted file mode 100644 index c12e913..0000000 --- a/src/main/java/cuchaz/enigma/utils/LFPrintWriter.java +++ /dev/null @@ -1,16 +0,0 @@ -package cuchaz.enigma.utils; - -import java.io.PrintWriter; -import java.io.Writer; - -public class LFPrintWriter extends PrintWriter { - public LFPrintWriter(Writer out) { - super(out); - } - - @Override - public void println() { - // https://stackoverflow.com/a/14749004 - write('\n'); - } -} diff --git a/src/main/java/cuchaz/enigma/utils/Message.java b/src/main/java/cuchaz/enigma/utils/Message.java deleted file mode 100644 index d7c5f23..0000000 --- a/src/main/java/cuchaz/enigma/utils/Message.java +++ /dev/null @@ -1,392 +0,0 @@ -package cuchaz.enigma.utils; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Objects; - -import cuchaz.enigma.network.packet.PacketHelper; -import cuchaz.enigma.translation.representation.entry.Entry; - -public abstract class Message { - - public final String user; - - public static Chat chat(String user, String message) { - return new Chat(user, message); - } - - public static Connect connect(String user) { - return new Connect(user); - } - - public static Disconnect disconnect(String user) { - return new Disconnect(user); - } - - public static EditDocs editDocs(String user, Entry entry) { - return new EditDocs(user, entry); - } - - public static MarkDeobf markDeobf(String user, Entry entry) { - return new MarkDeobf(user, entry); - } - - public static RemoveMapping removeMapping(String user, Entry entry) { - return new RemoveMapping(user, entry); - } - - public static Rename rename(String user, Entry entry, String newName) { - return new Rename(user, entry, newName); - } - - public abstract String translate(); - - public abstract Type getType(); - - public static Message read(DataInput input) throws IOException { - byte typeId = input.readByte(); - if (typeId < 0 || typeId >= Type.values().length) { - throw new IOException(String.format("Invalid message type ID %d", typeId)); - } - Type type = Type.values()[typeId]; - String user = input.readUTF(); - switch (type) { - case CHAT: - String message = input.readUTF(); - return chat(user, message); - case CONNECT: - return connect(user); - case DISCONNECT: - return disconnect(user); - case EDIT_DOCS: - Entry entry = PacketHelper.readEntry(input); - return editDocs(user, entry); - case MARK_DEOBF: - entry = PacketHelper.readEntry(input); - return markDeobf(user, entry); - case REMOVE_MAPPING: - entry = PacketHelper.readEntry(input); - return removeMapping(user, entry); - case RENAME: - entry = PacketHelper.readEntry(input); - String newName = input.readUTF(); - return rename(user, entry, newName); - default: - throw new IllegalStateException("unreachable"); - } - } - - public void write(DataOutput output) throws IOException { - output.writeByte(getType().ordinal()); - PacketHelper.writeString(output, user); - } - - private Message(String user) { - this.user = user; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Message message = (Message) o; - return Objects.equals(user, message.user); - } - - @Override - public int hashCode() { - return Objects.hash(user); - } - - public enum Type { - CHAT, - CONNECT, - DISCONNECT, - EDIT_DOCS, - MARK_DEOBF, - REMOVE_MAPPING, - RENAME, - } - - public static final class Chat extends Message { - - public final String message; - - private Chat(String user, String message) { - super(user); - this.message = message; - } - - @Override - public void write(DataOutput output) throws IOException { - super.write(output); - PacketHelper.writeString(output, message); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.chat.text"), user, message); - } - - @Override - public Type getType() { - return Type.CHAT; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - Chat chat = (Chat) o; - return Objects.equals(message, chat.message); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), message); - } - - @Override - public String toString() { - return String.format("Message.Chat { user: '%s', message: '%s' }", user, message); - } - - } - - public static final class Connect extends Message { - - private Connect(String user) { - super(user); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.connect.text"), user); - } - - @Override - public Type getType() { - return Type.CONNECT; - } - - @Override - public String toString() { - return String.format("Message.Connect { user: '%s' }", user); - } - - } - - public static final class Disconnect extends Message { - - private Disconnect(String user) { - super(user); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.disconnect.text"), user); - } - - @Override - public Type getType() { - return Type.DISCONNECT; - } - - @Override - public String toString() { - return String.format("Message.Disconnect { user: '%s' }", user); - } - - } - - public static final class EditDocs extends Message { - - public final Entry entry; - - private EditDocs(String user, Entry entry) { - super(user); - this.entry = entry; - } - - @Override - public void write(DataOutput output) throws IOException { - super.write(output); - PacketHelper.writeEntry(output, entry); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.edit_docs.text"), user, entry); - } - - @Override - public Type getType() { - return Type.EDIT_DOCS; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - EditDocs editDocs = (EditDocs) o; - return Objects.equals(entry, editDocs.entry); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), entry); - } - - @Override - public String toString() { - return String.format("Message.EditDocs { user: '%s', entry: %s }", user, entry); - } - - } - - public static final class MarkDeobf extends Message { - - public final Entry entry; - - private MarkDeobf(String user, Entry entry) { - super(user); - this.entry = entry; - } - - @Override - public void write(DataOutput output) throws IOException { - super.write(output); - PacketHelper.writeEntry(output, entry); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.mark_deobf.text"), user, entry); - } - - @Override - public Type getType() { - return Type.MARK_DEOBF; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - MarkDeobf markDeobf = (MarkDeobf) o; - return Objects.equals(entry, markDeobf.entry); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), entry); - } - - @Override - public String toString() { - return String.format("Message.MarkDeobf { user: '%s', entry: %s }", user, entry); - } - - } - - public static final class RemoveMapping extends Message { - - public final Entry entry; - - private RemoveMapping(String user, Entry entry) { - super(user); - this.entry = entry; - } - - @Override - public void write(DataOutput output) throws IOException { - super.write(output); - PacketHelper.writeEntry(output, entry); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.remove_mapping.text"), user, entry); - } - - @Override - public Type getType() { - return Type.REMOVE_MAPPING; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - RemoveMapping that = (RemoveMapping) o; - return Objects.equals(entry, that.entry); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), entry); - } - - @Override - public String toString() { - return String.format("Message.RemoveMapping { user: '%s', entry: %s }", user, entry); - } - - } - - public static final class Rename extends Message { - - public final Entry entry; - public final String newName; - - private Rename(String user, Entry entry, String newName) { - super(user); - this.entry = entry; - this.newName = newName; - } - - @Override - public void write(DataOutput output) throws IOException { - super.write(output); - PacketHelper.writeEntry(output, entry); - PacketHelper.writeString(output, newName); - } - - @Override - public String translate() { - return String.format(I18n.translate("message.rename.text"), user, entry, newName); - } - - @Override - public Type getType() { - return Type.RENAME; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - Rename rename = (Rename) o; - return Objects.equals(entry, rename.entry) && - Objects.equals(newName, rename.newName); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), entry, newName); - } - - @Override - public String toString() { - return String.format("Message.Rename { user: '%s', entry: %s, newName: '%s' }", user, entry, newName); - } - - } - -} diff --git a/src/main/java/cuchaz/enigma/utils/Pair.java b/src/main/java/cuchaz/enigma/utils/Pair.java deleted file mode 100644 index bf02cef..0000000 --- a/src/main/java/cuchaz/enigma/utils/Pair.java +++ /dev/null @@ -1,26 +0,0 @@ -package cuchaz.enigma.utils; - -import java.util.Objects; - -public class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - - @Override - public int hashCode() { - return Objects.hashCode(a) * 31 + - Objects.hashCode(b); - } - - @Override - public boolean equals(Object o) { - return o instanceof Pair && - Objects.equals(a, ((Pair) o).a) && - Objects.equals(b, ((Pair) o).b); - } -} diff --git a/src/main/java/cuchaz/enigma/utils/ReadableToken.java b/src/main/java/cuchaz/enigma/utils/ReadableToken.java deleted file mode 100644 index de152fe..0000000 --- a/src/main/java/cuchaz/enigma/utils/ReadableToken.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Jeff Martin. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser General Public - * License v3.0 which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl.html - *

- * Contributors: - * Jeff Martin - initial API and implementation - ******************************************************************************/ - -package cuchaz.enigma.utils; - -public class ReadableToken { - - public int line; - public int startColumn; - public int endColumn; - - public ReadableToken(int line, int startColumn, int endColumn) { - this.line = line; - this.startColumn = startColumn; - this.endColumn = endColumn; - } - - @Override - public String toString() { - return "line " + line + " columns " + startColumn + "-" + endColumn; - } -} diff --git a/src/main/java/cuchaz/enigma/utils/Utils.java b/src/main/java/cuchaz/enigma/utils/Utils.java deleted file mode 100644 index b45b00d..0000000 --- a/src/main/java/cuchaz/enigma/utils/Utils.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Jeff Martin. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser General Public - * License v3.0 which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl.html - *

- * Contributors: - * Jeff Martin - initial API and implementation - ******************************************************************************/ - -package cuchaz.enigma.utils; - -import com.google.common.io.CharStreams; -import org.objectweb.asm.Opcodes; - -import javax.swing.*; -import javax.swing.text.BadLocationException; -import javax.swing.text.JTextComponent; -import java.awt.*; -import java.awt.event.MouseEvent; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.*; -import java.util.List; -import java.util.stream.Collectors; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public class Utils { - - public static final int ASM_VERSION = Opcodes.ASM8; - - public static int combineHashesOrdered(Object... objs) { - final int prime = 67; - int result = 1; - for (Object obj : objs) { - result *= prime; - if (obj != null) { - result += obj.hashCode(); - } - } - return result; - } - - public static int combineHashesOrdered(List objs) { - final int prime = 67; - int result = 1; - for (Object obj : objs) { - result *= prime; - if (obj != null) { - result += obj.hashCode(); - } - } - return result; - } - - public static String readStreamToString(InputStream in) throws IOException { - return CharStreams.toString(new InputStreamReader(in, "UTF-8")); - } - - public static String readResourceToString(String path) throws IOException { - InputStream in = Utils.class.getResourceAsStream(path); - if (in == null) { - throw new IllegalArgumentException("Resource not found! " + path); - } - return readStreamToString(in); - } - - public static void openUrl(String url) { - if (Desktop.isDesktopSupported()) { - Desktop desktop = Desktop.getDesktop(); - try { - desktop.browse(new URI(url)); - } catch (IOException ex) { - throw new Error(ex); - } catch (URISyntaxException ex) { - throw new IllegalArgumentException(ex); - } - } - } - - public static JLabel unboldLabel(JLabel label) { - Font font = label.getFont(); - label.setFont(font.deriveFont(font.getStyle() & ~Font.BOLD)); - return label; - } - - public static void showToolTipNow(JComponent component) { - // HACKHACK: trick the tooltip manager into showing the tooltip right now - ToolTipManager manager = ToolTipManager.sharedInstance(); - int oldDelay = manager.getInitialDelay(); - manager.setInitialDelay(0); - manager.mouseMoved(new MouseEvent(component, MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, 0, 0, 0, false)); - manager.setInitialDelay(oldDelay); - } - - public static Rectangle safeModelToView(JTextComponent component, int modelPos) { - if (modelPos < 0) { - modelPos = 0; - } else if (modelPos >= component.getText().length()) { - modelPos = component.getText().length(); - } - try { - return component.modelToView(modelPos); - } catch (BadLocationException e) { - throw new RuntimeException(e); - } - } - - public static boolean getSystemPropertyAsBoolean(String property, boolean defValue) { - String value = System.getProperty(property); - return value == null ? defValue : Boolean.parseBoolean(value); - } - - public static void delete(Path path) throws IOException { - if (Files.exists(path)) { - for (Path p : Files.walk(path).sorted(Comparator.reverseOrder()).collect(Collectors.toList())) { - Files.delete(p); - } - } - } - - public static byte[] zipSha1(Path path) throws IOException { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException e) { - // Algorithm guaranteed to be supported - throw new RuntimeException(e); - } - try (ZipFile zip = new ZipFile(path.toFile())) { - List entries = Collections.list(zip.entries()); - // only compare classes (some implementations may not generate directory entries) - entries.removeIf(entry -> !entry.getName().toLowerCase(Locale.ROOT).endsWith(".class")); - // different implementations may add zip entries in a different order - entries.sort(Comparator.comparing(ZipEntry::getName)); - byte[] buffer = new byte[8192]; - for (ZipEntry entry : entries) { - digest.update(entry.getName().getBytes(StandardCharsets.UTF_8)); - try (InputStream in = zip.getInputStream(entry)) { - int n; - while ((n = in.read(buffer)) != -1) { - digest.update(buffer, 0, n); - } - } - } - } - return digest.digest(); - } - - public static String caplisiseCamelCase(String input){ - StringJoiner stringJoiner = new StringJoiner(" "); - for (String word : input.toLowerCase(Locale.ROOT).split("_")) { - stringJoiner.add(word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1)); - } - return stringJoiner.toString(); - } - - public static boolean isBlank(String input) { - if (input == null) { - return true; - } - for (int i = 0; i < input.length(); i++) { - if (!Character.isWhitespace(input.charAt(i))) { - return false; - } - } - return true; - } -} diff --git a/src/main/java/cuchaz/enigma/utils/search/SearchEntry.java b/src/main/java/cuchaz/enigma/utils/search/SearchEntry.java deleted file mode 100644 index 48b255f..0000000 --- a/src/main/java/cuchaz/enigma/utils/search/SearchEntry.java +++ /dev/null @@ -1,17 +0,0 @@ -package cuchaz.enigma.utils.search; - -import java.util.List; - -public interface SearchEntry { - - List getSearchableNames(); - - /** - * Returns a type that uniquely identifies this search entry across possible changes. - * This is used for tracking the amount of times this entry has been selected. - * - * @return a unique identifier for this search entry - */ - String getIdentifier(); - -} diff --git a/src/main/java/cuchaz/enigma/utils/search/SearchUtil.java b/src/main/java/cuchaz/enigma/utils/search/SearchUtil.java deleted file mode 100644 index a51afbb..0000000 --- a/src/main/java/cuchaz/enigma/utils/search/SearchUtil.java +++ /dev/null @@ -1,268 +0,0 @@ -package cuchaz.enigma.utils.search; - -import java.util.*; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.BiFunction; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import cuchaz.enigma.utils.Pair; - -public class SearchUtil { - - private final Map> entries = new HashMap<>(); - private final Map hitCount = new HashMap<>(); - private final Executor searchExecutor = Executors.newWorkStealingPool(); - - public void add(T entry) { - Entry e = Entry.from(entry); - entries.put(entry, e); - } - - public void add(Entry entry) { - entries.put(entry.searchEntry, entry); - } - - public void addAll(Collection entries) { - this.entries.putAll(entries.parallelStream().collect(Collectors.toMap(e -> e, Entry::from))); - } - - public void remove(T entry) { - entries.remove(entry); - } - - public void clear() { - entries.clear(); - } - - public void clearHits() { - hitCount.clear(); - } - - public Stream search(String term) { - return entries.values().parallelStream() - .map(e -> new Pair<>(e, e.getScore(term, hitCount.getOrDefault(e.searchEntry.getIdentifier(), 0)))) - .filter(e -> e.b > 0) - .sorted(Comparator.comparingDouble(o -> -o.b)) - .map(e -> e.a.searchEntry) - .sequential(); - } - - public SearchControl asyncSearch(String term, SearchResultConsumer consumer) { - Map hitCount = new HashMap<>(this.hitCount); - Map> entries = new HashMap<>(this.entries); - float[] scores = new float[entries.size()]; - Lock scoresLock = new ReentrantLock(); - AtomicInteger size = new AtomicInteger(); - AtomicBoolean control = new AtomicBoolean(false); - AtomicInteger elapsed = new AtomicInteger(); - for (Entry value : entries.values()) { - searchExecutor.execute(() -> { - try { - if (control.get()) return; - float score = value.getScore(term, hitCount.getOrDefault(value.searchEntry.getIdentifier(), 0)); - if (score <= 0) return; - score = -score; // sort descending - try { - scoresLock.lock(); - if (control.get()) return; - int dataSize = size.getAndIncrement(); - int index = Arrays.binarySearch(scores, 0, dataSize, score); - if (index < 0) { - index = ~index; - } - System.arraycopy(scores, index, scores, index + 1, dataSize - index); - scores[index] = score; - consumer.add(index, value.searchEntry); - } finally { - scoresLock.unlock(); - } - } finally { - elapsed.incrementAndGet(); - } - }); - } - - return new SearchControl() { - @Override - public void stop() { - control.set(true); - } - - @Override - public boolean isFinished() { - return entries.size() == elapsed.get(); - } - - @Override - public float getProgress() { - return (float) elapsed.get() / entries.size(); - } - }; - } - - public void hit(T entry) { - if (entries.containsKey(entry)) { - hitCount.compute(entry.getIdentifier(), (_id, i) -> i == null ? 1 : i + 1); - } - } - - public static final class Entry { - - public final T searchEntry; - private final String[][] components; - - private Entry(T searchEntry, String[][] components) { - this.searchEntry = searchEntry; - this.components = components; - } - - public float getScore(String term, int hits) { - String ucTerm = term.toUpperCase(Locale.ROOT); - float maxScore = (float) Arrays.stream(components) - .mapToDouble(name -> getScoreFor(ucTerm, name)) - .max().orElse(0.0); - return maxScore * (hits + 1); - } - - /** - * Computes the score for the given name against the given search term. - * - * @param term the search term (expected to be upper-case) - * @param name the entry name, split at word boundaries (see {@link Entry#wordwiseSplit(String)}) - * @return the computed score for the entry - */ - private static float getScoreFor(String term, String[] name) { - int totalLength = Arrays.stream(name).mapToInt(String::length).sum(); - float scorePerChar = 1f / totalLength; - - // This map contains a snapshot of all the states the search has - // been in. The keys are the remaining characters of the search - // term, the values are the maximum scores for that remaining - // search term part. - Map snapshots = new HashMap<>(); - snapshots.put(term, 0f); - - // For each component, start at each existing snapshot, searching - // for the next longest match, and calculate the new score for each - // match length until the maximum. Then the new scores are put back - // into the snapshot map. - for (int componentIndex = 0; componentIndex < name.length; componentIndex++) { - String component = name[componentIndex]; - float posMultiplier = (name.length - componentIndex) * 0.3f; - Map newSnapshots = new HashMap<>(); - for (Map.Entry snapshot : snapshots.entrySet()) { - String remaining = snapshot.getKey(); - float score = snapshot.getValue(); - component = component.toUpperCase(Locale.ROOT); - int l = compareEqualLength(remaining, component); - for (int i = 1; i <= l; i++) { - float baseScore = scorePerChar * i; - float chainBonus = (i - 1) * 0.5f; - merge(newSnapshots, Collections.singletonMap(remaining.substring(i), score + baseScore * posMultiplier + chainBonus), Math::max); - } - } - merge(snapshots, newSnapshots, Math::max); - } - - // Only return the score for when the search term was completely - // consumed. - return snapshots.getOrDefault("", 0f); - } - - private static void merge(Map self, Map source, BiFunction combiner) { - source.forEach((k, v) -> self.compute(k, (_k, v1) -> v1 == null ? v : v == null ? v1 : combiner.apply(v, v1))); - } - - public static Entry from(T e) { - String[][] components = e.getSearchableNames().parallelStream() - .map(Entry::wordwiseSplit) - .toArray(String[][]::new); - return new Entry<>(e, components); - } - - private static int compareEqualLength(String s1, String s2) { - int len = 0; - while (len < s1.length() && len < s2.length() && s1.charAt(len) == s2.charAt(len)) { - len += 1; - } - return len; - } - - /** - * Splits the given input into components, trying to detect word parts. - *

- * Example of how words get split (using | as seperator): - *

MinecraftClientGame -> Minecraft|Client|Game

- *

HTTPInputStream -> HTTP|Input|Stream

- *

class_932 -> class|_|932

- *

X11FontManager -> X|11|Font|Manager

- *

openHTTPConnection -> open|HTTP|Connection

- *

open_http_connection -> open|_|http|_|connection

- * - * @param input the input to split - * @return the resulting components - */ - private static String[] wordwiseSplit(String input) { - List list = new ArrayList<>(); - while (!input.isEmpty()) { - int take; - if (Character.isLetter(input.charAt(0))) { - if (input.length() == 1) { - take = 1; - } else { - boolean nextSegmentIsUppercase = Character.isUpperCase(input.charAt(0)) && Character.isUpperCase(input.charAt(1)); - if (nextSegmentIsUppercase) { - int nextLowercase = 1; - while (Character.isUpperCase(input.charAt(nextLowercase))) { - nextLowercase += 1; - if (nextLowercase == input.length()) { - nextLowercase += 1; - break; - } - } - take = nextLowercase - 1; - } else { - int nextUppercase = 1; - while (nextUppercase < input.length() && Character.isLowerCase(input.charAt(nextUppercase))) { - nextUppercase += 1; - } - take = nextUppercase; - } - } - } else if (Character.isDigit(input.charAt(0))) { - int nextNonNum = 1; - while (nextNonNum < input.length() && Character.isLetter(input.charAt(nextNonNum)) && !Character.isLowerCase(input.charAt(nextNonNum))) { - nextNonNum += 1; - } - take = nextNonNum; - } else { - take = 1; - } - list.add(input.substring(0, take)); - input = input.substring(take); - } - return list.toArray(new String[0]); - } - - } - - @FunctionalInterface - public interface SearchResultConsumer { - void add(int index, T entry); - } - - public interface SearchControl { - void stop(); - - boolean isFinished(); - - float getProgress(); - } - -} -- cgit v1.2.3