diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index ca7acca..55701cc 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -17,8 +17,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo | 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | done (`959f7ed`): the helpers are public with non-blocking methods, reached through `ServerSession`/`TeamspeakConnection` getters; 30 forwarders gone, and what they added (stop-at-first-refusal loops, log lines, description refresh, own avatar flag) moved into the helpers. Swing dialogs still take the whole connection for the model and our ids (item 5) | | 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | done (`9107bdd`): `OwnClient` owns the devices and our flags, and publishes them; `Recording` the recorder. `ServerSession` no longer keeps its own copy of the flags, and they are cleared when a connect starts rather than once it is done | | 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | done (`de42429`): `connection()` is gone; frontends reach the model, our ids, devices and the helpers through `ServerSession`. New helpers took the remaining actions off the connection: `ClientAdmin` (move, kick, ban, groups, talk power, poke, details), `ChannelFiles`, `ClientContacts`; `ChannelAdmin` also joins, moves and subscribes. Dialogs take the session, or only the helper they use | -| 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (uncommitted): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray | -| 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding | open | +| 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (`f7cf040`): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray | +| 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding || done (uncommitted): the five extend `ServerListDialog`, which lays out the toolbar, list, status line and Reload/Close, follows the server's name, binds F5/Ctrl+W/Escape, guards loading, reloads after a change and reports its failure; `ServerTab` keeps them in one map. All five now take F5, show load failures in red, and keep the status line's height; the ban list's own placeholder field is FlatLaf's. The table models stay per dialog: their rows and columns share nothing | | 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | open | | 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | open | | 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | open | diff --git a/ts3-client/README.md b/ts3-client/README.md index 1a9a600..d04109f 100644 --- a/ts3-client/README.md +++ b/ts3-client/README.md @@ -312,6 +312,7 @@ swing/ eu.lixko.ts3j.client ├── ConnectDialog connect form ├── BookmarksDialog manage saved servers ├── IdentitiesDialog manage identities (new/import/export/improve) + ├── ServerListDialog shared frame of a server's list windows (bans, complaints, privilege keys, offline messages, server log) ├── IdentityChooser identity drop-down shared by connect/bookmark forms ├── LevelMeter dBFS meter with threshold marker ├── IconTheme active icon pack: rasterising (JSVG) and caching diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java index adb8e25..7c735e4 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java @@ -1,6 +1,5 @@ package eu.lixko.ts3j.client.ui; -import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; import eu.lixko.ts3j.client.config.BanReasonPresets; import eu.lixko.ts3j.client.config.Settings; @@ -9,23 +8,18 @@ import eu.lixko.ts3j.client.session.ServerSession; import eu.lixko.ts3j.client.net.ban.BanEntry; import eu.lixko.ts3j.client.net.ban.BanRule; -import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; +import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; @@ -36,27 +30,16 @@ import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; -import java.awt.Font; import java.awt.Frame; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** @@ -64,12 +47,8 @@ import java.util.stream.Collectors; * Remove and Edit above a searchable table, Reload and the own-ban filters below it. * Which columns show is chosen from the header's context menu and remembered. * - *

