package com.ts3client.ui; import com.formdev.flatlaf.util.ScaledEmptyBorder; import com.formdev.flatlaf.util.UIScale; import com.ts3client.config.Settings; import com.ts3client.contacts.Contact; import com.ts3client.contacts.ContactStore; import com.ts3client.contacts.ContactType; import com.ts3client.contacts.NicknameDisplay; import com.ts3client.teamspeak.TeamSpeakSettingsDb; import com.ts3client.text.TsLink; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; 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.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.TransferHandler; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicTreeUI; 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.FlowLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The contact list window: the contacts grouped as friends, blocked and neutral on * the left, and on the right all of the selected one's settings — TeamSpeak's * General / Display / Ignore / Whisper pages, in one column rather than as tabs * since each holds only a few options. Every edit is stored as it is made. * *

Clients can be dragged in from the server tree — the drag carries the * client's TS3 link, which names its unique id. */ final class ContactsDialog extends JDialog { private static final DateTimeFormatter SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private static final DateTimeFormatter SEEN_DAY = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final Pattern CLIENT_LINK = Pattern.compile("client://[^\\]\\s]+"); private final ContactStore contacts; private final Settings settings; private final ContactStore.Listener storeListener = () -> SwingUtilities.invokeLater(this::reload); private final DefaultMutableTreeNode root = new DefaultMutableTreeNode(); private final DefaultTreeModel treeModel = new DefaultTreeModel(root); private final JTree tree = new JTree(treeModel); private final DefaultMutableTreeNode friends = new DefaultMutableTreeNode("Friends"); private final DefaultMutableTreeNode blocked = new DefaultMutableTreeNode("Blocked"); private final DefaultMutableTreeNode neutral = new DefaultMutableTreeNode("Neutral"); private final JTextField nicknameField = new JTextField(18); private final JButton nicknameApply = new JButton("Apply"); private final JRadioButton neutralRadio = new JRadioButton("Neutral"); private final JRadioButton blockedRadio = new JRadioButton("Blocked"); private final JRadioButton friendRadio = new JRadioButton("Friend"); private final JTextField phoneticField = new JTextField(18); private final JLabel lastSeenLabel = new JLabel(" "); private final JRadioButton bothRadio = new JRadioButton(NicknameDisplay.BOTH.label()); private final JRadioButton onlyCustomRadio = new JRadioButton(NicknameDisplay.ONLY_CUSTOM.label()); private final JRadioButton onlyNicknameRadio = new JRadioButton(NicknameDisplay.ONLY_NICKNAME.label()); private final JCheckBox automute = new JCheckBox("Mute"); private final JCheckBox ignorePublic = new JCheckBox("Ignore server/channel chat"); private final JCheckBox ignorePrivate = new JCheckBox("Ignore private chat"); private final JCheckBox ignorePokes = new JCheckBox("Ignore Pokes"); private final JCheckBox ignoreAvatar = new JCheckBox("Hide avatar"); private final JCheckBox ignoreAway = new JCheckBox("Hide away message"); private final JCheckBox denyWhisper = new JCheckBox("Deny whisper"); private final JPanel details = new JPanel(new BorderLayout(0, UIScale.scale(8))); /** Set while the fields are being filled from a contact, so that does not count as an edit. */ private boolean filling; ContactsDialog(Frame owner, ContactStore contacts, Settings settings) { super(owner, "Contacts", false); this.contacts = contacts; this.settings = settings; buildTree(); JPanel left = new JPanel(new BorderLayout(0, UIScale.scale(4))); left.setBorder(new ScaledEmptyBorder(8, 8, 8, 4)); JLabel hint = new JLabel("Drag & Drop users here"); hint.setForeground(Theme.chatSystem()); left.add(hint, BorderLayout.NORTH); JScrollPane scroll = new JScrollPane(tree); scroll.setPreferredSize(UIScale.scale(new Dimension(300, 340))); left.add(scroll, BorderLayout.CENTER); details.setBorder(new ScaledEmptyBorder(8, 4, 8, 8)); details.add(buildNicknameRow(), BorderLayout.NORTH); details.add(buildOptions(), BorderLayout.CENTER); JPanel buttons = new JPanel(new BorderLayout()); buttons.setBorder(new ScaledEmptyBorder(0, 8, 8, 8)); JPanel leftButtons = new JPanel(new FlowLayout(FlowLayout.LEFT, UIScale.scale(6), 0)); JButton defaults = new JButton("Set Defaults"); defaults.setToolTipText("Set default display, ignore and hide options"); defaults.addActionListener(e -> new ContactDefaultsDialog(this, settings).setVisible(true)); leftButtons.add(defaults); if (TeamSpeakSettingsDb.locate() != null) { JButton importButton = new JButton("Import from TeamSpeak 3…"); importButton.setToolTipText("Add the contacts of the TeamSpeak 3 client installed on this computer"); importButton.addActionListener(e -> importFromTeamSpeak()); leftButtons.add(importButton); } buttons.add(leftButtons, BorderLayout.WEST); JButton close = new JButton("Close"); close.addActionListener(e -> dispose()); JPanel rightButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0)); rightButtons.add(close); buttons.add(rightButtons, BorderLayout.EAST); getContentPane().setLayout(new BorderLayout()); getContentPane().add(left, BorderLayout.WEST); getContentPane().add(details, BorderLayout.CENTER); getContentPane().add(buttons, BorderLayout.SOUTH); contacts.addListener(storeListener); addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosed(java.awt.event.WindowEvent e) { contacts.removeListener(storeListener); } }); reload(); Dialogs.closeOnEscape(this); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); // Only the list scrolls, so the window never gets shorter than the options column. setMinimumSize(new Dimension(UIScale.scale(620), getHeight())); setLocationRelativeTo(owner); } // ---- tree ---- private void buildTree() { root.add(friends); root.add(blocked); root.add(neutral); tree.setRootVisible(false); tree.setShowsRootHandles(true); // Half the usual nesting, so long names and their dates fit in the narrow list. if (tree.getUI() instanceof BasicTreeUI) { BasicTreeUI ui = (BasicTreeUI) tree.getUI(); ui.setLeftChildIndent(UIScale.scale(4)); ui.setRightChildIndent(UIScale.scale(5)); } tree.setRowHeight(UIScale.scale(20)); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setCellRenderer(new ContactRenderer()); tree.addTreeSelectionListener(e -> showSelected()); tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { maybePopup(e); } @Override public void mouseReleased(MouseEvent e) { maybePopup(e); } }); tree.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "remove"); tree.getActionMap().put("remove", new javax.swing.AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { removeSelected(); } }); tree.setTransferHandler(new DropHandler()); } /** Re-lists the contacts, keeping the selection on the same unique id. */ private void reload() { String selectedUid = selectedContact() == null ? null : selectedContact().uniqueId; for (DefaultMutableTreeNode group : List.of(friends, blocked, neutral)) group.removeAllChildren(); List sorted = new ArrayList<>(contacts.all()); sorted.sort(Comparator.comparing((Contact c) -> c.nickname, String.CASE_INSENSITIVE_ORDER) .thenComparing(c -> c.uniqueId)); for (Contact c : sorted) groupOf(c.type).add(new DefaultMutableTreeNode(c)); treeModel.reload(); for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); if (selectedUid != null) select(selectedUid); else showSelected(); } private DefaultMutableTreeNode groupOf(ContactType type) { switch (type) { case FRIEND: return friends; case BLOCKED: return blocked; default: return neutral; } } /** Selects the contact with a unique id, if it is on the list. */ void select(String uniqueId) { java.util.Enumeration nodes = root.depthFirstEnumeration(); while (nodes.hasMoreElements()) { DefaultMutableTreeNode n = (DefaultMutableTreeNode) nodes.nextElement(); if (n.getUserObject() instanceof Contact && ((Contact) n.getUserObject()).uniqueId.equals(uniqueId)) { TreePath path = new TreePath(n.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); return; } } } private Contact selectedContact() { TreePath path = tree.getSelectionPath(); if (path == null) return null; Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); return obj instanceof Contact ? (Contact) obj : null; } private void maybePopup(MouseEvent e) { if (!e.isPopupTrigger()) return; TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path == null) return; tree.setSelectionPath(path); Contact contact = selectedContact(); if (contact == null) return; JPopupMenu menu = new JPopupMenu(); for (ContactType type : new ContactType[]{ContactType.FRIEND, ContactType.BLOCKED, ContactType.NEUTRAL}) { JMenuItem item = new javax.swing.JRadioButtonMenuItem(type.label(), type == contact.type); item.addActionListener(a -> edit(c -> c.type = type)); menu.add(item); } menu.addSeparator(); JMenuItem remove = new JMenuItem("Remove", Icons.of("DELETE")); remove.addActionListener(a -> removeSelected()); menu.add(remove); JMenuItem applyDefaults = new JMenuItem("Apply Defaults"); applyDefaults.addActionListener(a -> edit(c -> c.applyDefaults(settings.contactDefaults.of(c.type)))); menu.add(applyDefaults); menu.addSeparator(); JMenuItem copyUid = new JMenuItem("Copy Unique ID to Clipboard", Icons.of("COPY")); copyUid.addActionListener(a -> Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(new StringSelection(contact.uniqueId), null)); menu.add(copyUid); menu.show(tree, e.getX(), e.getY()); } private void removeSelected() { Contact contact = selectedContact(); if (contact == null) return; int answer = JOptionPane.showConfirmDialog(this, "Do you really want to delete contact " + contact.nickname + "?", "Remove Contact", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (answer == JOptionPane.YES_OPTION) contacts.remove(contact.uniqueId); } private void importFromTeamSpeak() { File db = TeamSpeakSettingsDb.locate(); if (db == null) return; try { List imported = TeamSpeakSettingsDb.readContacts(db); int added = contacts.merge(imported); JOptionPane.showMessageDialog(this, imported.size() + " contact(s) read from " + db + "\n" + added + " new, " + (imported.size() - added) + " updated.", "Import from TeamSpeak 3", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Could not read " + db + ":\n" + e.getMessage(), "Import from TeamSpeak 3", JOptionPane.ERROR_MESSAGE); } } // ---- details ---- /** The names, each label on its own line above its field. */ private JComponent buildNicknameRow() { JPanel row = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = UIScale.scale(new Insets(2, 2, 2, 2)); c.anchor = GridBagConstraints.WEST; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; row.add(new JLabel("Custom Nickname:"), c); c.gridy = 1; c.gridwidth = 1; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; nicknameField.setToolTipText("Enter custom nickname"); nicknameField.addActionListener(e -> applyNickname()); row.add(nicknameField, c); c.gridx = 1; c.weightx = 0; c.fill = GridBagConstraints.NONE; nicknameApply.setToolTipText("Apply nickname change"); nicknameApply.addActionListener(e -> applyNickname()); row.add(nicknameApply, c); c.gridx = 0; c.gridy = 2; c.gridwidth = 2; row.add(new JLabel("Phonetic Nickname:"), c); c.gridy = 3; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; row.add(phoneticField, c); c.gridy = 4; row.add(lastSeenLabel, c); return row; } /** Every option at once, one short group under the other. */ private JComponent buildOptions() { JComponent contact = group("Contact", radioGroup(neutralRadio, blockedRadio, friendRadio)); neutralRadio.setToolTipText("Mark as neutral"); blockedRadio.setToolTipText("Mark as blocked"); friendRadio.setToolTipText("Mark as friend"); phoneticField.setToolTipText("Client nickname written as phonemes (optional)"); neutralRadio.addActionListener(e -> edit(c -> c.type = ContactType.NEUTRAL)); blockedRadio.addActionListener(e -> edit(c -> c.type = ContactType.BLOCKED)); friendRadio.addActionListener(e -> edit(c -> c.type = ContactType.FRIEND)); phoneticField.addActionListener(e -> applyPhonetic()); phoneticField.addFocusListener(new java.awt.event.FocusAdapter() { @Override public void focusLost(java.awt.event.FocusEvent e) { applyPhonetic(); } }); JComponent display = group("Display", radioGroup(bothRadio, onlyCustomRadio, onlyNicknameRadio)); bothRadio.setToolTipText("Show custom name and nickname"); onlyCustomRadio.setToolTipText("Show only custom name"); onlyNicknameRadio.setToolTipText("Show nickname only"); bothRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.BOTH)); onlyCustomRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_CUSTOM)); onlyNicknameRadio.addActionListener(e -> edit(c -> c.nicknameDisplay = NicknameDisplay.ONLY_NICKNAME)); JComponent ignore = group("Ignore", automute, ignorePublic, ignorePrivate, ignorePokes, ignoreAvatar, ignoreAway, denyWhisper); automute.setToolTipText("Automatically mute this person"); ignorePublic.setToolTipText("Ignore messages this person sends to the server or in channels"); ignorePrivate.setToolTipText("Ignore private chat by this person"); ignorePokes.setToolTipText("Ignore pokes this person sends you"); ignoreAvatar.setToolTipText("Do not download this person's avatar"); ignoreAway.setToolTipText("Ignore this person's away messages"); automute.addActionListener(e -> edit(c -> c.automute = automute.isSelected())); ignorePublic.addActionListener(e -> edit(c -> c.ignorePublicMessages = ignorePublic.isSelected())); ignorePrivate.addActionListener(e -> edit(c -> c.ignorePrivateMessages = ignorePrivate.isSelected())); ignorePokes.addActionListener(e -> edit(c -> c.ignorePokes = ignorePokes.isSelected())); ignoreAvatar.addActionListener(e -> edit(c -> c.ignoreAvatar = ignoreAvatar.isSelected())); ignoreAway.addActionListener(e -> edit(c -> c.ignoreAwayMessage = ignoreAway.isSelected())); denyWhisper.setToolTipText("This contact is always denied to whisper to you"); denyWhisper.addActionListener(e -> edit(c -> c.whisperAllowed = !denyWhisper.isSelected())); return column(contact, display, ignore); } private static JPanel column(JComponent... groups) { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); for (JComponent g : groups) { g.setAlignmentX(Component.LEFT_ALIGNMENT); g.setMaximumSize(new Dimension(Integer.MAX_VALUE, g.getPreferredSize().height)); p.add(g); p.add(Box.createVerticalStrut(UIScale.scale(6))); } p.add(Box.createVerticalGlue()); return p; } private static JPanel group(String title, JComponent... rows) { JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.setBorder(BorderFactory.createTitledBorder(title)); for (JComponent row : rows) { row.setAlignmentX(Component.LEFT_ALIGNMENT); p.add(row); } return p; } private static JPanel radioGroup(JRadioButton... buttons) { ButtonGroup group = new ButtonGroup(); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); for (JRadioButton b : buttons) { group.add(b); b.setAlignmentX(Component.LEFT_ALIGNMENT); p.add(b); } return p; } /** Fills the right-hand side from the selected contact, or greys it out. */ private void showSelected() { Contact c = selectedContact(); filling = true; try { setDetailsEnabled(details, c != null); if (c == null) { nicknameField.setText(""); phoneticField.setText(""); lastSeenLabel.setText(" "); return; } nicknameField.setText(c.nickname); phoneticField.setText(c.phoneticNickname); lastSeenLabel.setText(lastSeen(c)); (c.type == ContactType.FRIEND ? friendRadio : c.type == ContactType.BLOCKED ? blockedRadio : neutralRadio) .setSelected(true); (c.nicknameDisplay == NicknameDisplay.ONLY_CUSTOM ? onlyCustomRadio : c.nicknameDisplay == NicknameDisplay.ONLY_NICKNAME ? onlyNicknameRadio : bothRadio) .setSelected(true); automute.setSelected(c.automute); ignorePublic.setSelected(c.ignorePublicMessages); ignorePrivate.setSelected(c.ignorePrivateMessages); ignorePokes.setSelected(c.ignorePokes); ignoreAvatar.setSelected(c.ignoreAvatar); ignoreAway.setSelected(c.ignoreAwayMessage); denyWhisper.setSelected(!c.whisperAllowed); } finally { filling = false; } } private static String lastSeen(Contact c) { if (c.lastSeen == null) return "Never seen"; String where = c.lastSeenServerName.isEmpty() ? c.lastSeenServerAddress : c.lastSeenServerName; return "Last seen " + SEEN.format(c.lastSeen) + (where.isEmpty() ? "" : " on " + where); } private static void setDetailsEnabled(Component component, boolean enabled) { component.setEnabled(enabled); if (component instanceof java.awt.Container) { for (Component child : ((java.awt.Container) component).getComponents()) { setDetailsEnabled(child, enabled); } } } /** Changes the selected contact and stores it; the store's change notice re-lists the tree. */ private void edit(Consumer change) { if (filling) return; Contact c = selectedContact(); if (c == null) return; change.accept(c); contacts.put(c); } private void applyNickname() { String name = nicknameField.getText().trim(); Contact c = selectedContact(); if (c == null || name.isEmpty() || name.equals(c.nickname)) return; edit(contact -> contact.nickname = name); } private void applyPhonetic() { String name = phoneticField.getText().trim(); Contact c = selectedContact(); if (c == null || name.equals(c.phoneticNickname)) return; edit(contact -> contact.phoneticNickname = name); } // ---- drop target ---- /** Accepts clients dragged out of a server tree, whose transfer text is their TS3 link. */ private final class DropHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { return support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override public boolean importData(TransferSupport support) { String text; try { text = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor); } catch (Exception e) { return false; } boolean added = false; Matcher m = CLIENT_LINK.matcher(text); while (m.find()) { TsLink.Ref ref = TsLink.parse(m.group()); if (ref == null || !ref.client || ref.uniqueId.isEmpty()) continue; if (contacts.find(ref.uniqueId) == null) { contacts.add(ref.uniqueId, ref.name, ContactType.NEUTRAL, settings.contactDefaults); } select(ref.uniqueId); added = true; } return added; } } // ---- rendering ---- private static final class ContactRenderer extends DefaultTreeCellRenderer { private final Border margin = getBorder(); /** Keeps a group's name clear of its expand arrow, which the tight nesting brings close. */ private final Border groupMargin = BorderFactory.createCompoundBorder(margin, new ScaledEmptyBorder(0, 4, 0, 0)); @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 obj = ((DefaultMutableTreeNode) value).getUserObject(); if (obj instanceof Contact) { Contact c = (Contact) obj; setText("" + esc(c.nickname) + "  " + (c.lastSeen == null ? "Never" : SEEN_DAY.format(c.lastSeen)) + ""); setFont(Theme.uiFont()); setBorder(margin); } else { setText(String.valueOf(obj)); setFont(Theme.uiBold()); setBorder(groupMargin); } setIcon(null); return this; } private static String esc(String s) { return s.replace("&", "&").replace("<", "<").replace(">", ">"); } private static String hex(java.awt.Color c) { return String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()); } } }