Files
ts3java/ts3-client/swing/src/main/java/com/ts3client/ui/ChatPanel.java
T
erikbrockoandClaude Opus 5.5 d05c04afb4 Find in chat with Ctrl+F
A find bar above the conversations highlights matches and steps through
them, or filters the selected tab down to matching messages. New lines
no longer pull the view away while it is open. Ctrl+F opens it from
anywhere the tree doesn't claim the shortcut.

Note tabs are now found by their scroll pane like other tabs, so sending
checks for a target instead of assuming every tab has one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:09:45 +00:00

595 lines
23 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.text.BBCode;
import com.ts3client.text.HtmlText;
import com.ts3client.text.TextQuery;
import com.ts3client.text.TsLink;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Chat area with one tab per conversation (server, current channel and one per
* private chat). The tab strip sits between the log and the input line. Logs are
* rendered as HTML: sender names are links that open the client context menu,
* and message bodies go through the {@link BBCode} renderer.
*/
public final class ChatPanel extends JPanel {
/** Where an outgoing message should go. */
public enum Target {CHANNEL, SERVER, PRIVATE}
public interface SendHandler {
/** {@code clientId} is only meaningful for {@link Target#PRIVATE}. */
void send(Target target, int clientId, String text);
}
/** Invoked when a client or channel link in the log is clicked. */
public interface LinkHandler {
void onClientLink(TsLink.Ref ref, Component source, int x, int y);
void onChannelLink(TsLink.Ref ref, Component source, int x, int y);
}
private final JTabbedPane tabs = new JTabbedPane(JTabbedPane.BOTTOM);
private final JTextField input = new JTextField();
private final SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
/** Tab strip height, so a tab with no icon still lines up with the others. */
private static final int HEADER_HEIGHT = 20;
private static final String NO_SERVER = "Server";
private static final String NO_CHANNEL = "Channel";
private final Tab serverTab = new Tab(Target.SERVER, 0, NO_SERVER, Icons.server());
private final Tab channelTab = new Tab(Target.CHANNEL, 0, NO_CHANNEL, Icons.channelChat());
/** Private chats keyed by the peer's client id. */
private final Map<Integer, Tab> privateTabs = new LinkedHashMap<>();
/** Static-content tabs (e.g. a moved-out description), keyed by caller-chosen id. */
private final Map<String, Tab> noteTabs = new LinkedHashMap<>();
private final TabDragReorder dragReorder = new TabDragReorder(tabs, this::moveTab);
private final ChatSearch search = new ChatSearch(new ChatSearch.Host() {
@Override
public JEditorPane selectedLog() {
Tab t = selectedTab();
return t == null ? null : t.log;
}
@Override
public void showMatching(TextQuery filter) {
Tab t = selectedTab();
if (t != null) t.showMatching(filter);
}
});
private SendHandler sendHandler;
private LinkHandler linkHandler;
public ChatPanel() {
super(new BorderLayout());
tabs.setFont(Theme.uiFont());
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
// Half the look and feel's leading padding: these tabs carry a name that is worth
// the width, and their headers bring their own spacing.
tabs.putClientProperty("JTabbedPane.tabInsets", new Insets(4, 6, 4, 12));
addTab(serverTab, false);
addTab(channelTab, false);
tabs.setSelectedIndex(0);
tabs.addChangeListener(e -> {
Tab t = selectedTab();
if (t != null) t.setUnread(false);
// A search filters only the tab it is in; the one left behind shows everything again.
for (Tab other : allTabs()) {
if (other != t) other.showMatching(null);
}
search.retarget();
});
tabs.addMouseWheelListener(this::onWheel);
dragReorder.attach(tabs);
add(tabs, BorderLayout.CENTER);
add(search.bar(), BorderLayout.NORTH);
String find = "ts3-chat-find";
getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), find);
getActionMap().put(find, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
openFind();
}
});
JPanel bottom = new JPanel(new BorderLayout(UIScale.scale(4), 0));
bottom.setBorder(new ScaledEmptyBorder(4, 0, 0, 0));
bottom.add(input, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
input.addActionListener(e -> fireSend());
setInputEnabled(false);
}
public void setSendHandler(SendHandler h) {
this.sendHandler = h;
}
public void setLinkHandler(LinkHandler h) {
this.linkHandler = h;
}
/** Opens the find bar on the selected conversation. */
public void openFind() {
edt(search::open);
}
/** Appends text to the input line, e.g. a client link dropped onto the chat. */
public void appendToInput(String text) {
edt(() -> {
String cur = input.getText();
input.setText(cur.isEmpty() || cur.endsWith(" ") ? cur + text : cur + " " + text);
input.requestFocusInWindow();
});
}
/** Names the server tab after the server we are on; blank falls back to "Server". */
public void setServerName(String name) {
edt(() -> serverTab.setTitle(name == null || name.isBlank() ? NO_SERVER : name));
}
/** Names the channel tab after the channel we are in; blank falls back to "Channel". */
public void setChannelName(String name) {
edt(() -> channelTab.setTitle(name == null || name.isBlank() ? NO_CHANNEL : name));
}
public void setInputEnabled(boolean enabled) {
input.setEnabled(enabled);
}
/** Opens (or focuses) the private chat with {@code clientId}. */
public void openPrivateChat(int clientId, String nickname) {
openPrivateChat(clientId, "", nickname);
}
/** Opens (or focuses) the private chat with {@code clientId}. */
public void openPrivateChat(int clientId, String uniqueId, String nickname) {
edt(() -> {
Tab tab = privateTab(clientId, uniqueId, nickname);
tabs.setSelectedComponent(tab.scroll);
input.requestFocusInWindow();
});
}
public void setServerHistory(List<String> htmlEntries) {
edt(() -> serverTab.setHistory(htmlEntries));
}
public void setChannelHistory(List<String> htmlEntries) {
edt(() -> channelTab.setHistory(htmlEntries));
}
public void setPrivateHistory(int clientId, String nickname, List<String> htmlEntries) {
edt(() -> privateTab(clientId, "", nickname).setHistory(htmlEntries));
}
/** Drops every private chat tab, e.g. after disconnecting. */
public void closePrivateChats() {
edt(() -> {
for (Tab t : privateTabs.values()) tabs.remove(t.scroll);
privateTabs.clear();
});
}
/** Drops every static-content tab (moved-out descriptions), e.g. after disconnecting. */
public void closeNoteTabs() {
edt(() -> {
for (Tab t : noteTabs.values()) tabs.remove(t.scroll);
noteTabs.clear();
});
}
/** Closes a single static-content tab by its key, if open; does not run its {@code onClose}. */
public void closeNoteTab(String key) {
edt(() -> {
Tab tab = noteTabs.remove(key);
if (tab != null) tabs.remove(tab.scroll);
});
}
/**
* Opens (or replaces the content of, and focuses) a static-content tab, e.g. a
* channel/client description moved out of the info panel. {@code onClose} runs
* when the tab is closed, so the caller can un-hide the description again.
*/
public void openDescriptionTab(String key, Icon icon, String title, String htmlBody, Runnable onClose) {
edt(() -> {
Tab tab = noteTabs.get(key);
if (tab == null) {
tab = new Tab(key, icon, title, onClose);
noteTabs.put(key, tab);
addTab(tab, true);
}
tab.setStaticContent(htmlBody);
tabs.setSelectedComponent(tab.scroll);
});
}
private void fireSend() {
String text = input.getText().trim();
if (text.isEmpty() || sendHandler == null) return;
Tab tab = selectedTab();
if (tab == null || tab.target == null) return;
sendHandler.send(tab.target, tab.clientId, text);
input.setText("");
}
// ---- append helpers (safe from any thread) ----
/** System notices always land in the server tab. */
public void appendSystem(String text) {
edt(() -> serverTab.appendLine("<span class=\"muted\">" + stamp()
+ BBCode.escape(text) + "</span>"));
}
/**
* Server-side events (client joins/leaves/moves, group changes, channel edits, …).
* These lines name clients and channels with TeamSpeak's own links, which stay
* clickable here — everything else in them is literal text.
*/
public void appendServerLog(String text) {
edt(() -> serverTab.appendLine("<span class=\"event\">" + stamp()
+ BBCode.linksToHtml(text) + "</span>"));
}
public void appendServerLogHtml(String html) {
edt(() -> serverTab.appendRawHtml(html));
}
public void appendServerMessage(int fromId, String from, String text) {
appendServerMessage(fromId, "", from, text);
}
public void appendServerMessage(int fromId, String uniqueId, String from, String text) {
edt(() -> serverTab.appendMessage(fromId, uniqueId, from, text));
}
public void appendChannelMessage(int fromId, String from, String text) {
appendChannelMessage(fromId, "", from, text);
}
public void appendChannelMessage(int fromId, String uniqueId, String from, String text) {
edt(() -> channelTab.appendMessage(fromId, uniqueId, from, text));
}
/** Appends to the private chat with {@code peerId}, creating the tab if needed. */
public void appendPrivateMessage(int peerId, String peerName, int fromId, String from, String text) {
appendPrivateMessage(peerId, "", peerName, fromId, "", from, text);
}
/** Appends to the private chat with {@code peerId}, creating the tab if needed. */
public void appendPrivateMessage(int peerId, String peerUniqueId, String peerName,
int fromId, String fromUniqueId, String from, String text) {
edt(() -> privateTab(peerId, peerUniqueId, peerName).appendMessage(fromId, fromUniqueId, from, text));
}
private String stamp() {
return "[" + time.format(new Date()) + "] ";
}
private Tab privateTab(int clientId, String nickname) {
return privateTab(clientId, "", nickname);
}
private Tab privateTab(int clientId, String uniqueId, String nickname) {
Tab tab = privateTabs.get(clientId);
if (tab == null) {
tab = new Tab(Target.PRIVATE, clientId, uniqueId, nickname, Icons.privateChat());
privateTabs.put(clientId, tab);
addTab(tab, true);
} else {
tab.setClientUniqueId(uniqueId);
}
return tab;
}
private void addTab(Tab tab, boolean closable) {
tabs.addTab(tab.title, tab.scroll);
tabs.setTabComponentAt(tabs.indexOfComponent(tab.scroll), tab.header(closable));
}
private void closeTab(Tab tab) {
if (tab.noteKey != null) {
noteTabs.remove(tab.noteKey);
if (tab.onClose != null) tab.onClose.run();
} else {
privateTabs.remove(tab.clientId);
}
tabs.remove(tab.scroll);
}
/** Drags a tab from one position to another, keeping the current selection on screen. */
private void moveTab(int from, int to) {
if (from < 0 || to < 0 || from >= tabs.getTabCount() || to >= tabs.getTabCount() || from == to) return;
Component content = tabs.getComponentAt(from);
String title = tabs.getTitleAt(from);
Icon icon = tabs.getIconAt(from);
String tip = tabs.getToolTipTextAt(from);
Component header = tabs.getTabComponentAt(from);
boolean wasSelected = tabs.getSelectedIndex() == from;
tabs.removeTabAt(from);
tabs.insertTab(title, icon, content, tip, to);
tabs.setTabComponentAt(to, header);
if (wasSelected) tabs.setSelectedIndex(to);
}
private void onWheel(MouseWheelEvent e) {
Component content = tabs.getSelectedComponent();
if (content != null && content.getBounds().contains(e.getPoint())) return;
int steps = e.getWheelRotation();
if (steps == 0) return;
int target = Math.max(0, Math.min(tabs.getTabCount() - 1, tabs.getSelectedIndex() + steps));
if (target != tabs.getSelectedIndex()) tabs.setSelectedIndex(target);
e.consume();
}
private Tab selectedTab() {
Component c = tabs.getSelectedComponent();
if (c == serverTab.scroll) return serverTab;
if (c == channelTab.scroll) return channelTab;
for (Tab t : privateTabs.values()) {
if (t.scroll == c) return t;
}
for (Tab t : noteTabs.values()) {
if (t.scroll == c) return t;
}
return null;
}
private List<Tab> allTabs() {
List<Tab> all = new ArrayList<>();
all.add(serverTab);
all.add(channelTab);
all.addAll(privateTabs.values());
all.addAll(noteTabs.values());
return all;
}
private void edt(Runnable r) {
if (SwingUtilities.isEventDispatchThread()) r.run();
else SwingUtilities.invokeLater(r);
}
/** One conversation: its HTML log, its scroll pane and the tab-strip header. */
private final class Tab {
final Target target;
final int clientId;
private String clientUniqueId;
private String title;
final JEditorPane log = HtmlStyles.pane("font-family:sans-serif; font-size:11px; margin:"
+ HtmlStyles.px(4) + " " + HtmlStyles.px(6) + ";");
final JScrollPane scroll;
/** Set for a static-content tab (e.g. a moved-out description); null for a conversation. */
final String noteKey;
final Runnable onClose;
private final Icon icon;
private JLabel titleLabel;
/** Everything this conversation has shown, whether or not a search currently hides it. */
private final List<String> entries = new ArrayList<>();
/** Only messages matching this are on screen; {@code null} shows all. */
private TextQuery filter;
Tab(Target target, int clientId, String title, Icon icon) {
this(target, clientId, "", title, icon, null, null);
}
Tab(Target target, int clientId, String clientUniqueId, String title, Icon icon) {
this(target, clientId, clientUniqueId, title, icon, null, null);
}
/** A static-content tab: no send target, closing it runs {@code onClose}. */
Tab(String noteKey, Icon icon, String title, Runnable onClose) {
this(null, 0, "", title, icon, noteKey, onClose);
}
private Tab(Target target, int clientId, String clientUniqueId, String title,
Icon icon, String noteKey, Runnable onClose) {
this.target = target;
this.clientId = clientId;
this.clientUniqueId = clientUniqueId == null ? "" : clientUniqueId;
this.title = title;
this.icon = icon;
this.noteKey = noteKey;
this.onClose = onClose;
log.setText("<html><body><div id=\"chatlog\"></div></body></html>");
log.addHyperlinkListener(e -> {
if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) return;
onLink(e.getDescription());
});
scroll = new JScrollPane(log);
HtmlStyles.fillViewport(log);
scroll.setBorder(BorderFactory.createEmptyBorder());
}
void setClientUniqueId(String uniqueId) {
if (uniqueId != null && !uniqueId.isBlank()) clientUniqueId = uniqueId;
}
private void onLink(String href) {
if (href == null) return;
TsLink.Ref ref = TsLink.parse(href);
if (ref == null) {
Links.open(href, ChatPanel.this);
return;
}
if (linkHandler == null) return;
Point p = log.getMousePosition();
if (p == null) p = new Point(0, 0);
if (ref.client) linkHandler.onClientLink(ref, log, p.x, p.y);
else linkHandler.onChannelLink(ref, log, p.x, p.y);
}
Component header(boolean closable) {
// Only the height is pinned: a fixed width would freeze the tab at the width of
// whatever name it was built with, clipping longer ones (and the bold unread font).
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(2), 0)) {
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(d.width, Math.max(d.height, UIScale.scale(HEADER_HEIGHT)));
}
};
p.setOpaque(false);
titleLabel = new JLabel(title, icon, JLabel.LEADING);
titleLabel.setFont(Theme.uiFont());
titleLabel.setIconTextGap(UIScale.scale(3));
p.add(titleLabel);
dragReorder.attach(p);
dragReorder.attach(titleLabel);
if (closable) {
JLabel close = new JLabel("×");
close.setFont(Theme.uiBold());
close.setForeground(Theme.chatSystem());
close.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
close.setToolTipText("Close chat");
close.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
closeTab(Tab.this);
}
});
p.add(close);
}
return p;
}
/** Renames the tab in place — the server and channel tabs follow where we are. */
void setTitle(String title) {
if (title.equals(this.title)) return;
this.title = title;
int index = tabs.indexOfComponent(scroll);
if (index >= 0) tabs.setTitleAt(index, title);
if (titleLabel == null) return;
titleLabel.setText(title);
// The strip lays its tabs out itself; it has to re-measure this one.
tabs.revalidate();
tabs.repaint();
}
void setUnread(boolean unread) {
if (titleLabel == null) return;
titleLabel.setFont(unread ? Theme.uiBold() : Theme.uiFont());
titleLabel.setForeground(unread ? Theme.accent() : null);
}
void appendMessage(int fromId, String fromUniqueId, String from, String text) {
String name = BBCode.escape(from);
String sender = fromId > 0
? "<a class=\"" + BBCode.IDENTITY_LINK_CLASS + "\" href=\""
+ BBCode.escape(TsLink.clientHref(fromId,
fromUniqueId == null || fromUniqueId.isBlank() ? clientUniqueId : fromUniqueId,
from)) + "\">" + name + "</a>"
: "<span class=\"name\">" + name + "</span>";
appendLine("<span class=\"muted\">" + stamp() + "</span>"
+ sender + ": " + BBCode.toHtml(text));
}
void setHistory(List<String> htmlEntries) {
entries.clear();
if (htmlEntries != null) {
for (String entry : htmlEntries) entries.add(normalizeTs3LogEntry(entry));
}
render();
}
/** Replaces the whole log with fixed content; used by static-content tabs. */
void setStaticContent(String html) {
entries.clear();
entries.add(html);
render();
}
void showMatching(TextQuery filter) {
if (Objects.equals(this.filter, filter)) return;
this.filter = filter;
render();
}
private boolean shows(String entry) {
return filter == null || filter.matches(HtmlText.plain(entry));
}
private void render() {
StringBuilder html = new StringBuilder();
for (String entry : entries) {
if (shows(entry)) html.append(entry);
}
log.setText("<html><body><div id=\"chatlog\">" + html + "</div></body></html>");
log.setCaretPosition(noteKey != null ? 0 : log.getDocument().getLength());
}
void appendLine(String html) {
appendRawHtml("<div>" + html + "</div>");
}
void appendRawHtml(String html) {
String entry = normalizeTs3LogEntry(html);
entries.add(entry);
if (shows(entry)) {
try {
HTMLDocument doc = (HTMLDocument) log.getDocument();
doc.insertBeforeEnd(doc.getElement("chatlog"), entry);
// Following new lines would pull the view away from the match being read.
if (!search.isOpen()) log.setCaretPosition(doc.getLength());
} catch (BadLocationException | IOException ignored) {
}
}
if (tabs.getSelectedComponent() != scroll) setUnread(true);
}
private String normalizeTs3LogEntry(String html) {
if (html == null || html.isBlank()) return "";
String normalized = html
.replaceAll("(?i)<img\\b[^>]*>", "")
.replaceFirst("(?i)^\\s*<p\\b", "<div")
.replaceFirst("(?i)</p>\\s*$", "</div>");
return normalized.startsWith("<div") ? normalized : "<div>" + normalized + "</div>";
}
}
}