One per server tab and modeless, so it can stay open while the server is used; - * the tab closes it when the connection goes away. */ -final class BanListDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); +final class BanListDialog extends ServerListDialog { /** The table's columns, in the official order; the split-out target columns start hidden. */ private enum Column { @@ -96,7 +75,6 @@ final class BanListDialog extends JDialog { } private final Frame owner; - private final ServerSession session; private final Settings settings; private final BanReasonPresets presets; @@ -110,35 +88,21 @@ final class BanListDialog extends JDialog { private final JButton addButton = new JButton("Add", Icons.of("ADD")); private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); private final JButton editButton = new JButton("Edit", Icons.of("EDIT")); - private final SearchField searchField = new SearchField(); + private final JTextField searchField = new JTextField(20); private final JCheckBox onlyOwn = new JCheckBox("Show only own bans"); private final JCheckBox highlightOwn = new JCheckBox("Highlight own bans"); - private final JLabel status = new JLabel(" "); - - private boolean loading; BanListDialog(Frame owner, ServerSession session, Settings settings, BanReasonPresets presets) { - super(owner, "Ban List", false); + super(owner, session, "Ban List"); this.owner = owner; - this.session = session; this.settings = settings; this.presets = presets; - 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(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); + buildOptions(); bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(920, 460))); - pack(); - setLocationRelativeTo(owner); - reload(); + layOut(buildToolbar(), buildTable(), new Dimension(920, 460), + Box.createHorizontalStrut(UIScale.scale(6)), onlyOwn, + Box.createHorizontalStrut(UIScale.scale(6)), highlightOwn); } // ---- construction ---- @@ -152,6 +116,7 @@ final class BanListDialog extends JDialog { removeButton.setToolTipText("Remove selected bans
(Delete)"); editButton.setToolTipText("Edit selected ban
(Return)"); searchField.setToolTipText("Search bans by text
(Ctrl+F)"); + searchField.putClientProperty("JTextField.placeholderText", "Search"); addButton.addActionListener(e -> addBan()); removeButton.addActionListener(e -> removeBans()); editButton.addActionListener(e -> editBan()); @@ -184,10 +149,6 @@ final class BanListDialog extends JDialog { } private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); table.setAutoCreateColumnsFromModel(false); table.setRowSorter(sorter); table.getSelectionModel().addListSelectionListener(e -> updateButtons()); @@ -225,15 +186,10 @@ final class BanListDialog extends JDialog { if (e.isPopupTrigger()) headerPopup().show(header, e.getX(), e.getY()); } }); - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; + return scroll(table); } - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.addActionListener(e -> reload()); + private void buildOptions() { onlyOwn.setToolTipText("Show only bans created by you"); onlyOwn.setOpaque(false); onlyOwn.addActionListener(e -> applyFilter()); @@ -245,30 +201,6 @@ final class BanListDialog extends JDialog { settings.save(); table.repaint(); }); - - JPanel options = new JPanel(); - options.setLayout(new BoxLayout(options, BoxLayout.X_AXIS)); - options.setOpaque(false); - options.add(reload); - options.add(Box.createHorizontalStrut(UIScale.scale(12))); - options.add(onlyOwn); - options.add(Box.createHorizontalStrut(UIScale.scale(12))); - options.add(highlightOwn); - options.add(Box.createHorizontalGlue()); - - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - JPanel closeRow = new JPanel(new BorderLayout()); - closeRow.setOpaque(false); - closeRow.add(close, BorderLayout.EAST); - - JPanel bottom = new JPanel(new BorderLayout(0, UIScale.scale(8))); - bottom.setOpaque(false); - bottom.add(status, BorderLayout.NORTH); - bottom.add(options, BorderLayout.CENTER); - bottom.add(closeRow, BorderLayout.SOUTH); - status.setForeground(Theme.chatEvent()); - return bottom; } private JPopupMenu tablePopup() { @@ -281,12 +213,6 @@ final class BanListDialog extends JDialog { return menu; } - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - private JPopupMenu headerPopup() { JPopupMenu menu = new JPopupMenu(); for (Column c : Column.values()) { @@ -305,26 +231,10 @@ final class BanListDialog extends JDialog { } private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::addBan); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control F"), - searchField::requestFocusInWindow); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeBans); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), - this::editBan); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-banlist-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); + bind("control N", this::addBan); + bind("control F", searchField::requestFocusInWindow); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "DELETE", this::removeBans); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "ENTER", this::editBan); } // ---- columns ---- @@ -360,32 +270,15 @@ final class BanListDialog extends JDialog { // ---- data ---- - /** Follows the server's name, as the official window's "Ban List - " title does. */ - void serverNameChanged() { - String name = session.model().getServerName(); - setTitle(name == null || name.isBlank() ? "Ban List" : "Ban List - " + name); - } - - /** The connection is gone; a ban list without a server is meaningless. */ - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - Edt.handle(session.bans().list(), bans -> { - loading = false; - if (!isDisplayable()) return; + @Override + void reload() { + load(session.bans()::list, bans -> { tableModel.setBans(bans); - status.setText(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); + showStatus(bans.size() == 1 ? "1 ban" : bans.size() + " bans"); updateButtons(); }, failure -> { - loading = false; - if (!isDisplayable()) return; tableModel.setBans(List.of()); - status.setText(failure.permissionDenied() + showError(failure.permissionDenied() ? "You have insufficient permissions to view the ban list." : "Failed to request ban list: " + failure.getMessage()); updateButtons(); @@ -438,7 +331,7 @@ final class BanListDialog extends JDialog { dialog.setVisible(true); BanRule rule = dialog.getRule(); if (rule == null) return; - afterChange(session.bans().add(rule), "Error adding ban: ", + change(session.bans().add(rule), "Error adding ban: ", () -> JOptionPane.showMessageDialog(this, "Your ban was successfully added.", "Ban List", JOptionPane.INFORMATION_MESSAGE)); } @@ -450,7 +343,7 @@ final class BanListDialog extends JDialog { dialog.setVisible(true); BanRule rule = dialog.getRule(); if (rule == null) return; - afterChange(session.bans().replace(ban.id, rule), "Error editing ban: "); + change(session.bans().replace(ban.id, rule), "Error editing ban: "); } private void removeBans() { @@ -460,25 +353,7 @@ final class BanListDialog extends JDialog { "Delete bans", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List ids = bans.stream().map(b -> b.id).collect(Collectors.toList()); - afterChange(session.bans().delete(ids), "Error deleting ban: "); - } - - /** Reports a failed change, or re-reads the list so the table shows what the server now holds. */ - private void afterChange(CompletableFuture change, String errorPrefix) { - afterChange(change, errorPrefix, () -> { - }); - } - - private void afterChange(CompletableFuture change, String errorPrefix, Runnable onSuccess) { - Edt.handle(change, () -> { - if (!isDisplayable()) return; - onSuccess.run(); - reload(); - }, failure -> { - if (!isDisplayable()) return; - JOptionPane.showMessageDialog(this, errorPrefix + failure.getMessage(), "Ban List", JOptionPane.ERROR_MESSAGE); - reload(); - }); + change(session.bans().delete(ids), "Error deleting ban: "); } // ---- table ---- @@ -569,11 +444,6 @@ final class BanListDialog extends JDialog { } } - private static String date(long epochSeconds) { - if (epochSeconds <= 0) return ""; - return DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())); - } - /** Shows the displayed text for every column and bolds our own bans when asked to. */ private final class BanCellRenderer extends DefaultTableCellRenderer { @Override @@ -618,24 +488,4 @@ final class BanListDialog extends JDialog { private static String escape(String s) { return s.replace("&", "&").replace("<", "<").replace(">", ">"); } - - /** A text field that shows "Search" while it is empty. */ - private static final class SearchField extends javax.swing.JTextField { - SearchField() { - super(20); - } - - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - if (!getText().isEmpty()) return; - Graphics2D g2 = (Graphics2D) g.create(); - g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - g2.setColor(Theme.chatEvent()); - g2.setFont(getFont().deriveFont(Font.ITALIC)); - int y = (getHeight() + g2.getFontMetrics().getAscent() - g2.getFontMetrics().getDescent()) / 2; - g2.drawString("Search", getInsets().left + UIScale.scale(2), y); - g2.dispose(); - } - } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java index 5c57ab4..a6a8f4a 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ComplaintsDialog.java @@ -7,40 +7,29 @@ import eu.lixko.ts3j.client.net.Complaint; import eu.lixko.ts3j.client.net.ServerModel; import eu.lixko.ts3j.client.session.ServerSession; -import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; -import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; @@ -55,13 +44,8 @@ import java.util.function.Consumer; * The server's complaints, as the official client's Tools > Complaints List window: one * collapsible row per client complained about, with each complaint's date, author and * reason beneath it. - * - *

