package com.ts3client.ui; import com.ts3client.text.TextQuery; import javax.swing.JEditorPane; import javax.swing.JToggleButton; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Document; import javax.swing.text.Highlighter; import java.awt.Color; import java.awt.Point; import java.awt.Rectangle; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; /** * Find in the chat: highlights the query's matches in the selected conversation and * steps through them, newest first. Optionally shows only the messages that match. */ final class ChatSearch implements FindBar.Listener { /** The conversation being searched: whichever chat tab is selected. */ interface Host { /** The selected tab's log, or {@code null} when there is none. */ JEditorPane selectedLog(); /** Shows only the selected tab's messages matching {@code filter}; {@code null} shows all again. */ void showMatching(TextQuery filter); } /** More highlights than this slow painting down, and nobody steps through them one by one. */ private static final int MAX_HIGHLIGHTS = 5000; private final Host host; private final FindBar bar = new FindBar(this); private final JToggleButton onlyMatching = bar.addFilterToggle("Show only matching messages"); private final Highlighter.HighlightPainter matchPainter = new ThemedPainter(false); private final Highlighter.HighlightPainter currentPainter = new ThemedPainter(true); private final List highlightTags = new ArrayList<>(); /** Start and end offsets of each match in the log document, oldest first. */ private final List matches = new ArrayList<>(); private int current = -1; /** The next re-highlight follows a new query, so it starts again from the newest match. */ private boolean freshQuery; private boolean rehighlightQueued; private JEditorPane log; private final DocumentListener docListener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { queueRehighlight(); } @Override public void removeUpdate(DocumentEvent e) { queueRehighlight(); } @Override public void changedUpdate(DocumentEvent e) { } }; /** A theme change re-installs the log's document. */ private final PropertyChangeListener docSwap = e -> { if (e.getOldValue() instanceof Document old) old.removeDocumentListener(docListener); if (e.getNewValue() instanceof Document now) now.addDocumentListener(docListener); queueRehighlight(); }; ChatSearch(Host host) { this.host = host; } FindBar bar() { return bar; } boolean isOpen() { return bar.isOpen(); } void open() { retarget(); bar.open(); } /** The selected tab changed: carry the search over to it. */ void retarget() { JEditorPane now = host.selectedLog(); if (now != log) { detach(); log = now; if (log != null) { log.getDocument().addDocumentListener(docListener); log.addPropertyChangeListener("document", docSwap); } } if (bar.isOpen()) queryChanged(bar.query()); } @Override public void queryChanged(TextQuery query) { freshQuery = true; boolean usable = !query.isEmpty() && !query.isInvalid(); host.showMatching(onlyMatching.isSelected() && usable ? query : null); rehighlight(); } @Override public void next() { step(1); } @Override public void previous() { step(-1); } @Override public void closed() { clearHighlights(); matches.clear(); host.showMatching(null); if (log != null) { log.setCaretPosition(log.getDocument().getLength()); log.requestFocusInWindow(); } } private void step(int delta) { if (matches.isEmpty()) return; current = Math.floorMod(current + delta, matches.size()); paintHighlights(); scrollToCurrent(); updateStatus(); } private void queueRehighlight() { if (!bar.isOpen() || rehighlightQueued) return; rehighlightQueued = true; SwingUtilities.invokeLater(() -> { rehighlightQueued = false; if (bar.isOpen()) rehighlight(); }); } /** Finds the matches in the log as it now reads, keeping the current one where it can. */ private void rehighlight() { int keepStart = !freshQuery && current >= 0 && current < matches.size() ? matches.get(current)[0] : -1; matches.clear(); current = -1; TextQuery query = bar.query(); Matcher m = null; if (log != null) { try { Document doc = log.getDocument(); m = query.matcher(doc.getText(0, doc.getLength())); } catch (BadLocationException ignored) { } } if (m != null) { while (m.find()) { if (m.end() > m.start()) matches.add(new int[]{m.start(), m.end()}); } } if (matches.size() > MAX_HIGHLIGHTS) matches.subList(0, matches.size() - MAX_HIGHLIGHTS).clear(); if (!matches.isEmpty()) { current = matches.size() - 1; if (keepStart >= 0) { for (int i = 0; i < matches.size(); i++) { if (matches.get(i)[0] >= keepStart) { current = i; break; } } } } paintHighlights(); if (freshQuery) scrollToCurrent(); freshQuery = false; updateStatus(); } private void updateStatus() { TextQuery query = bar.query(); if (query.isInvalid()) return; bar.setNavigable(matches.size() > 1); if (query.isEmpty()) bar.clearCount(); else bar.setCount(current + 1, matches.size(), matches.size() == MAX_HIGHLIGHTS); } private void paintHighlights() { clearHighlights(); if (log == null) return; Highlighter h = log.getHighlighter(); for (int i = 0; i < matches.size(); i++) { int[] r = matches.get(i); try { highlightTags.add(h.addHighlight(r[0], r[1], i == current ? currentPainter : matchPainter)); } catch (BadLocationException ignored) { } } } private void clearHighlights() { if (log != null) { Highlighter h = log.getHighlighter(); for (Object tag : highlightTags) h.removeHighlight(tag); } highlightTags.clear(); } /** Brings the current match to the middle of the view, once the log has been laid out. */ private void scrollToCurrent() { if (current < 0 || log == null) return; int start = matches.get(current)[0]; JEditorPane pane = log; SwingUtilities.invokeLater(() -> { if (pane != log || !(pane.getParent() instanceof JViewport viewport)) return; try { Rectangle r = pane.modelToView2D(start).getBounds(); Rectangle view = viewport.getViewRect(); if (view.contains(r)) return; int maxY = Math.max(0, pane.getHeight() - view.height); int y = Math.max(0, Math.min(maxY, r.y - (view.height - r.height) / 2)); viewport.setViewPosition(new Point(view.x, y)); } catch (BadLocationException ignored) { } }); } private void detach() { clearHighlights(); matches.clear(); current = -1; if (log == null) return; log.getDocument().removeDocumentListener(docListener); log.removePropertyChangeListener("document", docSwap); } /** Reads the theme when painting, so highlights follow a light/dark switch. */ private static final class ThemedPainter extends DefaultHighlighter.DefaultHighlightPainter { private final boolean current; ThemedPainter(boolean current) { super(null); this.current = current; } @Override public Color getColor() { return current ? Theme.searchCurrent() : Theme.searchMatch(); } } }