diff --git a/ts3-client/README.md b/ts3-client/README.md index 73da13f..b90071f 100644 --- a/ts3-client/README.md +++ b/ts3-client/README.md @@ -116,6 +116,10 @@ Android app in [`../android`](../android) does. - **Self status** — Away (with message) and Channel Commander toggles. - **Status bar** shows the server name, user count and live ping. - Change your nickname, mute/deafen from the toolbar. +- **Customize Toolbar** (right-click the toolbar), as in TeamSpeak 3: pick, order and + separate the buttons from ~70 actions (connection, self, dialogs, permissions, + recording, and channel/client actions on the tree's selection); search, drag and drop, + Reset to Defaults. ### Hotkeys - **Global hotkeys**, as in TeamSpeak 3: single keys or combinations (any key can act @@ -299,6 +303,8 @@ swing/ eu.lixko.ts3j.client └── ui ├── MainFrame window: menu, toolbar, tree | chat, status bar ├── MainCommands what the menu, toolbar and hotkeys do, each command once + ├── ToolbarActions what the toolbar can show (ToolbarAction), laid out per ToolbarLayout + ├── CustomizeToolbarDialog picks and orders the toolbar's buttons ├── ServerTreePanel TS3-style channel/client tree (group badges, spacers) ├── Spacers TS3 spacer-channel name parsing/rendering ├── InfoPanel channel description / client group + details view diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java index dbf3476..e23eadb 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java @@ -199,6 +199,8 @@ public final class Settings { // ---- window chrome ---- /** Whether the status bar at the bottom of the window is shown. */ public final Setting showStatusBar = flag("showStatusBar", true); + /** The main toolbar's buttons in order, comma-separated action ids with "-" for a separator; empty for the default set. */ + public final Setting toolbarLayout = text("toolbarLayout", ""); /** Whether the Master Volume slider is shown on the toolbar. */ public final Setting showMasterVolumeSlider = flag("showMasterVolumeSlider", true); /** Share of the tree/info column the tree takes, i.e. where their divider sits. */ diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CustomizeToolbarDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CustomizeToolbarDialog.java new file mode 100644 index 0000000..960f4a3 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CustomizeToolbarDialog.java @@ -0,0 +1,439 @@ +package eu.lixko.ts3j.client.ui; + +import com.formdev.flatlaf.FlatClientProperties; +import com.formdev.flatlaf.util.ScaledEmptyBorder; +import com.formdev.flatlaf.util.UIScale; +import eu.lixko.ts3j.client.config.Settings; +import eu.lixko.ts3j.client.ui.widget.Dialogs; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.DropMode; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.TransferHandler; +import javax.swing.UIManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.GridLayout; +import java.awt.Window; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.datatransfer.Transferable; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** + * The Customize Toolbar window, after the official client's: the actions not on the toolbar + * yet, grouped by category and searchable, beside the ones on it in order. Changes apply as + * they are made; Close only closes. + * + *

Actions move across with the arrow buttons, a double-click or a drag, and a drag within + * the list on the right reorders it. Separators can be added any number of times. + */ +final class CustomizeToolbarDialog extends JDialog { + + private static CustomizeToolbarDialog open; + + private final Settings settings; + private final ToolbarActions actions; + private final JTextField search = new JTextField(); + private final DefaultMutableTreeNode availableRoot = new DefaultMutableTreeNode(); + private final DefaultTreeModel availableModel = new DefaultTreeModel(availableRoot); + private final JTree available = new JTree(availableModel); + private final DefaultListModel selectedModel = new DefaultListModel<>(); + private final JList selected = new JList<>(selectedModel); + private final JButton add = arrowButton("→", "Add"); + private final JButton remove = arrowButton("←", "Remove"); + private final JButton up = arrowButton("↑", "Move Up"); + private final JButton down = arrowButton("↓", "Move Down"); + + /** Opens the window, or brings the open one forward. */ + static void show(Component parent, Settings settings, ToolbarActions actions) { + if (open == null) { + open = new CustomizeToolbarDialog(SwingUtilities.getWindowAncestor(parent), settings, actions); + open.setLocationRelativeTo(open.getOwner()); + } + open.setVisible(true); + open.toFront(); + } + + private CustomizeToolbarDialog(Window owner, Settings settings, ToolbarActions actions) { + super(owner, "Customize Toolbar", ModalityType.MODELESS); + this.settings = settings; + this.actions = actions; + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + + for (String id : ToolbarLayout.read(settings)) { + if (isKnown(id)) selectedModel.addElement(id); + } + + search.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, "Search…"); + search.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); + search.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + rebuildAvailable(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + rebuildAvailable(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + rebuildAvailable(); + } + }); + + available.setRootVisible(false); + available.setShowsRootHandles(true); + available.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + available.setCellRenderer(new AvailableRenderer()); + available.addTreeSelectionListener(e -> updateButtons()); + available.addMouseListener(doubleClick(this::addSelected)); + + selected.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + selected.setCellRenderer(new SelectedRenderer()); + selected.addListSelectionListener(e -> updateButtons()); + selected.addMouseListener(doubleClick(this::removeSelected)); + + LayoutTransfer transfer = new LayoutTransfer(); + available.setDragEnabled(true); + available.setDropMode(DropMode.ON); + available.setTransferHandler(transfer); + selected.setDragEnabled(true); + selected.setDropMode(DropMode.INSERT); + selected.setTransferHandler(transfer); + + add.addActionListener(e -> addSelected()); + remove.addActionListener(e -> removeSelected()); + up.addActionListener(e -> moveSelected(-1)); + down.addActionListener(e -> moveSelected(1)); + + JButton reset = new JButton("Reset to Defaults"); + reset.addActionListener(e -> resetToDefaults()); + JButton close = new JButton("Close"); + close.addActionListener(e -> dispose()); + + // The arrows sit with the left half, so the two lists stay the same width. + JPanel left = new JPanel(new BorderLayout(UIScale.scale(8), 0)); + left.setOpaque(false); + left.add(titled("Available actions:", new JScrollPane(available)), BorderLayout.CENTER); + left.add(buttonColumn(), BorderLayout.EAST); + JPanel both = new JPanel(new GridLayout(1, 2, UIScale.scale(8), 0)); + both.setOpaque(false); + both.add(left); + both.add(titled("Selected actions:", new JScrollPane(selected))); + + JPanel south = new JPanel(new BorderLayout()); + south.setOpaque(false); + south.add(reset, BorderLayout.WEST); + south.add(close, BorderLayout.EAST); + + JPanel top = new JPanel(new GridLayout(1, 2, UIScale.scale(8), 0)); + top.setOpaque(false); + top.add(search); + top.add(Box.createGlue()); + + JPanel content = new JPanel(new BorderLayout(0, UIScale.scale(8))); + content.setBackground(Theme.windowBg()); + content.setBorder(new ScaledEmptyBorder(10, 12, 10, 12)); + content.add(top, BorderLayout.NORTH); + content.add(both, BorderLayout.CENTER); + content.add(south, BorderLayout.SOUTH); + setContentPane(content); + Dialogs.closeOnEscape(this); + + rebuildAvailable(); + updateButtons(); + setSize(UIScale.scale(new Dimension(640, 460))); + setMinimumSize(UIScale.scale(new Dimension(480, 300))); + } + + @Override + public void dispose() { + open = null; + super.dispose(); + } + + // ---- layout ---- + + private JPanel buttonColumn() { + JPanel column = new JPanel(); + column.setLayout(new BoxLayout(column, BoxLayout.Y_AXIS)); + column.setOpaque(false); + // Lined up with the top of the lists, below their captions. + column.add(Box.createVerticalStrut(new JLabel(" ").getPreferredSize().height + UIScale.scale(4))); + column.add(add); + column.add(Box.createVerticalStrut(UIScale.scale(4))); + column.add(remove); + column.add(Box.createVerticalStrut(UIScale.scale(16))); + column.add(up); + column.add(Box.createVerticalStrut(UIScale.scale(4))); + column.add(down); + return column; + } + + private static JPanel titled(String caption, JComponent body) { + JPanel panel = new JPanel(new BorderLayout(0, UIScale.scale(4))); + panel.setOpaque(false); + panel.add(new JLabel(caption), BorderLayout.NORTH); + panel.add(body, BorderLayout.CENTER); + return panel; + } + + private static JButton arrowButton(String arrow, String tooltip) { + JButton button = new JButton(arrow); + button.setToolTipText(tooltip); + button.setFocusable(false); + return button; + } + + private static MouseAdapter doubleClick(Runnable action) { + return new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) action.run(); + } + }; + } + + // ---- the two lists ---- + + private boolean isKnown(String id) { + return id.equals(ToolbarLayout.SEPARATOR) || actions.byId(id).isPresent(); + } + + /** Lists what is not on the toolbar yet and matches the search, keeping the open category. */ + private void rebuildAvailable() { + Optional kept = availableId(); + String query = search.getText().trim().toLowerCase(Locale.ROOT); + List used = Collections.list(selectedModel.elements()); + + availableRoot.removeAllChildren(); + if (query.isEmpty() || "separator".contains(query)) { + DefaultMutableTreeNode separators = new DefaultMutableTreeNode("Separator"); + separators.add(new DefaultMutableTreeNode(ToolbarLayout.SEPARATOR)); + availableRoot.add(separators); + } + DefaultMutableTreeNode category = null; + for (ToolbarAction action : actions.all()) { + if (used.contains(action.id) || !action.label.toLowerCase(Locale.ROOT).contains(query)) continue; + if (category == null || !category.getUserObject().equals(action.category.label)) { + category = new DefaultMutableTreeNode(action.category.label); + availableRoot.add(category); + } + category.add(new DefaultMutableTreeNode(action)); + } + availableModel.reload(); + for (int row = 0; row < available.getRowCount(); row++) available.expandRow(row); + kept.ifPresent(this::selectAvailable); + updateButtons(); + } + + /** The action (or separator) id selected on the left. */ + private Optional availableId() { + TreePath path = available.getSelectionPath(); + if (path == null) return Optional.empty(); + DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); + if (!node.isLeaf() || node.getParent() == availableRoot) return Optional.empty(); + Object item = node.getUserObject(); + return Optional.of(item instanceof ToolbarAction ? ((ToolbarAction) item).id : (String) item); + } + + private void selectAvailable(String id) { + for (int row = 0; row < available.getRowCount(); row++) { + TreePath path = available.getPathForRow(row); + Object item = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + String itemId = item instanceof ToolbarAction ? ((ToolbarAction) item).id : null; + if (id.equals(itemId) || (id.equals(ToolbarLayout.SEPARATOR) && ToolbarLayout.SEPARATOR.equals(item))) { + available.setSelectionPath(path); + return; + } + } + } + + private void updateButtons() { + int index = selected.getSelectedIndex(); + add.setEnabled(availableId().isPresent()); + remove.setEnabled(index >= 0); + up.setEnabled(index > 0); + down.setEnabled(index >= 0 && index < selectedModel.size() - 1); + } + + // ---- changes ---- + + /** Puts the action selected on the left after the one selected on the right, or last. */ + private void addSelected() { + availableId().ifPresent(id -> { + int at = selected.getSelectedIndex() >= 0 ? selected.getSelectedIndex() + 1 : selectedModel.size(); + insert(id, at); + }); + } + + private void insert(String id, int at) { + selectedModel.add(at, id); + selected.setSelectedIndex(at); + selected.ensureIndexIsVisible(at); + changed(); + } + + private void removeSelected() { + int index = selected.getSelectedIndex(); + if (index < 0) return; + String id = selectedModel.remove(index); + if (!selectedModel.isEmpty()) selected.setSelectedIndex(Math.min(index, selectedModel.size() - 1)); + changed(); + selectAvailable(id); + } + + private void moveSelected(int delta) { + int from = selected.getSelectedIndex(); + int to = from + delta; + if (from < 0 || to < 0 || to >= selectedModel.size()) return; + selectedModel.add(to, selectedModel.remove(from)); + selected.setSelectedIndex(to); + selected.ensureIndexIsVisible(to); + changed(); + } + + private void resetToDefaults() { + if (JOptionPane.showConfirmDialog(this, "Do you really want to reset the toolbar?", "Please Confirm", + JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { + return; + } + selectedModel.clear(); + ToolbarLayout.DEFAULT.forEach(selectedModel::addElement); + changed(); + } + + /** Applies the list on the right to the toolbar. */ + private void changed() { + ToolbarLayout.write(settings, new ArrayList<>(Collections.list(selectedModel.elements()))); + rebuildAvailable(); + } + + // ---- rendering ---- + + private String labelOf(String id) { + return id.equals(ToolbarLayout.SEPARATOR) ? "Separator" : actions.byId(id).map(a -> a.label).orElse(id); + } + + private final class AvailableRenderer extends DefaultTreeCellRenderer { + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, + boolean leaf, int row, boolean hasFocus) { + super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + Object item = ((DefaultMutableTreeNode) value).getUserObject(); + if (item instanceof ToolbarAction) { + setText(((ToolbarAction) item).label); + setIcon(((ToolbarAction) item).listIcon()); + } else if (ToolbarLayout.SEPARATOR.equals(item)) { + setText(labelOf(ToolbarLayout.SEPARATOR)); + setIcon(null); + } else { + setIcon(null); + } + return this; + } + } + + private final class SelectedRenderer extends DefaultListCellRenderer { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean sel, + boolean hasFocus) { + super.getListCellRendererComponent(list, value, index, sel, hasFocus); + String id = (String) value; + setText(labelOf(id)); + setIcon(actions.byId(id).map(ToolbarAction::listIcon).orElse(null)); + if (id.equals(ToolbarLayout.SEPARATOR) && !sel) setForeground(UIManager.getColor("Label.disabledForeground")); + return this; + } + } + + /** + * Drags between the lists: from the left onto the right adds, within the right reorders, + * and from the right back onto the left removes. + */ + private final class LayoutTransfer extends TransferHandler { + /** Where on the right the dragged item sat; -1 while it comes from the left. */ + private int dragIndex = -1; + + @Override + public int getSourceActions(JComponent c) { + return MOVE; + } + + @Override + protected Transferable createTransferable(JComponent c) { + if (c == selected) { + dragIndex = selected.getSelectedIndex(); + return dragIndex < 0 ? null : new StringSelection(selectedModel.get(dragIndex)); + } + dragIndex = -1; + return availableId().map(StringSelection::new).orElse(null); + } + + @Override + public boolean canImport(TransferSupport support) { + if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) return false; + return support.getComponent() == selected || dragIndex >= 0; + } + + @Override + public boolean importData(TransferSupport support) { + if (!canImport(support)) return false; + String id; + try { + id = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); + } catch (Exception e) { + return false; + } + if (!isKnown(id)) return false; + if (support.getComponent() != selected) { + selected.setSelectedIndex(dragIndex); + removeSelected(); + return true; + } + int at = ((JList.DropLocation) support.getDropLocation()).getIndex(); + if (dragIndex >= 0) { + selectedModel.remove(dragIndex); + if (dragIndex < at) at--; + } + insert(id, at); + return true; + } + + @Override + protected void exportDone(JComponent source, Transferable data, int action) { + dragIndex = -1; + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java index 13e4e04..0b3fea0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java @@ -28,6 +28,7 @@ import javax.swing.JTextField; import java.awt.GridLayout; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.function.Consumer; /** @@ -65,6 +66,12 @@ public final class MainCommands { return tab == null ? null : tab.session(); } + /** The tab on screen while its server is connected. */ + Optional connectedTab() { + ServerTab tab = frame.selectedTab(); + return tab != null && tab.session().isConnected() ? Optional.of(tab) : Optional.empty(); + } + /** The server on screen while it is connected, else none. */ List currentConnected() { return targets(true); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java index de46c19..46fcfe3 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java @@ -218,7 +218,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { } private MainToolbar buildToolbar() { - return new MainToolbar(settings, commands, pictures); + return new MainToolbar(settings, new ToolbarActions(commands, sessions), pictures); } /** Rebuilds the icon-bearing chrome after the active icon pack changed. */ @@ -310,6 +310,11 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { updateTray(); } + /** The tree on {@code tab} changed, or what is selected in it: the toolbar's tree actions follow. */ + public void treeChanged(ServerTab tab) { + if (tab == selected) toolbar.refresh(); + } + /** The server on {@code tab} may have changed its host button. */ public void refreshHostButton(ServerTab tab) { if (tab == selected) toolbar.showHostButton(hostButtonOf(tab)); @@ -630,6 +635,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { /** The contact list changed somewhere: every open server follows. */ private void contactsChanged() { for (ServerTab tab : tabs) tab.contactsChanged(); + toolbar.refresh(); } void showSettings() { @@ -706,7 +712,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { boolean active = selected != null && selected == micTab(); boolean away = connected && selected.session().isAway(); boolean commander = connected && selected.session().isCommander(); - toolbar.refresh(connected, anyConnected, micMuted, deaf, active, away); + toolbar.refresh(); toolbar.showHostButton(hostButtonOf(selected)); menuBar.refresh(connected, anyConnected, micMuted, deaf, active, away, commander); statusBar.showRecording(connected && selected.session().isRecording()); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java index 07d81e8..3bfc376 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java @@ -6,100 +6,75 @@ import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.net.HostButton; import eu.lixko.ts3j.client.net.PictureDownloads; import eu.lixko.ts3j.client.ui.icons.Icons; -import eu.lixko.ts3j.client.ui.widget.DropDownToggleButton; import javax.swing.Box; -import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JLabel; +import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSlider; -import javax.swing.JToggleButton; import javax.swing.JToolBar; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; +import java.util.ArrayList; +import java.util.List; /** - * The main window's toolbar: connect/disconnect, the per-tab mic/speaker/away - * controls, and the Master Volume slider and the server's host button on the - * right. A right-click anywhere on the bar opens a customization menu for the - * window's optional chrome (this toolbar has no say over the status bar's own - * visibility beyond reporting the toggle). + * The main window's toolbar: the buttons the user picked in {@link CustomizeToolbarDialog} + * (connect/disconnect and the per-tab mic/speaker/away controls by default), then the + * Master Volume slider and the server's host button on the right. A right-click anywhere + * on the bar opens a customization menu for the window's optional chrome. * - *

Its buttons run {@link MainCommands}, and it owns no connection/tab state - * itself — {@link #refresh} is handed everything it needs to redraw each - * time the selection changes. + *

It owns no connection/tab state itself: each button reads what it shows from its + * {@link ToolbarAction} on {@link #refresh}. */ final class MainToolbar extends JToolBar { private final Settings settings; - private final MainCommands commands; - - private final JButton connectButton; - private final JButton disconnectButton; - private final JToggleButton activeButton; - private final JToggleButton micButton; - private final JToggleButton speakerButton; - private final DropDownToggleButton awayButton; + private final ToolbarActions actions; + private final List controls = new ArrayList<>(); private final JComponent masterVolumePanel; private final HostButtonView hostButton; - MainToolbar(Settings settings, MainCommands commands, PictureDownloads pictures) { + MainToolbar(Settings settings, ToolbarActions actions, PictureDownloads pictures) { this.settings = settings; - this.commands = commands; + this.actions = actions; setFloatable(false); setBackground(Theme.toolbarBg()); setBorder(new ScaledEmptyBorder(4, 6, 4, 6)); setComponentPopupMenu(buildContextMenu()); - connectButton = new JButton(Icons.connect()); - connectButton.setToolTipText("Connect to a server"); - connectButton.addActionListener(e -> commands.connect()); - - disconnectButton = new JButton(Icons.disconnect()); - disconnectButton.setToolTipText("Disconnect"); - disconnectButton.addActionListener(e -> commands.disconnect()); - - activeButton = new JToggleButton(Icons.micActive()); - activeButton.setToolTipText("Speak on this server (moves the microphone to this tab)"); - activeButton.addActionListener(e -> commands.activate()); - - micButton = new JToggleButton(Icons.mic()); - micButton.setToolTipText("Mute / unmute microphone on this server"); - micButton.addActionListener(e -> commands.toggleMicMuted()); - - speakerButton = new JToggleButton(Icons.speaker()); - speakerButton.setToolTipText("Deafen / undeafen (mute speakers) on this server"); - speakerButton.addActionListener(e -> commands.toggleDeafened()); - - awayButton = new DropDownToggleButton(Icons.away(), - "Away on this server (the arrow offers the global actions and presets)", - commands::buildAwayMenu); - awayButton.addActionListener(e -> commands.setAway(awayButton.isSelected())); - - JButton settingsButton = new JButton(Icons.settings()); - settingsButton.setToolTipText("Options"); - settingsButton.addActionListener(e -> commands.showSettings()); - - add(connectButton); - add(disconnectButton); - addSeparator(); - add(activeButton); - add(micButton); - add(speakerButton); - add(awayButton); - addSeparator(); - add(settingsButton); - add(Box.createHorizontalGlue()); masterVolumePanel = buildMasterVolumeControl(); masterVolumePanel.setVisible(settings.showMasterVolumeSlider.get()); - add(masterVolumePanel); hostButton = new HostButtonView(pictures); + rebuild(); + settings.toolbarLayout.addListener(layout -> rebuild()); + } + + /** Lays the buttons out again from the saved layout. */ + private void rebuild() { + removeAll(); + controls.clear(); + for (String id : ToolbarLayout.read(settings)) { + if (id.equals(ToolbarLayout.SEPARATOR)) { + addSeparator(); + continue; + } + actions.byId(id).ifPresent(action -> { + ToolbarAction.Control control = action.createControl(this::refresh); + controls.add(control); + add(control.component()); + }); + } + add(Box.createHorizontalGlue()); + add(masterVolumePanel); add(hostButton); + revalidate(); + repaint(); } /** Shows the selected server's host button; {@code null} hides it. */ @@ -108,22 +83,8 @@ final class MainToolbar extends JToolBar { } /** Reflects the current tab's state on the buttons. */ - void refresh(boolean connected, boolean anyConnected, boolean micMuted, boolean deafened, - boolean active, boolean away) { - disconnectButton.setEnabled(connected); - micButton.setEnabled(connected); - speakerButton.setEnabled(connected); - activeButton.setEnabled(connected); - // The away menu's actions are global, so the arrow stays live while any server is up. - awayButton.setEnabled(anyConnected); - awayButton.setToggleEnabled(connected); - - micButton.setSelected(micMuted); - micButton.setIcon(micMuted ? Icons.micMutedLarge() : Icons.mic()); - speakerButton.setSelected(deafened); - speakerButton.setIcon(deafened ? Icons.speakerMutedLarge() : Icons.speaker()); - activeButton.setSelected(active); - awayButton.setSelected(away); + void refresh() { + for (ToolbarAction.Control control : controls) control.refresh(); } /** The Master Volume slider: multiplies both voice and notification volume. */ @@ -180,8 +141,13 @@ final class MainToolbar extends JToolBar { repaint(); }); + JMenuItem customize = new JMenuItem("Customize Toolbar…"); + customize.addActionListener(e -> CustomizeToolbarDialog.show(this, settings, actions)); + menu.add(statusBarItem); menu.add(volumeItem); + menu.addSeparator(); + menu.add(customize); return menu; } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarAction.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarAction.java new file mode 100644 index 0000000..c005451 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarAction.java @@ -0,0 +1,187 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.ui.icons.Icons; +import eu.lixko.ts3j.client.ui.widget.DropDownToggleButton; + +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JPopupMenu; +import javax.swing.JToggleButton; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** + * Something the main toolbar can show, as the Customize Toolbar window lists it: a name, + * the group it is filed under and what its button does. + * + *

State is read back each time the toolbar refreshes, so an action only says how to ask + * (is it enabled, is the toggle down); it never keeps a copy. + */ +final class ToolbarAction { + + /** The groups of the Customize Toolbar window, in the official client's order. */ + enum Category { + CONNECTION("Connection"), + SELF("Self"), + DIALOGS("Dialogs"), + PERMISSIONS("Permissions"), + RECORDING("Recording"), + CHANNEL("Channel"), + CLIENT("Client"), + MISC("Misc"); + + final String label; + + Category(String label) { + this.label = label; + } + } + + private enum Kind { + BUTTON, + TOGGLE, + DROP_DOWN + } + + final String id; + final Category category; + final String label; + private final String[] iconKeys; + private final Runnable perform; + private Kind kind = Kind.BUTTON; + private BooleanSupplier enabled = () -> true; + private BooleanSupplier selected = () -> false; + private Supplier icon; + private Supplier selectedIcon; + private Supplier menu; + private BooleanSupplier menuEnabled; + + /** @param iconKeys the icon pack keys to try, in turn, for both the button and the list */ + ToolbarAction(String id, Category category, String label, Runnable perform, String... iconKeys) { + this.id = id; + this.category = category; + this.label = label; + this.perform = perform; + this.iconKeys = iconKeys; + this.icon = () -> Icons.toolbarOfAny(iconKeys); + this.selectedIcon = icon; + } + + ToolbarAction enabledWhen(BooleanSupplier enabled) { + this.enabled = enabled; + return this; + } + + /** Makes the button a toggle that is down while {@code selected} holds. */ + ToolbarAction toggle(BooleanSupplier selected) { + this.kind = Kind.TOGGLE; + this.selected = selected; + return this; + } + + /** A toggle with an arrow beside it opening {@code menu}, reachable while {@code menuEnabled} holds. */ + ToolbarAction dropDown(BooleanSupplier selected, Supplier menu, BooleanSupplier menuEnabled) { + toggle(selected); + this.kind = Kind.DROP_DOWN; + this.menu = menu; + this.menuEnabled = menuEnabled; + return this; + } + + /** The button's icon when the pack's would not do, e.g. for the built-in look's painted ones. */ + ToolbarAction icon(Supplier icon) { + this.icon = icon; + this.selectedIcon = icon; + return this; + } + + /** The icon a toggle shows while down. */ + ToolbarAction selectedIcon(Supplier selectedIcon) { + this.selectedIcon = selectedIcon; + return this; + } + + /** The icon beside the name in lists, at menu size; {@code null} when the pack has none. */ + Icon listIcon() { + return Icons.ofAny(iconKeys); + } + + /** + * A new button for this action. + * + * @param afterPerform run once the action has been carried out, so the toolbar can catch up + */ + Control createControl(Runnable afterPerform) { + Runnable run = () -> { + perform.run(); + afterPerform.run(); + }; + return switch (kind) { + case BUTTON -> new ButtonControl(new JButton(), run); + case TOGGLE -> new ButtonControl(new JToggleButton(), run); + case DROP_DOWN -> new DropDownControl(run); + }; + } + + /** One of this action's buttons on the toolbar. */ + abstract static class Control { + abstract JComponent component(); + + /** Re-reads the action's state onto the button. */ + abstract void refresh(); + } + + private final class ButtonControl extends Control { + private final AbstractButton button; + + ButtonControl(AbstractButton button, Runnable run) { + this.button = button; + button.setToolTipText(label); + button.setFocusable(false); + button.addActionListener(e -> run.run()); + refresh(); + } + + @Override + JComponent component() { + return button; + } + + @Override + void refresh() { + boolean down = selected.getAsBoolean(); + Icon shown = down ? selectedIcon.get() : icon.get(); + button.setIcon(shown); + // Packs lack some icons, and the built-in look has few; the name stands in for them. + button.setText(shown == null ? label : null); + button.setSelected(down); + button.setEnabled(enabled.getAsBoolean()); + } + } + + private final class DropDownControl extends Control { + private final DropDownToggleButton button; + + DropDownControl(Runnable run) { + button = new DropDownToggleButton(icon.get(), label, menu); + button.addActionListener(e -> run.run()); + refresh(); + } + + @Override + JComponent component() { + return button; + } + + @Override + void refresh() { + boolean down = selected.getAsBoolean(); + button.setIcon(down ? selectedIcon.get() : icon.get()); + button.setEnabled(menuEnabled.getAsBoolean()); + button.setToggleEnabled(enabled.getAsBoolean()); + button.setSelected(down); + } + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarActions.java new file mode 100644 index 0000000..8681135 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarActions.java @@ -0,0 +1,401 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.contacts.ContactType; +import eu.lixko.ts3j.client.net.ChannelNode; +import eu.lixko.ts3j.client.net.ChannelSettings; +import eu.lixko.ts3j.client.net.ClientEntry; +import eu.lixko.ts3j.client.net.Permissions; +import eu.lixko.ts3j.client.session.ServerSession; +import eu.lixko.ts3j.client.session.Sessions; +import eu.lixko.ts3j.client.ui.ToolbarAction.Category; +import eu.lixko.ts3j.client.ui.icons.Icons; +import eu.lixko.ts3j.client.ui.server.ServerTab; +import eu.lixko.ts3j.client.ui.server.ServerTreePanel; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; + +/** + * Every action the main toolbar can be given, after the official client's Customize Toolbar + * list, limited to what this client can do. + * + *

Channel actions work on the channel selected in the tree, or the one of the selected + * client, falling back to our own channel. Client actions work on the selected clients. + */ +final class ToolbarActions { + + private final MainCommands commands; + private final Sessions sessions; + private final Map byId = new LinkedHashMap<>(); + + ToolbarActions(MainCommands commands, Sessions sessions) { + this.commands = commands; + this.sessions = sessions; + addConnection(); + addSelf(); + addDialogs(); + addPermissions(); + addRecording(); + addChannel(); + addClient(); + addMisc(); + } + + /** All of them, grouped by category. */ + List all() { + return List.copyOf(byId.values()); + } + + Optional byId(String id) { + return Optional.ofNullable(byId.get(id)); + } + + private ToolbarAction add(String id, Category category, String label, Runnable perform, String... iconKeys) { + ToolbarAction action = new ToolbarAction(id, category, label, perform, iconKeys); + byId.put(id, action); + return action; + } + + // ---- the catalogue ---- + + private void addConnection() { + add("connect", Category.CONNECTION, "Connect", commands::connect, "CONNECT") + .icon(Icons::connect); + add("disconnect", Category.CONNECTION, "Disconnect from Current", commands::disconnect, "DISCONNECT") + .icon(Icons::disconnect) + .enabledWhen(this::connected); + add("disconnectAll", Category.CONNECTION, "Disconnect from All", commands::disconnectAll, "DISCONNECT_ALL") + .enabledWhen(sessions::anyConnected); + } + + private void addSelf() { + add("away", Category.SELF, "Toggle Away Status", () -> commands.setAway(!is(ServerSession::isAway)), "AWAY") + .icon(Icons::away) + .dropDown(() -> is(ServerSession::isAway), commands::buildAwayMenu, sessions::anyConnected) + .enabledWhen(this::connected); + add("activateMicrophone", Category.SELF, "Activate Microphone", commands::activate, "ACTIVATE_MICROPHONE") + .icon(Icons::micActive) + .toggle(() -> is(s -> s == sessions.microphoneOwner())) + .enabledWhen(this::connected); + add("muteMicrophone", Category.SELF, "Mute Microphone", commands::toggleMicMuted, "INPUT_MUTED") + .icon(Icons::mic) + .selectedIcon(Icons::micMutedLarge) + .toggle(() -> is(ServerSession::isMicMuted)) + .enabledWhen(this::connected); + add("muteSpeakers", Category.SELF, "Mute Speakers/Headphones", commands::toggleDeafened, "OUTPUT_MUTED") + .icon(Icons::speaker) + .selectedIcon(Icons::speakerMutedLarge) + .toggle(() -> is(ServerSession::isDeafened)) + .enabledWhen(this::connected); + add("channelCommander", Category.SELF, "Channel Commander", + () -> commands.setCommander(!is(ServerSession::isCommander)), "CHANNEL_COMMANDER") + .toggle(() -> is(ServerSession::isCommander)) + .enabledWhen(this::connected); + add("changeNickname", Category.SELF, "Change Nickname", commands::changeNickname, "CHANGE_NICKNAME"); + add("phoneticNickname", Category.SELF, "Set Phonetic Nickname", commands::setPhoneticNickname, + "PHONETICSNICKNAME") + .enabledWhen(this::connected); + add("requestTalkPower", Category.SELF, "Request Talk Power", commands::requestTalkPower, "TALK_POWER_REQUEST") + .enabledWhen(() -> is(s -> !s.isTalkRequested() && s.canRequestTalkPower())); + add("cancelTalkPowerRequest", Category.SELF, "Cancel Talk Power Request", commands::requestTalkPower, + "TALK_POWER_CANCEL_REQUEST") + .enabledWhen(() -> is(ServerSession::isTalkRequested)); + add("setAvatar", Category.SELF, "Set Avatar", commands::setAvatar, "UPLOAD_AVATAR") + .enabledWhen(() -> permitted(Permissions::canSetAvatar)); + add("deleteAvatar", Category.SELF, "Delete Avatar", commands::deleteAvatar, "DELETE_AVATAR") + .enabledWhen(() -> is(ServerSession::hasAvatar)); + add("giantPtt", Category.SELF, "Giant PTT", commands::showGiantPtt, "CAPTURE"); + } + + private void addDialogs() { + add("addBookmark", Category.DIALOGS, "Add to Bookmarks", commands::addCurrentServerBookmark, "BOOKMARK_ADD") + .enabledWhen(this::connected); + add("bookmarks", Category.DIALOGS, "Manage Bookmarks", commands::manageBookmarks, "BOOKMARK_MANAGER"); + add("banList", Category.DIALOGS, "Ban List", commands::showBanList, "BAN_LIST") + .enabledWhen(() -> permitted(Permissions::canViewBanList)); + add("complaints", Category.DIALOGS, "Complaints List", commands::showComplaints, "COMPLAINT_LIST") + .enabledWhen(() -> permitted(Permissions::canViewComplaints)); + add("contacts", Category.DIALOGS, "Contacts", commands::showContacts, "CONTACT", "EDIT_FRIEND_FOE_STATUS"); + add("identities", Category.DIALOGS, "Identities", commands::showIdentities, "IDENTITY_MANAGER"); + add("offlineMessages", Category.DIALOGS, "Offline Messages", commands::showOfflineMessages, "OFFLINE_MESSAGES") + .enabledWhen(this::connected); + add("options", Category.DIALOGS, "Options", commands::showSettings, "SETTINGS") + .icon(Icons::settings); + add("serverLog", Category.DIALOGS, "Server Log", commands::showServerLog, "SERVER_LOG") + .enabledWhen(() -> permitted(Permissions::canViewServerLog)); + } + + private void addPermissions() { + add("privilegeKeys", Category.PERMISSIONS, "Privilege Keys", commands::showPrivilegeKeys, "TOKEN") + .enabledWhen(() -> permitted(Permissions::canListPrivilegeKeys)); + add("usePrivilegeKey", Category.PERMISSIONS, "Use Privilege Key", commands::usePrivilegeKey, "TOKEN_USE") + .enabledWhen(this::connected); + } + + private void addRecording() { + add("startMultitrackRecording", Category.RECORDING, "Start Multitrack Recording", + () -> commands.startRecording(true), "RECORDING_START") + .enabledWhen(() -> is(s -> !s.isRecording())); + add("startRecording", Category.RECORDING, "Start Recording", + () -> commands.startRecording(false), "RECORDING_START") + .enabledWhen(() -> is(s -> !s.isRecording())); + add("stopRecording", Category.RECORDING, "Stop Recording", commands::stopRecording, "RECORDING_STOP") + .enabledWhen(() -> is(ServerSession::isRecording)); + } + + private void addChannel() { + add("joinChannel", Category.CHANNEL, "Join Channel", + () -> onChannel((tab, c) -> tab.treeActions().joinChannel(c.id)), "CHANNEL_SWITCH") + .enabledWhen(() -> channel().filter(c -> c != currentChannel().orElse(null)).isPresent()); + add("createChannel", Category.CHANNEL, "Create Channel", + () -> onTab(tab -> tab.treeActions().createChannel(null, ChannelSettings.Type.PERMANENT)), + "CHANNEL_CREATE") + .enabledWhen(this::connected); + add("createSpacer", Category.CHANNEL, "Create Spacer", + () -> onTab(tab -> tab.treeActions().createSpacer()), "CHANNEL_CREATE_SPACER", "CHANNEL_CREATE") + .enabledWhen(this::connected); + // Temporary, as from the channel's own menu: a channel made below another is usually a throwaway one. + add("createSubChannel", Category.CHANNEL, "Create Sub-Channel", + () -> onChannel((tab, c) -> tab.treeActions().createChannel(c, ChannelSettings.Type.TEMPORARY)), + "CHANNEL_CREATE_SUB") + .enabledWhen(this::hasChannel); + add("deleteChannel", Category.CHANNEL, "Delete Channel", + () -> onChannel((tab, c) -> tab.treeActions().deleteChannel(c)), "CHANNEL_DELETE") + .enabledWhen(this::hasChannel); + add("editChannel", Category.CHANNEL, "Edit Channel", + () -> onChannel((tab, c) -> tab.treeActions().editChannel(c)), "CHANNEL_EDIT") + .enabledWhen(this::hasChannel); + add("grantNextTalkPower", Category.CHANNEL, "Grant Next Requested Talk Power", + () -> commands.grantNextTalkPower(commands.currentConnected(), false), "TALK_POWER_GRANT_NEXT") + .enabledWhen(() -> permitted(Permissions::canGrantTalkPower)); + add("revokeAllGrantNextTalkPower", Category.CHANNEL, "Revoke All and Grant Next Requested Talk Power", + () -> commands.grantNextTalkPower(commands.currentConnected(), true), "TALK_POWER_REVOKE_ALL_GRANT_NEXT") + .enabledWhen(() -> permitted(Permissions::canGrantTalkPower)); + add("browseFiles", Category.CHANNEL, "Open File Browser", + () -> onChannel((tab, c) -> tab.treeActions().browseFiles(c)), "FILETRANSFER") + .enabledWhen(() -> hasChannel() && permitted(Permissions::canBrowseFiles)); + add("subscribeAll", Category.CHANNEL, "Subscribe to All Channels", () -> subscribeAll(true), + "SUBSCRIBE_TO_ALL_CHANNELS") + .enabledWhen(this::connected); + add("subscribeChannel", Category.CHANNEL, "Subscribe to Channel", + () -> setSubscribed(false, true), "SUBSCRIBE_TO_CHANNEL") + .enabledWhen(() -> channel().filter(c -> !c.subscribed).isPresent()); + add("subscribeFamily", Category.CHANNEL, "Subscribe to Channel Family", + () -> setSubscribed(true, true), "SUBSCRIBE_TO_CHANNEL_FAMILY", "SUBSCRIBE_TO_ALL_CHANNELS") + .enabledWhen(() -> channel().filter(c -> !c.children.isEmpty() && !c.allSubscribed()).isPresent()); + add("unsubscribeAll", Category.CHANNEL, "Unsubscribe from All Channels", () -> subscribeAll(false), + "UNSUBSCRIBE_FROM_ALL_CHANNELS") + .enabledWhen(this::connected); + add("unsubscribeChannel", Category.CHANNEL, "Unsubscribe from Channel", + () -> setSubscribed(false, false), "UNSUBSCRIBE_FROM_CHANNEL") + .enabledWhen(() -> channel().filter(c -> c.subscribed).isPresent()); + add("unsubscribeFamily", Category.CHANNEL, "Unsubscribe from Channel Family", + () -> setSubscribed(true, false), "UNSUBSCRIBE_FROM_CHANNEL_FAMILY", "UNSUBSCRIBE_FROM_ALL_CHANNELS") + .enabledWhen(() -> channel().filter(c -> !c.children.isEmpty() && c.anySubscribed()).isPresent()); + } + + private void addClient() { + add("openChat", Category.CLIENT, "Open Text Chat", + () -> onClient(ServerTreePanel.Actions::openPrivateChat), "PLAYER_CHAT") + .enabledWhen(this::hasOtherClient); + add("poke", Category.CLIENT, "Poke Client", () -> onClient(ServerTreePanel.Actions::pokeClient), "POKE") + .enabledWhen(this::hasOtherClient); + add("complain", Category.CLIENT, "Make a Complaint", + () -> onClient(ServerTreePanel.Actions::complainAboutClient), "SEND_COMPLAINT") + .enabledWhen(this::hasOtherClient); + add("addFriend", Category.CLIENT, "Add as Friend", + () -> onClient((a, c) -> a.addContact(c, ContactType.FRIEND)), "ADD_FRIEND") + .enabledWhen(() -> otherClient().filter(c -> contactType(c).isEmpty()).isPresent()); + add("addBlocked", Category.CLIENT, "Add as Blocked", + () -> onClient((a, c) -> a.addContact(c, ContactType.BLOCKED)), "ADD_FOE") + .enabledWhen(() -> otherClient().filter(c -> contactType(c).isEmpty()).isPresent()); + add("removeContact", Category.CLIENT, "Remove from Contacts", + () -> onClient(ServerTreePanel.Actions::removeContact), "REMOVE_FRIEND") + .enabledWhen(() -> otherClient().filter(c -> contactType(c).isPresent()).isPresent()); + add("kickFromChannel", Category.CLIENT, "Kick Client from Channel", + () -> onOthers(ServerTreePanel.Actions::kickClientsFromChannel), "KICK_FROM_CHANNEL") + .enabledWhen(() -> !otherClients().isEmpty()); + add("kickFromServer", Category.CLIENT, "Kick Client from Server", + () -> onOthers(ServerTreePanel.Actions::kickClientsFromServer), "KICK_FROM_SERVER") + .enabledWhen(() -> !otherClients().isEmpty()); + add("banClient", Category.CLIENT, "Ban Client", () -> onClient(ServerTreePanel.Actions::banClient), "BAN_CLIENT") + .enabledWhen(this::hasOtherClient); + add("moveToOwnChannel", Category.CLIENT, "Move Client to own Channel", + () -> onOthers(ServerTreePanel.Actions::moveClientsToOwnChannel), "MOVE_CLIENT_TO_OWN_CHANNEL") + .enabledWhen(() -> !otherClients().isEmpty()); + add("muteClient", Category.CLIENT, "Mute Client", + () -> onClient(ServerTreePanel.Actions::toggleClientMute), "INPUT_MUTED") + .enabledWhen(() -> otherClient().filter(c -> !locallyMuted(c)).isPresent()); + add("unmuteClient", Category.CLIENT, "Unmute Client", + () -> onClient(ServerTreePanel.Actions::toggleClientMute), "PLAYER_ON") + .enabledWhen(() -> otherClient().filter(this::locallyMuted).isPresent()); + add("changeVolume", Category.CLIENT, "Change Volume", + () -> onClient(ServerTreePanel.Actions::changeClientVolume), "VOLUME") + .enabledWhen(this::hasOtherClient); + add("grantTalkPower", Category.CLIENT, "Grant Talk Power", + () -> onTalkers(false, true), "TALK_POWER_GRANT") + .enabledWhen(() -> permitted(Permissions::canGrantTalkPower) && !talkers(false).isEmpty()); + add("revokeTalkPower", Category.CLIENT, "Revoke Talk Power", + () -> onTalkers(true, false), "TALK_POWER_REVOKE") + .enabledWhen(() -> permitted(Permissions::canGrantTalkPower) && !talkers(true).isEmpty()); + add("changeDescription", Category.CLIENT, "Change Description", + () -> onAnyClient(ServerTreePanel.Actions::changeClientDescription), "EDIT") + .enabledWhen(() -> anyClient().isPresent()); + add("deleteClientAvatar", Category.CLIENT, "Delete User's Avatar", + () -> onClient(ServerTreePanel.Actions::deleteClientAvatar), "DELETE_AVATAR_OTHER") + .enabledWhen(() -> permitted(Permissions::canDeleteOtherAvatars) + && otherClient().filter(c -> !c.avatarFlag.isEmpty()).isPresent()); + add("clientConnectionInfo", Category.CLIENT, "Client Connection Info", + () -> onAnyClient(ServerTreePanel.Actions::showConnectionInfo), "INFO") + .enabledWhen(() -> anyClient().isPresent()); + } + + private void addMisc() { + add("collapseAll", Category.MISC, "Collapse All", () -> collapseAll(true), "CHANNEL_COLLAPSE_ALL") + .enabledWhen(this::connected); + add("collapseSubchannels", Category.MISC, "Collapse Subchannels", () -> collapseBelow(true), + "CHANNEL_COLLAPSE_SUB") + .enabledWhen(this::hasChannel); + add("expandAll", Category.MISC, "Expand All", () -> collapseAll(false), "CHANNEL_EXPAND_ALL") + .enabledWhen(this::connected); + add("expandSubchannels", Category.MISC, "Expand Subchannels", () -> collapseBelow(false), + "CHANNEL_EXPAND_SUB") + .enabledWhen(this::hasChannel); + } + + // ---- what the actions work on ---- + + private boolean connected() { + return commands.connectedTab().isPresent(); + } + + /** Asks the server on screen; false while it is not connected. */ + private boolean is(Predicate question) { + return commands.connectedTab().map(tab -> question.test(tab.session())).orElse(false); + } + + private boolean permitted(Predicate question) { + return is(s -> question.test(s.permissions())); + } + + private Optional currentChannel() { + return commands.connectedTab().map(tab -> tab.session().currentChannel()); + } + + private Optional channel() { + return commands.connectedTab().flatMap(tab -> tab.tree().selectedChannel() + .or(() -> Optional.ofNullable(tab.session().currentChannel()))); + } + + private boolean hasChannel() { + return channel().isPresent(); + } + + private List selectedClients() { + return commands.connectedTab().map(tab -> tab.tree().selectedClients()).orElse(List.of()); + } + + /** The selected clients but us. */ + private List otherClients() { + int self = commands.connectedTab().map(tab -> tab.session().selfClientId()).orElse(-1); + return selectedClients().stream().filter(c -> c.id != self).toList(); + } + + /** The one client selected, us included. */ + private Optional anyClient() { + List clients = selectedClients(); + return clients.size() == 1 ? Optional.of(clients.get(0)) : Optional.empty(); + } + + /** The one client selected, unless that is us. */ + private Optional otherClient() { + List clients = selectedClients(); + List others = otherClients(); + return clients.size() == 1 && others.size() == 1 ? Optional.of(others.get(0)) : Optional.empty(); + } + + private boolean hasOtherClient() { + return otherClient().isPresent(); + } + + /** The selected clients that hold talk power ({@code true}) or lack what the channel needs ({@code false}). */ + private List talkers(boolean talking) { + return commands.connectedTab().map(tab -> tab.tree().selectedClients().stream() + .filter(c -> talking ? c.talker : tab.session().model().lacksTalkPower(c)) + .toList()).orElse(List.of()); + } + + private Optional contactType(ClientEntry client) { + return commands.connectedTab().flatMap(tab -> Optional.ofNullable(tab.treeActions().contactTypeOf(client))); + } + + private boolean locallyMuted(ClientEntry client) { + return commands.connectedTab().map(tab -> tab.treeActions().isClientLocallyMuted(client.id)).orElse(false); + } + + // ---- carrying them out ---- + + private void onTab(Consumer action) { + commands.connectedTab().ifPresent(action); + } + + private void onChannel(BiConsumer action) { + onTab(tab -> channel().ifPresent(c -> action.accept(tab, c))); + } + + private void onClient(BiConsumer action) { + onTab(tab -> otherClient().ifPresent(c -> action.accept(tab.treeActions(), c))); + } + + private void onAnyClient(BiConsumer action) { + onTab(tab -> anyClient().ifPresent(c -> action.accept(tab.treeActions(), c))); + } + + private void onOthers(BiConsumer> action) { + List others = otherClients(); + if (!others.isEmpty()) onTab(tab -> action.accept(tab.treeActions(), others)); + } + + private void onTalkers(boolean talking, boolean grant) { + List clients = talkers(talking); + if (!clients.isEmpty()) onTab(tab -> tab.treeActions().setTalker(clients, grant)); + } + + private void setSubscribed(boolean family, boolean subscribed) { + onChannel((tab, c) -> tab.treeActions().setChannelSubscribed(c, family, subscribed)); + } + + private void subscribeAll(boolean subscribed) { + onTab(tab -> { + List ids = new ArrayList<>(); + for (ChannelNode c : tab.session().model().channelsInTreeOrder()) ids.add(c.id); + tab.session().channels().setSubscribed(ids, subscribed); + }); + } + + private void collapseAll(boolean collapsed) { + onTab(tab -> { + List ids = new ArrayList<>(); + for (ChannelNode c : tab.session().model().channelsInTreeOrder()) ids.add(c.id); + tab.tree().setChannelsCollapsed(ids, collapsed); + }); + } + + /** + * Shuts every channel below the target, leaving the target itself open, or opens the + * target and everything below it. + */ + private void collapseBelow(boolean collapsed) { + onChannel((tab, c) -> { + List ids = c.familyIds(true); + if (collapsed) ids = ids.subList(1, ids.size()); + tab.tree().setChannelsCollapsed(ids, collapsed); + }); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarLayout.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarLayout.java new file mode 100644 index 0000000..ccf6491 --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ToolbarLayout.java @@ -0,0 +1,40 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.config.Settings; + +import java.util.ArrayList; +import java.util.List; + +/** Which {@link ToolbarActions} the main toolbar shows, in order, as kept in {@link Settings#toolbarLayout}. */ +final class ToolbarLayout { + + /** Stands for a separator among the action ids. */ + static final String SEPARATOR = "-"; + + static final List DEFAULT = List.of( + "connect", "disconnect", SEPARATOR, + "activateMicrophone", "muteMicrophone", "muteSpeakers", "away", SEPARATOR, + "options"); + + private ToolbarLayout() { + } + + static List read(Settings settings) { + String saved = settings.toolbarLayout.get().trim(); + if (saved.isEmpty()) return DEFAULT; + List ids = new ArrayList<>(); + for (String id : saved.split(",")) { + if (!id.isBlank()) ids.add(id.trim()); + } + return ids; + } + + /** + * Saves the layout. The default one is stored as nothing, so it follows future defaults; + * an empty toolbar then needs a lone comma to tell it apart. + */ + static void write(Settings settings, List ids) { + settings.toolbarLayout.set(ids.equals(DEFAULT) ? "" : ids.isEmpty() ? "," : String.join(",", ids)); + settings.save(); + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/icons/Icons.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/icons/Icons.java index 12ec8ca..b4e2156 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/icons/Icons.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/icons/Icons.java @@ -63,6 +63,15 @@ public final class Icons { return null; } + /** @return the pack's icon for the first key it has at toolbar size, or {@code null} when it has none */ + public static ImageIcon toolbarOfAny(String... keys) { + for (String key : keys) { + ImageIcon icon = IconTheme.icon(key, large()); + if (icon != null) return icon; + } + return null; + } + /** @return the pack's icon at {@code size} pixels, or {@code null} when it has none */ public static ImageIcon of(String key, int size) { return IconTheme.icon(key, size); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTab.java index acbdf68..006734f 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTab.java @@ -189,6 +189,15 @@ public final class ServerTab { return chatPanel; } + public ServerTreePanel tree() { + return treePanel; + } + + /** What the tree's context menus do, for the toolbar to do the same on the selected rows. */ + public ServerTreePanel.Actions treeActions() { + return treeActions; + } + /** Opens the server's ban list, or brings the already open one forward. */ public void showBanList(BanReasonPresets presets) { showListWindow(BanListDialog.class, () -> new BanListDialog(host, session, settings, presets)); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabConnectionEvents.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabConnectionEvents.java index 121d6d3..0cc6e23 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabConnectionEvents.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabConnectionEvents.java @@ -110,6 +110,7 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { treeActions.renderInfo(); treeActions.refreshGroupsDialog(); host.refreshHostButton(tab); + host.treeChanged(tab); }); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabTreeActions.java index b032494..b828002 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTabTreeActions.java @@ -376,6 +376,7 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { public void onSelectionChanged(Object userObject) { currentSelection = userObject; renderInfo(); + host.treeChanged(tab); if (!session.isConnected()) return; if (userObject instanceof ChannelNode) { ChannelNode ch = (ChannelNode) userObject; diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTreePanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTreePanel.java index dc2eb07..4353b9c 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTreePanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/server/ServerTreePanel.java @@ -33,8 +33,10 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; /** @@ -392,7 +394,7 @@ public final class ServerTreePanel extends JPanel { } /** The selected clients, in tree order; empty when a channel or the server is selected. */ - private List selectedClients() { + public List selectedClients() { List clients = new ArrayList<>(); for (Object obj : selectedUserObjects()) { if (obj instanceof ClientEntry) clients.add((ClientEntry) obj); @@ -400,6 +402,21 @@ public final class ServerTreePanel extends JPanel { return clients; } + /** The selected row's channel, or the channel of the selected client. */ + public Optional selectedChannel() { + Object selected = selectedUserObject(); + if (selected instanceof ChannelNode) return Optional.of((ChannelNode) selected); + if (selected instanceof ClientEntry) return Optional.ofNullable(model.getChannel(((ClientEntry) selected).channelId)); + return Optional.empty(); + } + + /** Opens or shuts these channels. */ + public void setChannelsCollapsed(Collection channelIds, boolean collapsed) { + if (collapsed) collapsedChannels.addAll(channelIds); + else collapsedChannels.removeAll(channelIds); + rebuild(); + } + /** The path of the tree node showing {@code target}, or {@code null}. */ private TreePath pathOf(Object target) { java.util.Enumeration nodes = root.breadthFirstEnumeration();