One per server tab and modeless, like the ban list; the tab closes it when the - * connection goes away. */ -final class ComplaintsDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); +final class ComplaintsDialog extends ServerListDialog { private enum Column { TARGET("Target Nickname", 200), @@ -88,7 +72,6 @@ final class ComplaintsDialog extends JDialog { } } - private final ServerSession session; private final Consumer banClient; private final ComplaintTableModel tableModel = new ComplaintTableModel(); @@ -102,36 +85,19 @@ final class ComplaintsDialog extends JDialog { } }; private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); - private final JLabel status = new JLabel(" "); private final JMenuItem removeItem = item("Remove", "DELETE", this::removeSelected); private final JMenuItem banItem = item("Ban Client", "BAN_CLIENT", this::banSelected); private List targets = List.of(); /** Targets shown expanded, by database id; kept across reloads. */ private final Set expanded = new HashSet<>(); - private boolean loading; /** @param banClient opens the ban dialog for an online client */ ComplaintsDialog(Frame owner, ServerSession session, Consumer banClient) { - super(owner, "Complaints List", false); - this.session = session; + super(owner, session, "Complaints List"); this.banClient = banClient; - - 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(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(680, 420))); - pack(); - setLocationRelativeTo(owner); - reload(); + layOut(buildToolbar(), buildTable(), new Dimension(680, 420)); } // ---- construction ---- @@ -149,10 +115,6 @@ final class ComplaintsDialog extends JDialog { } private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); table.setShowGrid(false); table.getTableHeader().setReorderingAllowed(false); table.getSelectionModel().addListSelectionListener(e -> updateButtons()); @@ -163,30 +125,7 @@ final class ComplaintsDialog extends JDialog { table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); } - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload complaints
(F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, 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; + return scroll(table); } private JPopupMenu tablePopup() { @@ -213,59 +152,22 @@ final class ComplaintsDialog extends JDialog { return menu; } - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeSelected); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), () -> setLeadExpanded(true)); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), () -> setLeadExpanded(false)); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-complaints-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "DELETE", this::removeSelected); + bind(table, JComponent.WHEN_FOCUSED, "RIGHT", () -> setLeadExpanded(true)); + bind(table, JComponent.WHEN_FOCUSED, "LEFT", () -> setLeadExpanded(false)); } // ---- data ---- - /** Follows the server's name, as the ban list's title does. */ - void serverNameChanged() { - String name = session.model().getServerName(); - setTitle(name == null || name.isBlank() ? "Complaints List" : "Complaints List - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - Edt.handle(session.complaints().list(), complaints -> { - loading = false; - if (!isDisplayable()) return; + @Override + void reload() { + load(session.complaints()::list, complaints -> { setTargets(groupByTarget(complaints)); - status.setText(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); + showStatus(complaints.size() == 1 ? "1 complaint" : complaints.size() + " complaints"); }, failure -> { - loading = false; - if (!isDisplayable()) return; setTargets(List.of()); - status.setText("Failed to request complaint list: " + failure.getMessage()); + showError("Failed to request complaint list: " + failure.getMessage()); }); } @@ -384,14 +286,7 @@ final class ComplaintsDialog extends JDialog { JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List whole = sel.whole().stream().map(Target::dbId).toList(); - Edt.handle(session.complaints().delete(whole, sel.single()), () -> { - if (isDisplayable()) reload(); - }, failure -> { - if (!isDisplayable()) return; - JOptionPane.showMessageDialog(this, "Failed to delete complaints: " + failure.getMessage(), getTitle(), - JOptionPane.ERROR_MESSAGE); - reload(); - }); + change(session.complaints().delete(whole, sel.single()), "Failed to delete complaints: "); } private void banSelected() { @@ -473,8 +368,7 @@ final class ComplaintsDialog extends JDialog { } Complaint c = row.complaint(); return switch (column) { - case TARGET -> c.timestampEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(c.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); + case TARGET -> date(c.timestampEpochSeconds()); case FROM -> c.fromName(); case REASON -> c.message(); }; diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java index 6907854..e8ddf21 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/OfflineMessagesDialog.java @@ -6,13 +6,11 @@ import eu.lixko.ts3j.client.net.OfflineMessage; import eu.lixko.ts3j.client.session.ServerSession; import eu.lixko.ts3j.client.text.BBCode; -import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; -import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JMenuItem; @@ -23,8 +21,6 @@ import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; import javax.swing.RowSorter; import javax.swing.SortOrder; import javax.swing.UIManager; @@ -40,12 +36,8 @@ import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.Point; -import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -57,12 +49,8 @@ import java.util.Set; * Our offline message inbox on one server, as the official client's Tools > Offline Messages * window: the messages above, the selected one's subject and text below. Viewing a message * marks it read. - * - *

