From 8255d986ac54bc177b5114ea4a9a18342a4bee25 Mon Sep 17 00:00:00 2001 From: ericek111 Date: Sun, 4 Oct 2026 13:19:52 +0000 Subject: [PATCH] Add the Server Log window Tools > Server Log (Ctrl+Shift+L), offered with b_virtualserver_log_view, reads the virtual server's log with logview, a hundred lines at a time, with Show Older going further back. As in TS3, lines can be narrowed by level, left out by exclude terms, coloured by keyword, and shown in UTC or local time; the choices are kept in the settings. The find bar, with its show-only-matches toggle, takes the place of TS3's separate search and filter fields. Co-Authored-By: Claude Opus 5.5 --- .../ts3client/config/ServerLogSettings.java | 132 +++++++ .../java/com/ts3client/config/Settings.java | 5 + .../ts3client/net/ConnectionEventHandler.java | 1 + .../com/ts3client/net/ServerLogAdmin.java | 82 ++++ .../com/ts3client/net/ServerLogEntry.java | 49 +++ .../java/com/ts3client/net/ServerLogPage.java | 15 + .../ts3client/net/TeamspeakConnection.java | 13 +- .../com/ts3client/session/ServerSession.java | 5 + .../config/ServerLogSettingsTest.java | 77 ++++ .../com/ts3client/net/ServerLogEntryTest.java | 39 ++ .../java/com/ts3client/ui/ChatSearch.java | 12 +- .../com/ts3client/ui/ListEditorDialog.java | 184 +++++++++ .../main/java/com/ts3client/ui/MainFrame.java | 10 + .../java/com/ts3client/ui/MainMenuBar.java | 17 +- .../com/ts3client/ui/ServerLogDialog.java | 366 ++++++++++++++++++ .../ts3client/ui/ServerLogExcludeDialog.java | 27 ++ .../ui/ServerLogHighlightDialog.java | 145 +++++++ .../main/java/com/ts3client/ui/ServerTab.java | 17 +- 18 files changed, 1190 insertions(+), 6 deletions(-) create mode 100644 ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java create mode 100644 ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java create mode 100644 ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java create mode 100644 ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java create mode 100644 ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java diff --git a/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java b/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java new file mode 100644 index 0000000..8c848bc --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/config/ServerLogSettings.java @@ -0,0 +1,132 @@ +package com.ts3client.config; + +import com.ts3client.net.ServerLogEntry.Level; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +/** + * How the Server Log window shows the log: which levels, in which time zone, which lines + * stand out in colour and which are left out — TeamSpeak's ServerLogView settings. + */ +public final class ServerLogSettings { + + /** + * Lines containing {@code keyword} (ignoring case) are drawn in these colours. + * + * @param foreground an RGB colour, or {@code null} for the usual text colour + * @param background an RGB colour, or {@code null} for none + */ + public record Highlight(String keyword, Integer foreground, Integer background) { + } + + private static final String PREFIX = "serverLog."; + + /** The levels the window offers to show; the server's debug levels never reach a virtual server log. */ + public static final List SHOWN_LEVELS = List.of(Level.CRITICAL, Level.ERROR, Level.WARNING, Level.INFO); + + public final Set levels = EnumSet.copyOf(SHOWN_LEVELS); + /** Show times in the local time zone rather than in UTC, as the server writes them. */ + public boolean localTime; + /** Checked in order; the first keyword a line contains decides its colours. */ + public final List highlights = new ArrayList<>(List.of( + new Highlight("Critical", 0xC00000, null), + new Highlight("Error", 0xE03030, null), + new Highlight("Warning", 0xC07000, null))); + /** Lines containing any of these (ignoring case) are not shown. */ + public final List excludes = new ArrayList<>(); + + /** Whether a line passes the level choice and the exclude filter. */ + public boolean shows(Level level, String line) { + if (!levels.contains(level) && SHOWN_LEVELS.contains(level)) return false; + String lower = line.toLowerCase(Locale.ROOT); + for (String term : excludes) { + if (!term.isEmpty() && lower.contains(term.toLowerCase(Locale.ROOT))) return false; + } + return true; + } + + /** The first highlight whose keyword {@code line} contains, or {@code null}. */ + public Highlight highlightFor(String line) { + String lower = line.toLowerCase(Locale.ROOT); + for (Highlight h : highlights) { + if (!h.keyword().isEmpty() && lower.contains(h.keyword().toLowerCase(Locale.ROOT))) return h; + } + return null; + } + + void load(Properties p) { + String lv = p.getProperty(PREFIX + "levels"); + if (lv != null) { + levels.clear(); + for (String name : lv.split(",")) { + try { + levels.add(Level.valueOf(name.trim())); + } catch (IllegalArgumentException ignored) { + // dropped level name + } + } + } + localTime = Boolean.parseBoolean(p.getProperty(PREFIX + "localTime", Boolean.toString(localTime))); + if (p.getProperty(PREFIX + "highlights") != null) { + highlights.clear(); + int n = parseCount(p.getProperty(PREFIX + "highlights")); + for (int i = 0; i < n; i++) { + String keyword = p.getProperty(PREFIX + "highlight." + i + ".keyword"); + if (keyword == null) continue; + highlights.add(new Highlight(keyword, parseColor(p.getProperty(PREFIX + "highlight." + i + ".fg")), + parseColor(p.getProperty(PREFIX + "highlight." + i + ".bg")))); + } + } + if (p.getProperty(PREFIX + "excludes") != null) { + excludes.clear(); + int n = parseCount(p.getProperty(PREFIX + "excludes")); + for (int i = 0; i < n; i++) { + String term = p.getProperty(PREFIX + "exclude." + i); + if (term != null) excludes.add(term); + } + } + } + + void store(Properties p) { + p.stringPropertyNames().stream() + .filter(k -> k.startsWith(PREFIX + "highlight.") || k.startsWith(PREFIX + "exclude.")) + .forEach(p::remove); + p.setProperty(PREFIX + "levels", String.join(",", levels.stream().map(Enum::name).toList())); + p.setProperty(PREFIX + "localTime", Boolean.toString(localTime)); + p.setProperty(PREFIX + "highlights", Integer.toString(highlights.size())); + for (int i = 0; i < highlights.size(); i++) { + Highlight h = highlights.get(i); + p.setProperty(PREFIX + "highlight." + i + ".keyword", h.keyword()); + p.setProperty(PREFIX + "highlight." + i + ".fg", formatColor(h.foreground())); + p.setProperty(PREFIX + "highlight." + i + ".bg", formatColor(h.background())); + } + p.setProperty(PREFIX + "excludes", Integer.toString(excludes.size())); + for (int i = 0; i < excludes.size(); i++) p.setProperty(PREFIX + "exclude." + i, excludes.get(i)); + } + + private static int parseCount(String v) { + try { + return Math.max(0, Integer.parseInt(v.trim())); + } catch (NumberFormatException e) { + return 0; + } + } + + private static Integer parseColor(String v) { + if (v == null || v.isBlank()) return null; + try { + return Integer.parseInt(v.trim().replace("#", ""), 16) & 0xFFFFFF; + } catch (NumberFormatException e) { + return null; + } + } + + private static String formatColor(Integer rgb) { + return rgb == null ? "" : String.format("#%06X", rgb); + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/config/Settings.java b/ts3-client/core/src/main/java/com/ts3client/config/Settings.java index 7c1cfc4..251271f 100644 --- a/ts3-client/core/src/main/java/com/ts3client/config/Settings.java +++ b/ts3-client/core/src/main/java/com/ts3client/config/Settings.java @@ -181,6 +181,9 @@ public final class Settings { /** The ban list columns the user shows, comma-separated column names; empty for the default set. */ public String banListColumns = ""; + /** What the Server Log window shows and how. */ + public final ServerLogSettings serverLog = new ServerLogSettings(); + /** Which actions make a sound, and which ones are important enough to survive muting. */ public final NotificationSettings notifications = new NotificationSettings(); @@ -289,6 +292,7 @@ public final class Settings { banHighlightOwn = parseB(props.getProperty("banHighlightOwn"), banHighlightOwn); banListColumns = props.getProperty("banListColumns", banListColumns); notifications.load(props); + serverLog.load(props); contactDefaults.load(props); colorContacts = parseB(props.getProperty("colorContacts"), colorContacts); descriptionPictures = parseB(props.getProperty("descriptionPictures"), descriptionPictures); @@ -345,6 +349,7 @@ public final class Settings { props.setProperty("banHighlightOwn", Boolean.toString(banHighlightOwn)); props.setProperty("banListColumns", banListColumns); notifications.store(props); + serverLog.store(props); contactDefaults.store(props); props.setProperty("colorContacts", Boolean.toString(colorContacts)); props.setProperty("descriptionPictures", Boolean.toString(descriptionPictures)); diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java index 536b178..968c51a 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/ConnectionEventHandler.java @@ -671,6 +671,7 @@ final class ConnectionEventHandler implements TS3Listener { else if ("notifytokenlist".equals(e.getCommand())) conn.privilegeKeys.onListEntry(e); else if ("notifytokenadd".equals(e.getCommand())) conn.privilegeKeys.onAdded(e); else if ("notifycomplainlist".equals(e.getCommand())) conn.complaints.onListEntry(e); + else if ("notifyserverlog".equals(e.getCommand())) conn.serverLog.onLine(e); } // ---- helpers ---- diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java new file mode 100644 index 0000000..9930afd --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogAdmin.java @@ -0,0 +1,82 @@ +package com.ts3client.net; + +import com.github.manevolent.ts3j.command.CommandException; +import com.github.manevolent.ts3j.command.SingleCommand; +import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; +import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; +import com.github.manevolent.ts3j.protocol.ProtocolRole; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Reads the virtual server's log with {@code logview}, which answers with one + * {@code notifyserverlog} per line, newest first, each also carrying {@code last_pos}: where + * the lines it returned begin in the log file, and so where the older ones end. + * + *

Split out of {@link TeamspeakConnection} like {@link BanAdmin}. Every call here blocks + * and must run off the UI thread; the connection's public wrapper does that. + */ +final class ServerLogAdmin { + + /** The most lines {@code logview} returns at once. */ + static final int PAGE_LINES = 100; + + /** What {@code logview} may answer for an empty log. */ + private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; + + private final TeamspeakConnection conn; + + /** The {@code logview} reply in progress; one request may be in flight at a time. */ + private volatile Reply reply; + + private static final class Reply { + final List entries = Collections.synchronizedList(new ArrayList<>()); + volatile long lastPos; + } + + ServerLogAdmin(TeamspeakConnection conn) { + this.conn = conn; + } + + /** + * Reads the newest lines, or with {@code olderFrom} > 0 those ending there (from an + * earlier {@link ServerLogPage#olderFrom()}). + */ + synchronized ServerLogPage read(long olderFrom) throws Exception { + SingleCommand cmd = new SingleCommand("logview", ProtocolRole.CLIENT); + cmd.add(new CommandSingleParameter("lines", Integer.toString(PAGE_LINES))); + if (olderFrom > 0) cmd.add(new CommandSingleParameter("begin_pos", Long.toString(olderFrom))); + cmd.add(new CommandSingleParameter("reverse", "1")); + cmd.add(new CommandSingleParameter("instance", "0")); + Reply r = new Reply(); + reply = r; + try { + conn.socket().executeCommand(cmd).complete(); + conn.awaitEventsProcessed(); + } catch (CommandException e) { + if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; + } finally { + reply = null; + } + List entries = new ArrayList<>(r.entries); + Collections.reverse(entries); + return new ServerLogPage(entries, entries.isEmpty() ? 0 : r.lastPos); + } + + void onLine(UnknownTeamspeakEvent e) { + Reply r = reply; + if (r == null) return; + String line = e.get("l"); + if (line != null && !line.isEmpty()) r.entries.add(ServerLogEntry.parse(line)); + String lastPos = e.get("last_pos"); + if (lastPos != null) { + try { + r.lastPos = Long.parseLong(lastPos.trim()); + } catch (NumberFormatException ignored) { + // keep what the earlier lines said + } + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java new file mode 100644 index 0000000..8792b2c --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogEntry.java @@ -0,0 +1,49 @@ +package com.ts3client.net; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Locale; + +/** + * One line of the virtual server's log, as {@code logview} hands it over: + * {@code 2026-10-04 13:11:01.038554|INFO |VirtualServer |1 |message}. + * + * @param timestamp when the server wrote it, in UTC as the server logs; {@code null} if the line had none + * @param channel the server component that wrote it, e.g. {@code VirtualServer} or {@code PktHandler} + */ +public record ServerLogEntry(LocalDateTime timestamp, Level level, String channel, String message) { + + /** The server's log levels, most severe first. */ + public enum Level { + CRITICAL, ERROR, WARNING, INFO, DEBUG, DEVEL + } + + private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSSSSS]"); + + /** + * Reads a log line. One whose timestamp is damaged — the server cuts the start off the + * file's very first line — keeps the rest; one that does not follow the format at all + * is kept whole as an info message. + */ + public static ServerLogEntry parse(String line) { + String[] fields = line.split("\\|", 5); + if (fields.length == 5) { + try { + Level level = Level.valueOf(fields[1].trim().toUpperCase(Locale.ROOT)); + return new ServerLogEntry(timestamp(fields[0]), level, fields[2].trim(), fields[4]); + } catch (IllegalArgumentException ignored) { + // not a line of ours; fall through + } + } + return new ServerLogEntry(null, Level.INFO, "", line); + } + + private static LocalDateTime timestamp(String field) { + try { + return LocalDateTime.parse(field.trim(), TIMESTAMP); + } catch (DateTimeParseException e) { + return null; + } + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java new file mode 100644 index 0000000..16f9d62 --- /dev/null +++ b/ts3-client/core/src/main/java/com/ts3client/net/ServerLogPage.java @@ -0,0 +1,15 @@ +package com.ts3client.net; + +import java.util.List; + +/** + * A stretch of the server's log, oldest line first. + * + * @param olderFrom where the log's older lines end, to ask for them next; 0 once the start is reached + */ +public record ServerLogPage(List entries, long olderFrom) { + + public boolean hasOlder() { + return olderFrom > 0; + } +} diff --git a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java index eda3f06..40f174a 100644 --- a/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/com/ts3client/net/TeamspeakConnection.java @@ -97,10 +97,11 @@ public final class TeamspeakConnection implements TS3Listener { final ConnectionStatsCollector stats = new ConnectionStatsCollector(this); /** Channel editing and the server's icon store; package-private for {@link ConnectionEventHandler}. */ final ChannelAdmin channels = new ChannelAdmin(this); - /** The server's ban list, privilege keys and complaints; also package-private for {@link ConnectionEventHandler}. */ + /** The server's ban list, privilege keys, complaints and log; also package-private for {@link ConnectionEventHandler}. */ final BanAdmin bans = new BanAdmin(this); final PrivilegeKeyAdmin privilegeKeys = new PrivilegeKeyAdmin(this); final ComplaintAdmin complaints = new ComplaintAdmin(this); + final ServerLogAdmin serverLog = new ServerLogAdmin(this); private final AvatarAdmin avatarAdmin = new AvatarAdmin(this); /* @@ -1040,6 +1041,16 @@ public final class TeamspeakConnection implements TS3Listener { }); } + // ---- server log ---- + + /** + * Reads the server's newest log lines, or with {@code olderFrom} > 0 the ones before an + * earlier page's, delivering them (or a failure message) off the UI thread. + */ + public void requestServerLog(long olderFrom, BiConsumer callback) { + run(callback, () -> serverLog.read(olderFrom)); + } + // ---- bans ---- /** Reads the server's ban list, delivering it (or a failure message) off the UI thread. */ diff --git a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java index 78e55ad..a8adb6d 100644 --- a/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/com/ts3client/session/ServerSession.java @@ -437,6 +437,11 @@ public final class ServerSession { return permits("b_client_complain_list"); } + /** Whether the server grants us {@code b_virtualserver_log_view}; offered while unknown. */ + public boolean canViewServerLog() { + return permits("b_virtualserver_log_view"); + } + /** Whether the server grants us {@code b_virtualserver_token_list}; offered while unknown. */ public boolean canListPrivilegeKeys() { return permits("b_virtualserver_token_list"); diff --git a/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java b/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java new file mode 100644 index 0000000..112125b --- /dev/null +++ b/ts3-client/core/src/test/java/com/ts3client/config/ServerLogSettingsTest.java @@ -0,0 +1,77 @@ +package com.ts3client.config; + +import com.ts3client.config.ServerLogSettings.Highlight; +import com.ts3client.net.ServerLogEntry.Level; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ServerLogSettingsTest { + + @Test + void whatIsStoredLoadsBack() { + ServerLogSettings saved = new ServerLogSettings(); + saved.levels.remove(Level.INFO); + saved.localTime = true; + saved.highlights.clear(); + saved.highlights.add(new Highlight("banned", 0x112233, null)); + saved.highlights.add(new Highlight("kicked", null, 0xABCDEF)); + saved.excludes.add("ping timeout"); + Properties p = new Properties(); + saved.store(p); + + ServerLogSettings loaded = new ServerLogSettings(); + loaded.load(p); + assertEquals(Set.of(Level.CRITICAL, Level.ERROR, Level.WARNING), loaded.levels); + assertTrue(loaded.localTime); + assertEquals(saved.highlights, loaded.highlights); + assertEquals(List.of("ping timeout"), loaded.excludes); + } + + @Test + void shorterListsLeaveNoStaleEntriesBehind() { + ServerLogSettings s = new ServerLogSettings(); + s.excludes.addAll(List.of("a", "b", "c")); + Properties p = new Properties(); + s.store(p); + s.excludes.clear(); + s.highlights.clear(); + s.store(p); + + assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.exclude."))); + assertTrue(p.stringPropertyNames().stream().noneMatch(k -> k.startsWith("serverLog.highlight."))); + ServerLogSettings loaded = new ServerLogSettings(); + loaded.load(p); + assertTrue(loaded.excludes.isEmpty()); + assertTrue(loaded.highlights.isEmpty()); + } + + @Test + void levelsAndExcludesDecideWhatShows() { + ServerLogSettings s = new ServerLogSettings(); + s.levels.remove(Level.INFO); + s.excludes.add("Ping Timeout"); + assertFalse(s.shows(Level.INFO, "client connected")); + assertTrue(s.shows(Level.WARNING, "something odd")); + assertFalse(s.shows(Level.WARNING, "dropping client because of ping timeout")); + assertTrue(s.shows(Level.DEBUG, "levels the window has no box for always show")); + } + + @Test + void theFirstMatchingKeywordWins() { + ServerLogSettings s = new ServerLogSettings(); + s.highlights.clear(); + s.highlights.add(new Highlight("error", 1, null)); + s.highlights.add(new Highlight("client", 2, null)); + assertEquals(1, s.highlightFor("ERROR client gone").foreground()); + assertEquals(2, s.highlightFor("client joined").foreground()); + assertNull(s.highlightFor("nothing here")); + } +} diff --git a/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java b/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java new file mode 100644 index 0000000..0630a4d --- /dev/null +++ b/ts3-client/core/src/test/java/com/ts3client/net/ServerLogEntryTest.java @@ -0,0 +1,39 @@ +package com.ts3client.net; + +import com.ts3client.net.ServerLogEntry.Level; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ServerLogEntryTest { + + @Test + void readsTheServersLineFormat() { + ServerLogEntry e = ServerLogEntry.parse("2026-10-04 13:11:01.038554|WARNING |VirtualServer |1 |" + + "client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)"); + assertEquals(LocalDateTime.of(2026, 10, 4, 13, 11, 1, 38_554_000), e.timestamp()); + assertEquals(Level.WARNING, e.level()); + assertEquals("VirtualServer", e.channel()); + assertEquals("client 'a|b'(id:19) was added to servergroup 'Server Admin'(id:6)", e.message()); + } + + @Test + void keepsTheRestOfALineWithACutOffTimestamp() { + ServerLogEntry e = ServerLogEntry.parse("6-10-01 23:26:51.007742|INFO |VirtualServerBase|1 |listening on 0.0.0.0:9990"); + assertNull(e.timestamp()); + assertEquals(Level.INFO, e.level()); + assertEquals("VirtualServerBase", e.channel()); + assertEquals("listening on 0.0.0.0:9990", e.message()); + } + + @Test + void keepsAnUnreadableLineWhole() { + ServerLogEntry e = ServerLogEntry.parse("2026-10-04 00:23:41.975519|INFO "); + assertNull(e.timestamp()); + assertEquals(Level.INFO, e.level()); + assertEquals("2026-10-04 00:23:41.975519|INFO ", e.message()); + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java index 26a5b52..96d0bdf 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ChatSearch.java @@ -21,8 +21,9 @@ 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. + * Find in a log pane — the chat's selected conversation, or the server log: highlights the + * query's matches and steps through them, newest first. Optionally shows only the + * messages that match. */ final class ChatSearch implements FindBar.Listener { @@ -40,7 +41,7 @@ final class ChatSearch implements FindBar.Listener { private final Host host; private final FindBar bar = new FindBar(this); - private final JToggleButton onlyMatching = bar.addFilterToggle("Show only matching messages"); + private final JToggleButton onlyMatching; private final Highlighter.HighlightPainter matchPainter = new ThemedPainter(false); private final Highlighter.HighlightPainter currentPainter = new ThemedPainter(true); @@ -76,7 +77,12 @@ final class ChatSearch implements FindBar.Listener { }; ChatSearch(Host host) { + this(host, "Show only matching messages"); + } + + ChatSearch(Host host, String filterTooltip) { this.host = host; + onlyMatching = bar.addFilterToggle(filterTooltip); } FindBar bar() { diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java new file mode 100644 index 0000000..593df11 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ListEditorDialog.java @@ -0,0 +1,184 @@ +package com.ts3client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ListSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Window; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * A small modal editor for a list of text-keyed items: Add, Remove, optionally Move up and + * down, and OK/Cancel. Edits a copy and writes it back only on OK. + */ +abstract class ListEditorDialog extends JDialog { + + protected final DefaultListModel model = new DefaultListModel<>(); + protected final JList list = new JList<>(model); + private final String itemPrompt; + private final JPanel south = new JPanel(new BorderLayout(0, UIScale.scale(8))); + private boolean accepted; + + /** + * @param intro text above the list, or {@code null} + * @param itemPrompt what Add and a double-click ask for + * @param movable whether the order matters, offering Move up and down + */ + ListEditorDialog(Window owner, String title, String intro, String itemPrompt, List items, boolean movable) { + super(owner, title, ModalityType.APPLICATION_MODAL); + this.itemPrompt = itemPrompt; + items.forEach(model::addElement); + + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + list.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) selectionChanged(); + }); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && list.getSelectedIndex() >= 0) rename(list.getSelectedIndex()); + } + }); + JScrollPane scroll = new JScrollPane(list); + scroll.setPreferredSize(UIScale.scale(new Dimension(260, 200))); + + JPanel buttons = new JPanel(); + buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); + buttons.setOpaque(false); + addButton(buttons, "Add", this::add); + JButton remove = addButton(buttons, "Remove", this::remove); + JButton up = movable ? addButton(buttons, "Move Up", () -> move(-1)) : null; + JButton down = movable ? addButton(buttons, "Move Down", () -> move(1)) : null; + list.addListSelectionListener(e -> { + int i = list.getSelectedIndex(); + remove.setEnabled(i >= 0); + if (up != null) up.setEnabled(i > 0); + if (down != null) down.setEnabled(i >= 0 && i < model.size() - 1); + }); + remove.setEnabled(false); + if (up != null) up.setEnabled(false); + if (down != null) down.setEnabled(false); + + JPanel center = new JPanel(new BorderLayout(UIScale.scale(8), UIScale.scale(6))); + center.setOpaque(false); + if (intro != null) center.add(ReasonDialog.label(intro), BorderLayout.NORTH); + center.add(scroll, BorderLayout.CENTER); + center.add(buttons, BorderLayout.EAST); + + JButton ok = new JButton("OK"); + ok.addActionListener(e -> { + accepted = true; + dispose(); + }); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(e -> dispose()); + JPanel okCancel = new JPanel(new FlowLayout(FlowLayout.RIGHT, UIScale.scale(6), 0)); + okCancel.setOpaque(false); + okCancel.add(ok); + okCancel.add(cancel); + + south.setOpaque(false); + south.add(okCancel, BorderLayout.SOUTH); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(center, BorderLayout.CENTER); + content.add(south, BorderLayout.SOUTH); + setContentPane(content); + getRootPane().setDefaultButton(ok); + Dialogs.closeOnEscape(this); + } + + /** Controls under the list acting on the selected item, or {@code null}. */ + protected JComponent extraControls() { + return null; + } + + protected void selectionChanged() { + } + + /** The item that {@code text} names, typed into Add, or a rename of {@code old} ({@code null} on Add). */ + protected abstract T item(String text, T old); + + protected abstract String text(T item); + + /** Shows the dialog; on OK copies the edited list into {@code target}. */ + protected boolean showAndApply(List target) { + JComponent extra = extraControls(); + if (extra != null) south.add(extra, BorderLayout.NORTH); + selectionChanged(); + pack(); + setLocationRelativeTo(getOwner()); + setVisible(true); + if (!accepted) return false; + target.clear(); + target.addAll(Collections.list(model.elements())); + return true; + } + + private JButton addButton(JPanel column, String text, Runnable action) { + JButton b = new JButton(text); + b.setAlignmentX(Component.LEFT_ALIGNMENT); + b.setMaximumSize(new Dimension(Integer.MAX_VALUE, b.getPreferredSize().height)); + b.addActionListener(e -> action.run()); + if (column.getComponentCount() > 0) column.add(Box.createVerticalStrut(UIScale.scale(4))); + column.add(b); + return b; + } + + private void add() { + String text = ask(itemPrompt, ""); + if (text == null) return; + model.addElement(item(text, null)); + list.setSelectedIndex(model.size() - 1); + } + + private void rename(int index) { + String text = ask(itemPrompt, text(model.get(index))); + if (text != null) model.set(index, item(text, model.get(index))); + } + + private String ask(String prompt, String initial) { + Object answer = JOptionPane.showInputDialog(this, prompt, getTitle(), JOptionPane.PLAIN_MESSAGE, + null, null, initial); + String text = answer == null ? null : answer.toString().trim(); + return text == null || text.isEmpty() ? null : text; + } + + private void remove() { + int i = list.getSelectedIndex(); + if (i < 0) return; + model.remove(i); + if (!model.isEmpty()) list.setSelectedIndex(Math.min(i, model.size() - 1)); + } + + private void move(int delta) { + int i = list.getSelectedIndex(); + int j = i + delta; + if (i < 0 || j < 0 || j >= model.size()) return; + List items = new ArrayList<>(Collections.list(model.elements())); + Collections.swap(items, i, j); + model.clear(); + items.forEach(model::addElement); + list.setSelectedIndex(j); + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java index 497b21b..7ea3804 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainFrame.java @@ -318,6 +318,16 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { if (selected != null) selected.showComplaints(); } + @Override + public boolean canViewServerLog() { + return selected != null && selected.session().canViewServerLog(); + } + + @Override + public void onShowServerLog() { + if (selected != null) selected.showServerLog(); + } + @Override public boolean canListPrivilegeKeys() { return selected != null && selected.session().canListPrivilegeKeys(); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java b/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java index 53da11f..3d3ae4e 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/MainMenuBar.java @@ -86,6 +86,11 @@ final class MainMenuBar extends JMenuBar { void onShowComplaints(); + /** Whether the current server lets us read its log; asked as the Tools menu opens. */ + boolean canViewServerLog(); + + void onShowServerLog(); + /** Whether the current server lets us list its privilege keys; asked as the Permissions menu opens. */ boolean canListPrivilegeKeys(); @@ -122,6 +127,7 @@ final class MainMenuBar extends JMenuBar { private JMenuItem deleteAvatarItem; private JMenuItem banListItem; private JMenuItem complaintsItem; + private JMenuItem serverLogItem; private JMenuItem privilegeKeysItem; private JMenuItem usePrivilegeKeyItem; @@ -276,6 +282,11 @@ final class MainMenuBar extends JMenuBar { complaintsItem.addActionListener(e -> { if (listener.canViewComplaints()) listener.onShowComplaints(); }); + serverLogItem = new JMenuItem("Server Log", Icons.of("SERVER_LOG")); + serverLogItem.setAccelerator(KeyStroke.getKeyStroke("control shift L")); + serverLogItem.addActionListener(e -> { + if (listener.canViewServerLog()) listener.onShowServerLog(); + }); JMenuItem options = new JMenuItem("Options…", Icons.of("SETTINGS")); options.setAccelerator(KeyStroke.getKeyStroke("alt P")); options.addActionListener(e -> listener.onShowSettings()); @@ -285,6 +296,7 @@ final class MainMenuBar extends JMenuBar { tools.addSeparator(); tools.add(banListItem); tools.add(complaintsItem); + tools.add(serverLogItem); tools.add(adminSeparator); tools.add(options); // Permissions arrive after the connection does, so the item is judged as the menu opens @@ -294,9 +306,11 @@ final class MainMenuBar extends JMenuBar { public void menuSelected(MenuEvent e) { boolean bans = banListItem.isEnabled() && listener.canViewBanList(); boolean complaints = complaintsItem.isEnabled() && listener.canViewComplaints(); + boolean serverLog = serverLogItem.isEnabled() && listener.canViewServerLog(); banListItem.setVisible(bans); complaintsItem.setVisible(complaints); - adminSeparator.setVisible(bans || complaints); + serverLogItem.setVisible(serverLog); + adminSeparator.setVisible(bans || complaints || serverLog); } @Override @@ -338,6 +352,7 @@ final class MainMenuBar extends JMenuBar { deleteAvatarItem.setEnabled(connected); banListItem.setEnabled(connected); complaintsItem.setEnabled(connected); + serverLogItem.setEnabled(connected); privilegeKeysItem.setEnabled(connected); usePrivilegeKeyItem.setEnabled(connected); awayItem.setSelected(away); diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java new file mode 100644 index 0000000..8ba64c2 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogDialog.java @@ -0,0 +1,366 @@ +package com.ts3client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import com.ts3client.config.ServerLogSettings; +import com.ts3client.config.ServerLogSettings.Highlight; +import com.ts3client.config.Settings; +import com.ts3client.net.ServerLogEntry; +import com.ts3client.net.ServerLogEntry.Level; +import com.ts3client.net.ServerLogPage; +import com.ts3client.net.TeamspeakConnection; +import com.ts3client.text.TextQuery; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * The virtual server's log, as the official client's Tools > Server Log window: the newest + * hundred lines, more on Show Older, narrowed down by level and exclude terms and coloured + * by keyword. Find (with "show only matches") stands in for TS3's separate search and + * include-filter fields. + * + *

One per server tab and modeless, like the ban list; the tab closes it when the + * connection goes away. + */ +final class ServerLogDialog extends JDialog { + + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + private static final String TITLE = "Server Log"; + private static final int LEVEL_WIDTH = "Critical".length(); + + private final TeamspeakConnection conn; + private final Settings settings; + private final ServerLogSettings view; + + private final JTextPane log = new JTextPane() { + /** Long lines scroll sideways rather than wrap, keeping the columns lined up. */ + @Override + public boolean getScrollableTracksViewportWidth() { + return getParent() == null || getUI().getPreferredSize(this).width <= getParent().getWidth(); + } + }; + private final DefaultStyledDocument doc = new DefaultStyledDocument(); + private final ChatSearch search = new ChatSearch(new ChatSearch.Host() { + @Override + public JEditorPane selectedLog() { + return log; + } + + @Override + public void showMatching(TextQuery filter) { + onlyMatching = filter; + render(false); + } + }, "Show only matching lines"); + private final Map levelBoxes = new EnumMap<>(Level.class); + private final JComboBox timeZone = new JComboBox<>(new String[]{"UTC time", "Local time"}); + private final JButton olderButton = new JButton("Show Older"); + private final JLabel status = new JLabel(" "); + + /** Everything read so far, oldest first. */ + private final List entries = new ArrayList<>(); + private long olderFrom; + private TextQuery onlyMatching; + private boolean loading; + + ServerLogDialog(Frame owner, TeamspeakConnection conn, Settings settings) { + super(owner, TITLE, false); + this.conn = conn; + this.settings = settings; + this.view = settings.serverLog; + + JPanel center = new JPanel(new BorderLayout()); + center.setOpaque(false); + center.add(buildLog(), BorderLayout.CENTER); + center.add(search.bar(), BorderLayout.SOUTH); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(buildToolbar(), BorderLayout.NORTH); + content.add(center, BorderLayout.CENTER); + content.add(buildBottom(), BorderLayout.SOUTH); + setContentPane(content); + bindKeys(); + + serverNameChanged(); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setPreferredSize(UIScale.scale(new Dimension(900, 520))); + pack(); + setLocationRelativeTo(owner); + search.open(); + reload(); + } + + // ---- construction ---- + + private JPanel buildToolbar() { + JPanel bar = new JPanel(); + bar.setLayout(new BoxLayout(bar, BoxLayout.X_AXIS)); + bar.setOpaque(false); + String[] labels = {"Critical", "Errors", "Warnings", "Info"}; + int[] mnemonics = {KeyEvent.VK_C, KeyEvent.VK_E, KeyEvent.VK_W, KeyEvent.VK_I}; + for (int i = 0; i < ServerLogSettings.SHOWN_LEVELS.size(); i++) { + Level level = ServerLogSettings.SHOWN_LEVELS.get(i); + JCheckBox box = new JCheckBox(labels[i], view.levels.contains(level)); + box.setMnemonic(mnemonics[i]); + box.setOpaque(false); + box.addActionListener(e -> { + if (box.isSelected()) view.levels.add(level); + else view.levels.remove(level); + settingsChanged(); + }); + levelBoxes.put(level, box); + bar.add(box); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + } + bar.add(Box.createHorizontalStrut(UIScale.scale(12))); + + JButton highlighting = new JButton("Highlighting…"); + highlighting.setMnemonic(KeyEvent.VK_H); + highlighting.addActionListener(e -> { + if (ServerLogHighlightDialog.edit(this, view.highlights)) settingsChanged(); + }); + JButton exclude = new JButton("Exclude Filter…"); + exclude.setMnemonic(KeyEvent.VK_X); + exclude.addActionListener(e -> { + if (ServerLogExcludeDialog.edit(this, view.excludes)) settingsChanged(); + }); + bar.add(highlighting); + bar.add(Box.createHorizontalStrut(UIScale.scale(6))); + bar.add(exclude); + bar.add(Box.createHorizontalGlue()); + + timeZone.setSelectedIndex(view.localTime ? 1 : 0); + timeZone.setMaximumSize(timeZone.getPreferredSize()); + timeZone.addActionListener(e -> { + view.localTime = timeZone.getSelectedIndex() == 1; + settingsChanged(); + }); + bar.add(timeZone); + return bar; + } + + private JScrollPane buildLog() { + log.setEditable(false); + log.setDocument(doc); + log.setFont(new Font(Font.MONOSPACED, Font.PLAIN, UIScale.scale(12))); + log.setBackground(Theme.chatBg()); + log.setForeground(Theme.chatText()); + log.setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); + JScrollPane scroll = new JScrollPane(log); + scroll.getViewport().setBackground(Theme.chatBg()); + return scroll; + } + + private JPanel buildBottom() { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setMnemonic(KeyEvent.VK_R); + reload.setToolTipText("Reload the newest lines
(F5)"); + reload.addActionListener(e -> reload()); + olderButton.setMnemonic(KeyEvent.VK_O); + olderButton.setEnabled(false); + olderButton.addActionListener(e -> loadOlder()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + JPanel left = new JPanel(); + left.setLayout(new BoxLayout(left, BoxLayout.X_AXIS)); + left.setOpaque(false); + left.add(reload); + left.add(Box.createHorizontalStrut(UIScale.scale(6))); + left.add(olderButton); + + JPanel row = new JPanel(new BorderLayout()); + row.setOpaque(false); + row.add(left, BorderLayout.WEST); + row.add(close, BorderLayout.EAST); + + JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); + bottom.setOpaque(false); + bottom.add(status, BorderLayout.NORTH); + bottom.add(row, BorderLayout.SOUTH); + status.setForeground(Theme.chatEvent()); + return bottom; + } + + private void bindKeys() { + bind(KeyStroke.getKeyStroke("F5"), this::reload); + bind(KeyStroke.getKeyStroke("control W"), this::dispose); + bind(KeyStroke.getKeyStroke("control F"), search::open); + Dialogs.closeOnEscape(this); + } + + private void bind(KeyStroke key, Runnable action) { + String name = "ts3-serverlog-" + key; + getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, name); + getRootPane().getActionMap().put(name, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + // ---- data ---- + + void serverNameChanged() { + String name = conn.getModel().getServerName(); + setTitle(name == null || name.isBlank() ? TITLE : TITLE + " - " + name); + } + + void connectionLost() { + dispose(); + } + + private void reload() { + request(0); + } + + private void loadOlder() { + if (olderFrom > 0) request(olderFrom); + } + + /** Reads the newest page ({@code from} 0, replacing what is shown) or the one ending at {@code from}. */ + private void request(long from) { + if (loading) return; + loading = true; + olderButton.setEnabled(false); + status.setForeground(Theme.chatEvent()); + status.setText("Loading…"); + conn.requestServerLog(from, (page, error) -> SwingUtilities.invokeLater(() -> { + loading = false; + if (!isDisplayable()) return; + if (error != null) { + failed(error); + olderButton.setEnabled(olderFrom > 0); + return; + } + received(page, from > 0); + })); + } + + private void received(ServerLogPage page, boolean older) { + if (!older) entries.clear(); + entries.addAll(0, page.entries()); + olderFrom = page.olderFrom(); + olderButton.setEnabled(page.hasOlder()); + render(!older); + if (older) log.setCaretPosition(0); + } + + private void failed(String error) { + status.setForeground(Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); + status.setText(error.toLowerCase(Locale.ROOT).contains("insufficient") + ? "Insufficient permissions to view Server Log" + : "Error requesting server log: " + error); + } + + private void settingsChanged() { + settings.save(); + render(false); + } + + // ---- rendering ---- + + /** Lays the log out again; {@code toEnd} scrolls to the newest line, otherwise the view stays put. */ + private void render(boolean toEnd) { + int channelWidth = 0; + for (ServerLogEntry e : entries) channelWidth = Math.max(channelWidth, e.channel().length()); + + int scrollY = log.getVisibleRect().y; + int shown = 0; + try { + doc.remove(0, doc.getLength()); + for (ServerLogEntry e : entries) { + String line = format(e, channelWidth); + if (!view.shows(e.level(), line)) continue; + if (onlyMatching != null && !onlyMatching.matches(line)) continue; + doc.insertString(doc.getLength(), line + "\n", style(view.highlightFor(line))); + shown++; + } + } catch (BadLocationException ignored) { + // appending at the end never fails + } + + status.setForeground(Theme.chatEvent()); + if (entries.isEmpty()) status.setText("No log entries available"); + else if (shown == entries.size()) status.setText(lines(shown)); + else status.setText(shown + " of " + lines(entries.size())); + + if (toEnd) { + log.setCaretPosition(doc.getLength()); + } else { + SwingUtilities.invokeLater(() -> log.scrollRectToVisible( + new Rectangle(0, scrollY, 1, log.getVisibleRect().height))); + } + } + + private static String lines(int n) { + return n == 1 ? "1 line" : n + " lines"; + } + + private String format(ServerLogEntry e, int channelWidth) { + String time = ""; + if (e.timestamp() != null) { + LocalDateTime t = view.localTime + ? e.timestamp().atOffset(ZoneOffset.UTC).atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime() + : e.timestamp(); + time = TIME.format(t); + } + return pad(time, 19) + " " + pad(e.channel(), channelWidth) + " " + + pad(levelName(e.level()), LEVEL_WIDTH) + " " + e.message(); + } + + private static String levelName(Level level) { + String name = level.name(); + return name.charAt(0) + name.substring(1).toLowerCase(Locale.ROOT); + } + + private static String pad(String s, int width) { + return s.length() >= width ? s : s + " ".repeat(width - s.length()); + } + + private static SimpleAttributeSet style(Highlight h) { + SimpleAttributeSet a = new SimpleAttributeSet(); + if (h == null) return a; + if (h.foreground() != null) StyleConstants.setForeground(a, new Color(h.foreground())); + if (h.background() != null) StyleConstants.setBackground(a, new Color(h.background())); + return a; + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java new file mode 100644 index 0000000..0341be1 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogExcludeDialog.java @@ -0,0 +1,27 @@ +package com.ts3client.ui; + +import java.awt.Window; +import java.util.List; + +/** The Server Log's exclude filter: terms whose lines are left out. */ +final class ServerLogExcludeDialog extends ListEditorDialog { + + private ServerLogExcludeDialog(Window owner, List terms) { + super(owner, "Exclude Filter", "Exclude lines containing:", "Term:", terms, false); + } + + /** @return whether the terms were changed */ + static boolean edit(Window owner, List terms) { + return new ServerLogExcludeDialog(owner, terms).showAndApply(terms); + } + + @Override + protected String item(String text, String old) { + return text; + } + + @Override + protected String text(String item) { + return item; + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java new file mode 100644 index 0000000..6cca868 --- /dev/null +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerLogHighlightDialog.java @@ -0,0 +1,145 @@ +package com.ts3client.ui; + +import com.formdev.flatlaf.util.UIScale; +import com.ts3client.config.ServerLogSettings.Highlight; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Window; +import java.util.List; +import java.util.function.Function; + +/** The Server Log's highlighting: keywords and the colours their lines are drawn in, first match first. */ +final class ServerLogHighlightDialog extends ListEditorDialog { + + private JButton foreground; + private JButton background; + private JButton clearForeground; + private JButton clearBackground; + + private ServerLogHighlightDialog(Window owner, List highlights) { + super(owner, "Highlighting", null, "Keyword:", highlights, true); + list.setCellRenderer(new DefaultListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList l, Object value, int index, + boolean selected, boolean focused) { + Highlight h = (Highlight) value; + super.getListCellRendererComponent(l, h.keyword(), index, selected, focused); + if (!selected) { + if (h.foreground() != null) setForeground(new Color(h.foreground())); + if (h.background() != null) setBackground(new Color(h.background())); + } + return this; + } + }); + } + + /** @return whether the highlights were changed */ + static boolean edit(Window owner, List highlights) { + return new ServerLogHighlightDialog(owner, highlights).showAndApply(highlights); + } + + @Override + protected Highlight item(String text, Highlight old) { + return old == null ? new Highlight(text, null, null) : new Highlight(text, old.foreground(), old.background()); + } + + @Override + protected String text(Highlight item) { + return item.keyword(); + } + + @Override + protected JComponent extraControls() { + foreground = new JButton("Text Color…"); + foreground.addActionListener(e -> choose("Text Color", Highlight::foreground, true)); + clearForeground = new JButton("None"); + clearForeground.addActionListener(e -> update(null, true)); + background = new JButton("Background…"); + background.addActionListener(e -> choose("Background", Highlight::background, false)); + clearBackground = new JButton("None"); + clearBackground.addActionListener(e -> update(null, false)); + + JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(4), 0)); + row.setOpaque(false); + row.add(foreground); + row.add(clearForeground); + row.add(new JLabel(" ")); + row.add(background); + row.add(clearBackground); + return row; + } + + @Override + protected void selectionChanged() { + Highlight h = list.getSelectedValue(); + foreground.setEnabled(h != null); + background.setEnabled(h != null); + clearForeground.setEnabled(h != null && h.foreground() != null); + clearBackground.setEnabled(h != null && h.background() != null); + foreground.setIcon(new Swatch(h == null ? null : h.foreground())); + background.setIcon(new Swatch(h == null ? null : h.background())); + } + + private void choose(String title, Function current, boolean isForeground) { + Highlight h = list.getSelectedValue(); + if (h == null) return; + Integer rgb = current.apply(h); + Color chosen = JColorChooser.showDialog(this, title, rgb == null ? Theme.chatText() : new Color(rgb)); + if (chosen != null) update(chosen.getRGB() & 0xFFFFFF, isForeground); + } + + private void update(Integer rgb, boolean isForeground) { + int i = list.getSelectedIndex(); + if (i < 0) return; + Highlight h = model.get(i); + model.set(i, isForeground ? new Highlight(h.keyword(), rgb, h.background()) + : new Highlight(h.keyword(), h.foreground(), rgb)); + selectionChanged(); + } + + /** A colour sample; struck through when there is none. */ + private record Swatch(Integer rgb) implements Icon { + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + Graphics2D g2 = (Graphics2D) g.create(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + int w = getIconWidth() - 1; + int h = getIconHeight() - 1; + if (rgb != null) { + g2.setColor(new Color(rgb)); + g2.fillRect(x, y, w, h); + } + g2.setColor(Theme.border()); + g2.drawRect(x, y, w, h); + if (rgb == null) { + g2.setStroke(new BasicStroke(UIScale.scale(1f))); + g2.drawLine(x, y + h, x + w, y); + } + g2.dispose(); + } + + @Override + public int getIconWidth() { + return UIScale.scale(14); + } + + @Override + public int getIconHeight() { + return UIScale.scale(14); + } + } +} diff --git a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java index 21dbdf9..a80214f 100644 --- a/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/com/ts3client/ui/ServerTab.java @@ -56,6 +56,7 @@ final class ServerTab { private BanListDialog banList; private PrivilegeKeysDialog privilegeKeys; private ComplaintsDialog complaints; + private ServerLogDialog serverLog; ServerTab(MainFrame host, Settings settings, IdentityStore identities, AudioBackend audio, SoundNotifier sounds, ContactStore contacts, PictureDownloads pictures) { @@ -201,6 +202,16 @@ final class ServerTab { complaints.toFront(); } + /** Opens the server's log, or brings the already open window forward. */ + void showServerLog() { + if (!session.isConnected()) return; + if (serverLog == null || !serverLog.isDisplayable()) { + serverLog = new ServerLogDialog(host, conn, settings); + } + serverLog.setVisible(true); + serverLog.toFront(); + } + /** Asks for a privilege key and redeems it on this server. */ void usePrivilegeKey() { if (!session.isConnected()) return; @@ -224,7 +235,7 @@ final class ServerTab { privilegeKeys.toFront(); } - /** The server's name changed or the connection went; the ban list, complaints and privilege keys windows follow. */ + /** The server's name changed or the connection went; the server admin windows follow. */ void serverWindowsChanged(boolean connected) { if (banList != null) { if (connected) banList.serverNameChanged(); @@ -234,6 +245,10 @@ final class ServerTab { if (connected) complaints.serverNameChanged(); else complaints.connectionLost(); } + if (serverLog != null) { + if (connected) serverLog.serverNameChanged(); + else serverLog.connectionLost(); + } if (privilegeKeys != null) { if (connected) privilegeKeys.serverNameChanged(); else privilegeKeys.connectionLost();