One per server tab and modeless; the tab closes it when the connection goes away. */ -final class OfflineMessagesDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); +final class OfflineMessagesDialog extends ServerListDialog { /** Where Compose and Reply lead: the tab opens the compose window. */ interface Composer { @@ -86,7 +74,6 @@ final class OfflineMessagesDialog extends JDialog { } } - private final ServerSession session; private final Composer composer; private final MessageTableModel tableModel = new MessageTableModel(); @@ -114,7 +101,6 @@ final class OfflineMessagesDialog extends JDialog { private final JButton deleteButton = new JButton("Delete"); private final JTextField subjectField = new JTextField(); private final JEditorPane bodyPane = HtmlStyles.pane("font-family:sans-serif; font-size:11px;"); - private final JLabel status = new JLabel(" "); /** Bodies already read, by message id; each costs a {@code messageget}. */ private final Map bodies = new HashMap<>(); @@ -122,11 +108,9 @@ final class OfflineMessagesDialog extends JDialog { private int shownId = -1; /** Set while a right-click selects its row, which leaves the reader alone. */ private boolean selectingForPopup; - private boolean loading; OfflineMessagesDialog(Frame owner, ServerSession session, Composer composer) { - super(owner, "Offline Messages", false); - this.session = session; + super(owner, session, "Offline Messages"); this.composer = composer; JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buildTable(), buildReader()); @@ -134,22 +118,9 @@ final class OfflineMessagesDialog extends JDialog { split.setBorder(null); split.setOpaque(false); - 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(split, BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(600, 560))); - pack(); - setLocationRelativeTo(owner); updateButtons(); - reload(); + layOut(buildToolbar(), split, new Dimension(600, 560)); } // ---- construction ---- @@ -177,10 +148,6 @@ final class OfflineMessagesDialog extends JDialog { } private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); table.setShowGrid(false); table.getTableHeader().setReorderingAllowed(false); table.setComponentPopupMenu(tablePopup()); @@ -202,8 +169,7 @@ final class OfflineMessagesDialog extends JDialog { sorter.setSortKeys(List.of(new RowSorter.SortKey(Column.DATE.ordinal(), SortOrder.ASCENDING))); table.setRowSorter(sorter); - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); + JScrollPane scroll = scroll(table); scroll.setMinimumSize(UIScale.scale(new Dimension(0, 80))); return scroll; } @@ -231,36 +197,16 @@ final class OfflineMessagesDialog extends JDialog { return reader; } - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload messages
(F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, 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 JPopupMenu tablePopup() { - JMenuItem reply = item("Reply to message", this::replySelected); - JMenuItem delete = item("Delete message", this::deleteSelected); - JMenuItem markRead = item("Mark as Read", () -> markSelected(true)); - JMenuItem markUnread = item("Mark as Unread", () -> markSelected(false)); + JMenuItem reply = item("Reply to message", null, this::replySelected); + JMenuItem delete = item("Delete message", null, this::deleteSelected); + JMenuItem markRead = item("Mark as Read", null, () -> markSelected(true)); + JMenuItem markUnread = item("Mark as Unread", null, () -> markSelected(false)); JPopupMenu menu = new JPopupMenu(); menu.add(reply); menu.add(delete); menu.addSeparator(); - menu.add(item("Reload messages", this::reload)); + menu.add(item("Reload messages", null, this::reload)); menu.addSeparator(); menu.add(markRead); menu.add(markUnread); @@ -285,57 +231,25 @@ final class OfflineMessagesDialog extends JDialog { return menu; } - private static JMenuItem item(String text, Runnable action) { - JMenuItem item = new JMenuItem(text); - item.addActionListener(e -> action.run()); - return item; - } - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::compose); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::deleteSelected); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-offline-messages-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); + bind("control N", this::compose); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "DELETE", this::deleteSelected); } // ---- data ---- - void serverNameChanged() { - String name = session.model().getServerName(); - setTitle(name == null || name.isBlank() ? "Offline Messages" : "Offline Messages on " + name); - } - - void connectionLost() { - dispose(); + @Override + String title(String serverName) { + return "Offline Messages on " + serverName; } /** Reads the inbox again, keeping the selection where the messages are still there. */ + @Override void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - Edt.handle(session.offlineMessages().list(), messages -> { - loading = false; - if (!isDisplayable()) return; + load(session.offlineMessages()::list, messages -> { setMessages(messages); - status.setText(messages.isEmpty() ? "No messages" : " "); - }, failure -> { - loading = false; - if (isDisplayable()) status.setText("Failed to list offline messages: " + failure.getMessage()); - }); + showStatus(messages.isEmpty() ? "No messages" : null); + }, failure -> showError("Failed to list offline messages: " + failure.getMessage())); } private void setMessages(List messages) { @@ -394,7 +308,7 @@ final class OfflineMessagesDialog extends JDialog { if (shownId == message.id()) showBody(message, text); }, failure -> { if (isDisplayable() && shownId == message.id()) { - status.setText("Failed to get offline message: " + failure.getMessage()); + showError("Failed to get offline message: " + failure.getMessage()); } }); } @@ -424,7 +338,7 @@ final class OfflineMessagesDialog extends JDialog { bodies.put(message.id(), text); composer.reply(message, text); }, failure -> { - if (isDisplayable()) status.setText("Failed to get offline message: " + failure.getMessage()); + if (isDisplayable()) showError("Failed to get offline message: " + failure.getMessage()); }); } @@ -438,7 +352,7 @@ final class OfflineMessagesDialog extends JDialog { for (OfflineMessage m : messages) tableModel.replace(m.withRead(read)); Edt.onFailure(session.offlineMessages().markRead(messages.stream().map(OfflineMessage::id).toList(), read), failure -> { if (!isDisplayable()) return; - status.setText("Failed to update offline message: " + failure.getMessage()); + showError("Failed to update offline message: " + failure.getMessage()); reload(); }); } @@ -456,18 +370,9 @@ final class OfflineMessagesDialog extends JDialog { JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; } - Runnable deleted = () -> { - for (OfflineMessage m : selected) bodies.remove(m.id()); - reload(); - }; - Edt.handle(session.offlineMessages().delete(selected.stream().map(OfflineMessage::id).toList()), () -> { - if (isDisplayable()) deleted.run(); - }, failure -> { - if (!isDisplayable()) return; - JOptionPane.showMessageDialog(this, "Failed to delete offline message: " + failure.getMessage(), - getTitle(), JOptionPane.ERROR_MESSAGE); - deleted.run(); - }); + for (OfflineMessage m : selected) bodies.remove(m.id()); + change(session.offlineMessages().delete(selected.stream().map(OfflineMessage::id).toList()), + "Failed to delete offline message: "); } private static String subjectOrPlaceholder(OfflineMessage m) { @@ -547,8 +452,7 @@ final class OfflineMessagesDialog extends JDialog { Object shown = switch (c) { case STATE -> ""; case SUBJECT -> subjectOrPlaceholder(m); - case DATE -> m.timestampEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(m.timestampEpochSeconds()).atZone(ZoneId.systemDefault())); + case DATE -> date(m.timestampEpochSeconds()); default -> value; }; super.getTableCellRendererComponent(t, shown, selected, focused, row, column); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java index 14f6ab1..3ed1de1 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PrivilegeKeysDialog.java @@ -1,41 +1,28 @@ package eu.lixko.ts3j.client.ui; -import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; import eu.lixko.ts3j.client.net.Group; import eu.lixko.ts3j.client.net.PrivilegeKey; import eu.lixko.ts3j.client.net.ServerModel; import eu.lixko.ts3j.client.session.ServerSession; -import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableRowSorter; -import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -43,13 +30,8 @@ import java.util.stream.Collectors; /** * The server's privilege keys, as the official client's Permissions > Privilege Keys * window: Create and Remove above the list, Reload below it. - * - *

One per server tab and modeless, like the ban list; the tab closes it when the - * connection goes away. */ -final class PrivilegeKeysDialog extends JDialog { - - private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); +final class PrivilegeKeysDialog extends ServerListDialog { private enum Column { KEY("Privilege Key", 320), @@ -68,37 +50,18 @@ final class PrivilegeKeysDialog extends JDialog { } } - private final ServerSession session; private final GroupIcons groupIcons; private final KeyTableModel tableModel = new KeyTableModel(); private final JTable table = new JTable(tableModel); private final JButton createButton = new JButton("Create", Icons.of("ADD")); private final JButton removeButton = new JButton("Remove", Icons.of("DELETE")); - private final JLabel status = new JLabel(" "); - - private boolean loading; PrivilegeKeysDialog(Frame owner, ServerSession session, GroupIcons groupIcons) { - super(owner, "Privilege Keys", false); - this.session = session; + super(owner, session, "Privilege Keys"); this.groupIcons = groupIcons; - - 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(buildTable(), BorderLayout.CENTER); - content.add(buildBottom(), BorderLayout.SOUTH); - setContentPane(content); bindKeys(); - - serverNameChanged(); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setPreferredSize(UIScale.scale(new Dimension(1040, 400))); - pack(); - setLocationRelativeTo(owner); - reload(); + layOut(buildToolbar(), buildTable(), new Dimension(1040, 400)); } // ---- construction ---- @@ -120,10 +83,6 @@ final class PrivilegeKeysDialog extends JDialog { } private JScrollPane buildTable() { - table.setFont(Theme.uiFont()); - table.setRowHeight(UIScale.scale(20)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - table.setFillsViewportHeight(true); table.setRowSorter(new TableRowSorter<>(tableModel)); table.getSelectionModel().addListSelectionListener(e -> updateButtons()); table.setComponentPopupMenu(tablePopup()); @@ -133,30 +92,7 @@ final class PrivilegeKeysDialog extends JDialog { table.getColumnModel().getColumn(c.ordinal()).setPreferredWidth(UIScale.scale(c.width)); table.getColumnModel().getColumn(c.ordinal()).setCellRenderer(renderer); } - - JScrollPane scroll = new JScrollPane(table); - scroll.getViewport().setBackground(Theme.treeBg()); - return scroll; - } - - private JPanel buildBottom() { - JButton reload = new JButton("Reload", Icons.of("REFRESH")); - reload.setToolTipText("Reload privilege keys
(F5)"); - reload.addActionListener(e -> reload()); - JButton close = new JButton("Close"); - close.addActionListener(e -> dispose()); - - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(reload, 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; + return scroll(table); } private JPopupMenu tablePopup() { @@ -169,60 +105,23 @@ final class PrivilegeKeysDialog extends JDialog { return menu; } - private static JMenuItem item(String text, String icon, Runnable action) { - JMenuItem item = new JMenuItem(text, Icons.of(icon)); - item.addActionListener(e -> action.run()); - return item; - } - private void bindKeys() { - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control N"), this::createKey); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("F5"), this::reload); - bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, KeyStroke.getKeyStroke("control W"), this::dispose); - bind(table, JComponent.WHEN_FOCUSED, KeyStroke.getKeyStroke("control C"), this::copyKeys); - bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), - this::removeKeys); - Dialogs.closeOnEscape(this); - } - - private static void bind(JComponent target, int condition, KeyStroke key, Runnable action) { - String name = "ts3-privilegekeys-" + key; - target.getInputMap(condition).put(key, name); - target.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent e) { - action.run(); - } - }); + bind("control N", this::createKey); + bind(table, JComponent.WHEN_FOCUSED, "control C", this::copyKeys); + bind(table, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, "DELETE", this::removeKeys); } // ---- data ---- - /** Follows the server's name, as the ban list's title does. */ - void serverNameChanged() { - String name = session.model().getServerName(); - setTitle(name == null || name.isBlank() ? "Privilege Keys" : "Privilege Keys - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { - if (loading) return; - loading = true; - status.setText("Loading…"); - Edt.handle(session.privilegeKeys().list(), keys -> { - loading = false; - if (!isDisplayable()) return; + @Override + void reload() { + load(session.privilegeKeys()::list, keys -> { tableModel.setKeys(keys); - status.setText(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); + showStatus(keys.size() == 1 ? "1 privilege key" : keys.size() + " privilege keys"); updateButtons(); }, failure -> { - loading = false; - if (!isDisplayable()) return; tableModel.setKeys(List.of()); - status.setText("Failed to request Privilege Key list: " + failure.getMessage()); + showError("Failed to request Privilege Key list: " + failure.getMessage()); updateButtons(); }); } @@ -252,14 +151,7 @@ final class PrivilegeKeysDialog extends JDialog { "Delete Privilege Keys", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer != JOptionPane.YES_OPTION) return; List tokens = selectedKeys().stream().map(PrivilegeKey::token).collect(Collectors.toList()); - Edt.handle(session.privilegeKeys().delete(tokens), () -> { - if (isDisplayable()) reload(); - }, failure -> { - if (!isDisplayable()) return; - JOptionPane.showMessageDialog(this, "Failed to delete Privilege Key: " + failure.getMessage(), getTitle(), - JOptionPane.ERROR_MESSAGE); - reload(); - }); + change(session.privilegeKeys().delete(tokens), "Failed to delete Privilege Key: "); } private void copyKeys() { @@ -330,8 +222,7 @@ final class PrivilegeKeysDialog extends JDialog { String path = session.model().channelPath(key.channelId()); return path.isEmpty() ? Integer.toString(key.channelId()) : path; case CREATED: - return key.createdEpochSeconds() <= 0 ? "" : DATE.format( - Instant.ofEpochSecond(key.createdEpochSeconds()).atZone(ZoneId.systemDefault())); + return date(key.createdEpochSeconds()); case DESCRIPTION: return key.description(); default: diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerListDialog.java new file mode 100644 index 0000000..3a19258 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerListDialog.java @@ -0,0 +1,211 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.net.RequestException; +import eu.lixko.ts3j.client.session.ServerSession; + +import javax.swing.AbstractAction; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A modeless window onto one of a server's lists, as the official client's ban list, + * complaints, privilege keys, offline messages and server log: a toolbar above the list, + * a status line with Reload and Close below it, titled after the server. + * + *

One per server tab; the tab closes it when the connection goes away. + */ +abstract class ServerListDialog extends JDialog { + + static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + final ServerSession session; + private final String name; + private final JLabel status = new JLabel(" "); + private boolean loading; + + ServerListDialog(Frame owner, ServerSession session, String name) { + super(owner, name, false); + this.session = session; + this.name = name; + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + bind("F5", this::reload); + bind("control W", this::dispose); + Dialogs.closeOnEscape(this); + } + + /** Reads the list again. */ + abstract void reload(); + + /** + * Lays the window out and starts loading; the last thing a subclass's constructor does. + * + * @param besideReload further controls in the bottom row, after Reload + */ + final void layOut(JComponent toolbar, JComponent list, Dimension size, Component... besideReload) { + JButton reload = new JButton("Reload", Icons.of("REFRESH")); + reload.setToolTipText("Reload
(F5)"); + reload.addActionListener(e -> reload()); + 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); + for (Component c : besideReload) { + left.add(Box.createHorizontalStrut(UIScale.scale(6))); + left.add(c); + } + + 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); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(6))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(toolbar, BorderLayout.NORTH); + content.add(list, BorderLayout.CENTER); + content.add(bottom, BorderLayout.SOUTH); + setContentPane(content); + + serverNameChanged(); + setPreferredSize(UIScale.scale(size)); + pack(); + setLocationRelativeTo(getOwner()); + reload(); + } + + /** The title for a server called {@code serverName}. */ + String title(String serverName) { + return name + " - " + serverName; + } + + void serverNameChanged() { + String serverName = session.model().getServerName(); + setTitle(serverName == null || serverName.isBlank() ? name : title(serverName)); + } + + void connectionLost() { + dispose(); + } + + // ---- requests ---- + + /** Requests the list unless a request is already out, showing "Loading…" meanwhile. */ + final void load(Supplier> request, Consumer loaded, + Consumer failed) { + if (loading) return; + loading = true; + showStatus("Loading…"); + Edt.handle(request.get(), result -> { + loading = false; + if (isDisplayable()) loaded.accept(result); + }, failure -> { + loading = false; + if (isDisplayable()) failed.accept(failure); + }); + } + + /** Sends a change and reloads, so the list shows what the server now holds; a failure is reported first. */ + final void change(CompletableFuture request, String failurePrefix) { + change(request, failurePrefix, () -> { + }); + } + + final void change(CompletableFuture request, String failurePrefix, Runnable onSuccess) { + Edt.handle(request, () -> { + if (!isDisplayable()) return; + onSuccess.run(); + reload(); + }, failure -> { + if (!isDisplayable()) return; + JOptionPane.showMessageDialog(this, failurePrefix + failure.getMessage(), getTitle(), + JOptionPane.ERROR_MESSAGE); + reload(); + }); + } + + /** Shows {@code text} under the list; {@code null} leaves the line blank. */ + final void showStatus(String text) { + status.setText(text == null || text.isEmpty() ? " " : text); + status.setForeground(Theme.chatEvent()); + } + + final void showError(String text) { + status.setText(text); + status.setForeground(Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); + } + + // ---- building blocks ---- + + /** Binds a key anywhere in the window. */ + final void bind(String key, Runnable action) { + bind(getRootPane(), JComponent.WHEN_IN_FOCUSED_WINDOW, key, action); + } + + static void bind(JComponent target, int condition, String key, Runnable action) { + String actionName = "ts3-" + key; + target.getInputMap(condition).put(KeyStroke.getKeyStroke(key), actionName); + target.getActionMap().put(actionName, new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + action.run(); + } + }); + } + + /** A list table with multiple selection, in a scroll pane. */ + static JScrollPane scroll(JTable table) { + table.setFont(Theme.uiFont()); + table.setRowHeight(UIScale.scale(20)); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + table.setFillsViewportHeight(true); + JScrollPane scroll = new JScrollPane(table); + scroll.getViewport().setBackground(Theme.treeBg()); + return scroll; + } + + /** @param icon an {@link Icons} name, or {@code null} */ + static JMenuItem item(String text, String icon, Runnable action) { + JMenuItem item = new JMenuItem(text, icon == null ? null : Icons.of(icon)); + item.addActionListener(e -> action.run()); + return item; + } + + static String date(long epochSeconds) { + if (epochSeconds <= 0) return ""; + return DATE.format(Instant.ofEpochSecond(epochSeconds).atZone(ZoneId.systemDefault())); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java index 07752f0..4954d80 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerLogDialog.java @@ -5,27 +5,21 @@ import com.formdev.flatlaf.util.UIScale; import eu.lixko.ts3j.client.config.ServerLogSettings; import eu.lixko.ts3j.client.config.ServerLogSettings.Highlight; import eu.lixko.ts3j.client.config.Settings; -import eu.lixko.ts3j.client.net.RequestException; import eu.lixko.ts3j.client.net.ServerLogEntry; import eu.lixko.ts3j.client.net.ServerLogEntry.Level; import eu.lixko.ts3j.client.net.ServerLogPage; import eu.lixko.ts3j.client.session.ServerSession; import eu.lixko.ts3j.client.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; @@ -37,12 +31,10 @@ 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; @@ -54,17 +46,11 @@ import java.util.Map; * 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 { +final class ServerLogDialog extends ServerListDialog { - 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 ServerSession session; private final Settings settings; private final ServerLogSettings view; @@ -91,18 +77,14 @@ final class ServerLogDialog extends JDialog { 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"); - /** Loading, failures and an empty log; hidden otherwise. */ - 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, ServerSession session, Settings settings) { - super(owner, TITLE, false); - this.session = session; + super(owner, session, "Server Log"); this.settings = settings; this.view = settings.serverLog; @@ -111,22 +93,12 @@ final class ServerLogDialog extends JDialog { 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); + olderButton.setMnemonic(KeyEvent.VK_O); + olderButton.setEnabled(false); + olderButton.addActionListener(e -> loadOlder()); + bind("control F", search::open); search.open(); - reload(); + layOut(buildToolbar(), center, new Dimension(900, 520), olderButton); } // ---- construction ---- @@ -190,67 +162,10 @@ final class ServerLogDialog extends JDialog { 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.setVisible(false); - 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 = session.model().getServerName(); - setTitle(name == null || name.isBlank() ? TITLE : TITLE + " - " + name); - } - - void connectionLost() { - dispose(); - } - - private void reload() { + @Override + void reload() { request(0); } @@ -260,17 +175,13 @@ final class ServerLogDialog extends JDialog { /** 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); - showStatus("Loading…", Theme.chatEvent()); - Edt.handle(session.serverLog().read(from), page -> { - loading = false; - if (isDisplayable()) received(page, from > 0); - }, failure -> { - loading = false; - if (!isDisplayable()) return; - failed(failure); + load(() -> { + olderButton.setEnabled(false); + return session.serverLog().read(from); + }, page -> received(page, from > 0), failure -> { + showError(failure.permissionDenied() + ? "Insufficient permissions to view Server Log" + : "Error requesting server log: " + failure.getMessage()); olderButton.setEnabled(olderFrom > 0); }); } @@ -284,13 +195,6 @@ final class ServerLogDialog extends JDialog { if (older) log.setCaretPosition(0); } - private void failed(RequestException failure) { - showStatus(failure.permissionDenied() - ? "Insufficient permissions to view Server Log" - : "Error requesting server log: " + failure.getMessage(), - Theme.isDark() ? new Color(0xFF6B6B) : new Color(0xC00000)); - } - private void settingsChanged() { settings.save(); render(false); @@ -316,7 +220,7 @@ final class ServerLogDialog extends JDialog { // appending at the end never fails } - showStatus(entries.isEmpty() ? "No log entries available" : null, Theme.chatEvent()); + showStatus(entries.isEmpty() ? "No log entries available" : null); if (toEnd) { log.setCaretPosition(doc.getLength()); @@ -326,20 +230,13 @@ final class ServerLogDialog extends JDialog { } } - /** Shows {@code text} under the log, or hides the label for {@code null}. */ - private void showStatus(String text, Color color) { - status.setText(text); - status.setForeground(color); - status.setVisible(text != null); - } - 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); + time = DATE.format(t); } return pad(time, 19) + " " + pad(e.channel(), channelWidth) + " " + pad(levelName(e.level()), LEVEL_WIDTH) + " " + e.message(); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index 25d827f..a04fe91 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -20,6 +20,9 @@ import javax.swing.JOptionPane; import javax.swing.JSplitPane; import java.awt.Component; import java.awt.Window; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; /** * One server connection and the views bound to it (tree, info and chat). The @@ -49,11 +52,8 @@ final class ServerTab { private int savedDividerLocation = -1; /** The one open ban list window for this server, if any. */ - private BanListDialog banList; - private PrivilegeKeysDialog privilegeKeys; - private ComplaintsDialog complaints; - private ServerLogDialog serverLog; - private OfflineMessagesDialog offlineMessages; + /** The open ban list, complaints and other list windows, one of each kind. */ + private final Map, ServerListDialog> listWindows = new HashMap<>(); /** The unread count last reported, to tell new mail from messages being read. */ private int unreadMessages; @@ -179,58 +179,60 @@ final class ServerTab { /** Opens the server's ban list, or brings the already open one forward. */ void showBanList(BanReasonPresets presets) { - if (!session.isConnected()) return; - if (banList == null || !banList.isDisplayable()) { - banList = new BanListDialog(host, session, settings, presets); - } - banList.setVisible(true); - banList.toFront(); + showListWindow(BanListDialog.class, () -> new BanListDialog(host, session, settings, presets)); } - /** Opens the server's complaints, or brings the already open window forward. */ void showComplaints() { - if (!session.isConnected()) return; - if (complaints == null || !complaints.isDisplayable()) { - complaints = new ComplaintsDialog(host, session, treeActions::banClient); - } - complaints.setVisible(true); - complaints.toFront(); + showListWindow(ComplaintsDialog.class, () -> new ComplaintsDialog(host, session, treeActions::banClient)); } - /** 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, session, settings); - } - serverLog.setVisible(true); - serverLog.toFront(); + showListWindow(ServerLogDialog.class, () -> new ServerLogDialog(host, session, settings)); } - /** Opens our offline message inbox, or brings the already open window forward. */ - void showOfflineMessages() { - if (!session.isConnected()) return; - if (offlineMessages == null || !offlineMessages.isDisplayable()) { - offlineMessages = new OfflineMessagesDialog(host, session, new OfflineMessagesDialog.Composer() { - @Override - public void compose() { - composeOfflineMessage(); - } + void showPrivilegeKeys() { + showListWindow(PrivilegeKeysDialog.class, () -> new PrivilegeKeysDialog(host, session, groupIcons)); + } - @Override - public void reply(OfflineMessage message, String body) { - if (!session.isConnected()) return; - OfflineMessageComposeDialog.reply(offlineMessages, session.offlineMessages(), contacts, message, body).setVisible(true); - } - }); + void showOfflineMessages() { + showListWindow(OfflineMessagesDialog.class, () -> new OfflineMessagesDialog(host, session, + new OfflineMessagesDialog.Composer() { + @Override + public void compose() { + composeOfflineMessage(); + } + + @Override + public void reply(OfflineMessage message, String body) { + if (!session.isConnected()) return; + OfflineMessageComposeDialog.reply(listWindow(OfflineMessagesDialog.class), + session.offlineMessages(), contacts, message, body).setVisible(true); + } + })); + } + + /** Opens a list window of this server, or brings the already open one forward. */ + private void showListWindow(Class type, Supplier create) { + if (!session.isConnected()) return; + ServerListDialog window = listWindow(type); + if (window == null) { + window = create.get(); + listWindows.put(type, window); } - offlineMessages.setVisible(true); - offlineMessages.toFront(); + window.setVisible(true); + window.toFront(); + } + + /** The open list window of a kind, or {@code null}. */ + private D listWindow(Class type) { + ServerListDialog window = listWindows.get(type); + return window != null && window.isDisplayable() ? type.cast(window) : null; } void composeOfflineMessage() { if (!session.permissions().canSendOfflineMessages()) return; - Window owner = offlineMessages != null && offlineMessages.isShowing() ? offlineMessages : host; + OfflineMessagesDialog inbox = listWindow(OfflineMessagesDialog.class); + Window owner = inbox != null && inbox.isShowing() ? inbox : host; OfflineMessageComposeDialog.compose(owner, session.offlineMessages(), contacts).setVisible(true); } @@ -238,7 +240,8 @@ final class ServerTab { void unreadMessagesChanged(int unread) { boolean newMail = unread > unreadMessages; unreadMessages = unread; - if (newMail && offlineMessages != null && offlineMessages.isDisplayable()) offlineMessages.reload(); + OfflineMessagesDialog inbox = listWindow(OfflineMessagesDialog.class); + if (newMail && inbox != null) inbox.reload(); } /** Asks for a privilege key and redeems it on this server. */ @@ -251,39 +254,16 @@ final class ServerTab { failure.getMessage(), "Error using Privilege Key", JOptionPane.ERROR_MESSAGE)); } - /** Opens the server's privilege keys, or brings the already open window forward. */ - void showPrivilegeKeys() { - if (!session.isConnected()) return; - if (privilegeKeys == null || !privilegeKeys.isDisplayable()) { - privilegeKeys = new PrivilegeKeysDialog(host, session, groupIcons); - } - privilegeKeys.setVisible(true); - privilegeKeys.toFront(); - } - - /** The server's name changed or the connection went; the server admin windows follow. */ + /** The server's name changed or the connection went; the list windows follow. */ void serverWindowsChanged(boolean connected) { - if (banList != null) { - if (connected) banList.serverNameChanged(); - else banList.connectionLost(); + for (ServerListDialog window : listWindows.values()) { + if (connected) window.serverNameChanged(); + else window.connectionLost(); } - if (complaints != null) { - if (connected) complaints.serverNameChanged(); - else complaints.connectionLost(); + if (!connected) { + listWindows.clear(); + unreadMessages = 0; } - if (serverLog != null) { - if (connected) serverLog.serverNameChanged(); - else serverLog.connectionLost(); - } - if (privilegeKeys != null) { - if (connected) privilegeKeys.serverNameChanged(); - else privilegeKeys.connectionLost(); - } - if (offlineMessages != null) { - if (connected) offlineMessages.serverNameChanged(); - else offlineMessages.connectionLost(); - } - if (!connected) unreadMessages = 0; } /** The contact list changed: names, colours and per-client playback follow. */