diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt index cfdb276..f5460de 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -191,8 +191,11 @@ class ServerController internal constructor( val canMoveClients: Boolean get() = session.canMoveClients() - fun moveClient(clientId: Int, channelId: Int) { - if (session.isConnected) conn.moveClient(clientId, channelId, null) + /** The channel kicked clients go back to; 0 until the server named it. */ + val defaultChannelId: Int get() = conn.model.defaultChannelId() + + fun moveClients(clientIds: Collection, channelId: Int) { + if (session.isConnected) conn.moveClients(clientIds, channelId) } fun poke(clientId: Int, message: String) { @@ -295,12 +298,12 @@ class ServerController internal constructor( /** The longest ban we may hand out in seconds; 0 or -1 for no limit. */ val maxBanSeconds: Long get() = conn.model.maxBanSeconds() - fun kickFromChannel(clientId: Int, reason: String) { - if (session.isConnected) conn.kickFromChannel(clientId, reason) + fun kickFromChannel(clientIds: Collection, reason: String) { + if (session.isConnected) conn.kickFromChannel(clientIds, reason) } - fun kickFromServer(clientId: Int, reason: String) { - if (session.isConnected) conn.kickFromServer(clientId, reason) + fun kickFromServer(clientIds: Collection, reason: String) { + if (session.isConnected) conn.kickFromServer(clientIds, reason) } /** Bans a client for [seconds], or for good with 0. */ diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt index 538746e..edfca66 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ChannelTree.kt @@ -153,6 +153,10 @@ fun ChannelTree( listState: LazyListState = rememberLazyListState(), /** Brings our own client into view; its row may sit in folded channels. */ onShowSelf: () -> Unit = {}, + /** Clients picked to be moved or kicked together. */ + selected: Set = emptySet(), + /** Picks a client into [selected]; null when there is nothing to do with several. */ + onClientLongPress: ((ClientItem) -> Unit)? = null, ) { val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) } var flashing by remember { mutableStateOf(null) } @@ -201,16 +205,17 @@ fun ChannelTree( } items(rows, key = { it.key }) { row -> val background = rowBackground( - when (row.ref) { - flashing -> FLASH - foundCurrent -> findCurrentColor() - in found -> findMatchColor() + when { + row.ref == flashing -> FLASH + !row.ref.channel && row.ref.id in selected -> MaterialTheme.colorScheme.secondaryContainer + row.ref == foundCurrent -> findCurrentColor() + row.ref in found -> findMatchColor() else -> Color.Transparent }, ) when (row) { is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap) - is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient) + is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient, onClientLongPress) } } } @@ -239,6 +244,7 @@ private fun RowLayout( /** The colour under [background], which a flash or find match goes over. */ tint: Color = Color.Transparent, onDoubleClick: (() -> Unit)? = null, + onLongClick: (() -> Unit)? = null, content: @Composable RowScope.() -> Unit, ) { Row( @@ -247,7 +253,7 @@ private fun RowLayout( .background(tint) .background(background) .height(ROW) - .then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier) + .then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onLongClick = onLongClick, onClick = onClick) else Modifier) .padding(start = 4.dp + INDENT * depth, end = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), @@ -315,9 +321,16 @@ private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) { } @Composable -private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) { +private fun ClientRow( + row: TreeRow.Client, + countryFlags: Boolean, + background: Color, + onClient: (ClientItem) -> Unit, + onLongPress: ((ClientItem) -> Unit)?, +) { val client = row.client - RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) { + RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background), + onLongClick = onLongPress?.let { { it(client) } }) { Spacer(Modifier.width(ICON + 4.dp)) StatusIcon(client.status) Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) { diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt index 9180a0a..dd7d8a9 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/Moderation.kt @@ -211,7 +211,7 @@ fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> onDismiss = { kick = null }, ) { reason -> kick = null - if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason) + if (fromServer) server.kickFromServer(listOf(client.id), reason) else server.kickFromChannel(listOf(client.id), reason) onDone() } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt index d971bf2..e60e5e8 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/ServerScreen.kt @@ -22,6 +22,7 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowDropDown +import androidx.compose.material.icons.filled.Close import androidx.compose.material3.AlertDialog import androidx.compose.material3.Badge import androidx.compose.material3.BadgedBox @@ -161,8 +162,23 @@ fun ServerScreen( /** What is being added to a whisper list, while the list is picked: its name and how to add it. */ var toWhisperList by remember { mutableStateOf Unit>?>(null) } var connectionInfo by rememberSaveable { mutableStateOf(null) } - /** The client to move, while a channel for them is being picked. */ - var moving by remember { mutableStateOf(null) } + /** The clients to move, while a channel for them is being picked. */ + var moving by remember { mutableStateOf?>(null) } + /** Clients picked by a long press, to be moved or kicked together; those who left fall out. */ + var picked by remember { mutableStateOf(emptySet()) } + val selection = remember(picked, tree) { picked.filterTo(LinkedHashSet()) { tree.client(it) != null } } + /** Whether the selection is being kicked: from the server, or from their channels. */ + var kickingSelection by remember { mutableStateOf(null) } + /** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */ + val kickable = { fromServer: Boolean -> + val inDefault = if (fromServer) emptySet() else tree.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet() + selection - state.selfClientId - inDefault + } + val moveTo = { channelId: Int, clients: Set -> + server.moveClients(clients, channelId) + moving = null + picked = emptySet() + } val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle() val chatRequest by server.chatRequest.collectAsStateWithLifecycle() @@ -261,6 +277,7 @@ fun ServerScreen( BackHandler(showChat) { showChat = false } BackHandler(moving != null && !showChat) { moving = null } + BackHandler(moving == null && selection.isNotEmpty() && !showChat) { picked = emptySet() } BackHandler(find.open) { find.open = false } Scaffold( @@ -304,13 +321,24 @@ fun ServerScreen( ) { padding -> Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) { if (!showChat) { - moving?.let { id -> - val client = tree.client(id) - if (client == null) { - LaunchedEffect(id) { moving = null } + val movingNow = moving + if (movingNow != null) { + val clients = movingNow.mapNotNull { tree.client(it) } + if (clients.isEmpty()) { + LaunchedEffect(movingNow) { moving = null } } else { - MovePrompt(client.name) { moving = null } + MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { moving = null } } + } else if (selection.isNotEmpty()) { + val outside = tree.channel(state.channelId)?.clients.orEmpty().map { it.id }.let { selection - it.toSet() } + SelectionBar( + count = selection.size, + onMove = if (server.canMoveClients) ({ moving = selection }) else null, + onMoveHere = if (server.canMoveClients && outside.isNotEmpty()) ({ moveTo(state.channelId, outside) }) else null, + onKickChannel = if (server.canKickFromChannel && kickable(false).isNotEmpty()) ({ kickingSelection = false }) else null, + onKickServer = if (server.canKickFromServer && kickable(true).isNotEmpty()) ({ kickingSelection = true }) else null, + onClear = { picked = emptySet() }, + ) } ChannelTree( serverName = state.title, @@ -323,22 +351,28 @@ fun ServerScreen( else filterCollapsed += it.id }, onChannel = { channel -> - val client = moving + val clients = moving when { channel.spacer != null -> {} - client != null -> { server.moveClient(client, channel.id); moving = null } + clients != null -> moveTo(channel.id, clients) else -> channelSheet = channel.id } }, onChannelDoubleTap = { channel -> - val client = moving + val clients = moving when { - client != null -> { server.moveClient(client, channel.id); moving = null } + clients != null -> moveTo(channel.id, clients) channel.id == state.channelId -> {} else -> join(channel) } }, - onClient = { clientSheet = it.id; clientSheetFromTree = true }, + onClient = { + when { + selection.isEmpty() -> { clientSheet = it.id; clientSheetFromTree = true } + it.id in selection -> picked = selection - it.id + else -> picked = selection + it.id + } + }, onServer = { serverSheet = true }, modifier = Modifier.weight(1f), reveal = reveal, @@ -346,6 +380,10 @@ fun ServerScreen( found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }, foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, listState = treeList, + selected = selection, + onClientLongPress = if (server.canMoveClients || server.canKickFromChannel || server.canKickFromServer) { + { picked = selection + it.id } + } else null, onShowSelf = { val path = tree.pathTo(state.selfClientId).orEmpty() if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) @@ -403,9 +441,9 @@ fun ServerScreen( clientSheet = null server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } }) else null, - onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null, + onMove = if (server.canMoveClients) ({ clientSheet = null; moving = setOf(id) }) else null, onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) { - { server.moveClient(id, state.channelId); clientSheet = null } + { server.moveClients(listOf(id), state.channelId); clientSheet = null } } else null, onFindInTree = if (clientSheetFromTree) null else ({ clientSheet = null @@ -443,6 +481,18 @@ fun ServerScreen( ) } } + kickingSelection?.let { fromServer -> + val others = kickable(fromServer) + val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients" + KickPrompt( + if (fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?", + onDismiss = { kickingSelection = null }, + ) { reason -> + kickingSelection = null + if (fromServer) server.kickFromServer(others, reason) else server.kickFromChannel(others, reason) + picked = emptySet() + } + } joinLocked?.let { id -> TextPrompt( title = "Join ${tree.channel(id)?.name.orEmpty()}", @@ -504,6 +554,28 @@ private const val MAX_CHAT_MATCHES = 5000 private fun next(at: Int, delta: Int, size: Int): Int = if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size) +/** How many clients are picked in the tree, and what may be done with them at once. */ +@Composable +private fun SelectionBar( + count: Int, + onMove: (() -> Unit)?, + onMoveHere: (() -> Unit)?, + onKickChannel: (() -> Unit)?, + onKickServer: (() -> Unit)?, + onClear: () -> Unit, +) { + Surface(color = MaterialTheme.colorScheme.secondaryContainer) { + Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") } + Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium) + onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } } + onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } } + onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } } + onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } } + } + } +} + /** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */ @Composable private fun MovePrompt(name: String, onCancel: () -> Unit) { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java index 1e7c81e..99eb2f2 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ConnectionEventHandler.java @@ -452,8 +452,11 @@ final class ConnectionEventHandler implements TS3Listener { } /** The properties a channel event carries that the model keeps; each only when present. */ - private static void applyChannelProperties(ChannelNode ch, BaseEvent e) { + private void applyChannelProperties(ChannelNode ch, BaseEvent e) { if (has(e, "channel_name")) ch.name = e.get("channel_name"); + if (has(e, "channel_flag_default") && e.getBoolean("channel_flag_default")) { + conn.getModel().setDefaultChannel(ch.id); + } // An emptied topic arrives as a bare key, which has() would skip. if (reported(e, "channel_topic")) ch.topic = TeamspeakConnection.orEmpty(e.get("channel_topic")); if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id"); diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java index a72b6a1..7914168 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ServerModel.java @@ -42,6 +42,8 @@ public final class ServerModel { private final Map serverProperties = new HashMap<>(); /** The channel group everyone starts in, e.g. "Guest" — not worth offering to (re)assign. */ private int defaultChannelGroupId; + /** The channel new clients land in, and kicked ones go back to; 0 until the server names it. */ + private int defaultChannelId; public synchronized void clear() { channels.clear(); @@ -55,6 +57,7 @@ public final class ServerModel { unreportedValues.clear(); serverProperties.clear(); defaultChannelGroupId = 0; + defaultChannelId = 0; } // ---- groups ---- @@ -352,6 +355,15 @@ public final class ServerModel { return c; } + public synchronized int defaultChannelId() { + return defaultChannelId; + } + + /** The server announces only the new default channel, so this replaces the old one. */ + public synchronized void setDefaultChannel(int id) { + defaultChannelId = id; + } + public synchronized ChannelNode getChannel(int id) { return channels.get(id); } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java index 2bb1833..16d4e5e 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -752,20 +752,66 @@ public final class TeamspeakConnection implements TS3Listener { (password == null || password.isEmpty()) ? null : password)); } + /** + * Moves several clients (ourselves among them, if wanted) into a channel in one piped + * command. Clients already in it are left out, which the server would refuse. + */ + public void moveClients(Collection clientIds, int channelId) { + List rows = new ArrayList<>(clientIds.size()); + for (int id : clientIds) { + ClientEntry client = model.getClient(id); + if (client != null && client.channelId == channelId) continue; + rows.add(new SingleCommand("clientmove", ProtocolRole.CLIENT, + new CommandSingleParameter("clid", Integer.toString(id)))); + } + if (rows.isEmpty()) return; + act(rows.size() == 1 ? "Could not move client: " : "Could not move clients: ", sock -> { + MultiCommand cmd = new MultiCommand("clientmove", ProtocolRole.CLIENT, rows); + cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); + sock.executeCommand(cmd).complete(); + }); + } + /** Kicks a client out of its channel, back into the server's default one. */ public void kickFromChannel(int clientId, String reason) { - kick(clientId, REASON_KICK_CHANNEL, reason, "Could not kick client from the channel: "); + kickFromChannel(List.of(clientId), reason); + } + + /** + * Kicks clients out of their channels in one command; we are never among them, nor are + * clients already in the default channel, as the server would refuse the whole command. + */ + public void kickFromChannel(Collection clientIds, String reason) { + int defaultChannel = model.defaultChannelId(); + List ids = new ArrayList<>(clientIds.size()); + for (int id : clientIds) { + ClientEntry client = model.getClient(id); + if (client == null || client.channelId != defaultChannel) ids.add(id); + } + kick(ids, REASON_KICK_CHANNEL, reason, "channel"); } /** Kicks a client off the server entirely. */ public void kickFromServer(int clientId, String reason) { - kick(clientId, REASON_KICK_SERVER, reason, "Could not kick client from the server: "); + kickFromServer(List.of(clientId), reason); } - private void kick(int clientId, int reasonId, String reason, String errorPrefix) { + /** Kicks clients off the server in one command; we are never among them. */ + public void kickFromServer(Collection clientIds, String reason) { + kick(clientIds, REASON_KICK_SERVER, reason, "server"); + } + + private void kick(Collection clientIds, int reasonId, String reason, String from) { + List rows = new ArrayList<>(clientIds.size()); + for (int id : clientIds) { + if (id == selfClientId) continue; + rows.add(new SingleCommand("clientkick", ProtocolRole.CLIENT, + new CommandSingleParameter("clid", Integer.toString(id)))); + } + if (rows.isEmpty()) return; + String errorPrefix = "Could not kick " + (rows.size() == 1 ? "client" : "clients") + " from the " + from + ": "; act(errorPrefix, sock -> { - SingleCommand cmd = new SingleCommand("clientkick", ProtocolRole.CLIENT); - cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId))); + MultiCommand cmd = new MultiCommand("clientkick", ProtocolRole.CLIENT, rows); cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId))); if (reason != null && !reason.isEmpty()) { cmd.add(new CommandSingleParameter("reasonmsg", reason)); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java index f455c77..8ac0a51 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientMenu.java @@ -42,10 +42,10 @@ final class ClientMenu { menu.add(complain); menu.addSeparator(); JMenuItem kickChannel = new JMenuItem("Kick Client from Channel", Icons.of("KICK_FROM_CHANNEL")); - kickChannel.addActionListener(a -> actions.kickClientFromChannel(client)); + kickChannel.addActionListener(a -> actions.kickClientsFromChannel(List.of(client))); menu.add(kickChannel); JMenuItem kickServer = new JMenuItem("Kick Client from Server", Icons.of("KICK_FROM_SERVER")); - kickServer.addActionListener(a -> actions.kickClientFromServer(client)); + kickServer.addActionListener(a -> actions.kickClientsFromServer(List.of(client))); menu.add(kickServer); JMenuItem ban = new JMenuItem("Ban Client", Icons.of("BAN_CLIENT")); ban.addActionListener(a -> actions.banClient(client)); @@ -93,12 +93,34 @@ final class ClientMenu { joinChannel.addActionListener(a -> actions.joinChannel(client.channelId)); menu.add(joinChannel); JMenuItem moveHere = new JMenuItem("Move Client to own Channel", Icons.of("MOVE_CLIENT_TO_OWN_CHANNEL")); - moveHere.addActionListener(a -> actions.moveClientToOwnChannel(client)); + moveHere.addActionListener(a -> actions.moveClientsToOwnChannel(List.of(client))); menu.add(moveHere); } return menu; } + /** The context menu for several clients selected together; we may be among them. */ + static JPopupMenu buildForMany(List clients, int selfId, ServerModel model, + ServerTreePanel.Actions actions) { + JPopupMenu menu = new JPopupMenu(); + boolean others = clients.stream().anyMatch(c -> c.id != selfId); + int defaultChannel = model.defaultChannelId(); + JMenuItem kickChannel = new JMenuItem("Kick Clients from Channel", Icons.of("KICK_FROM_CHANNEL")); + kickChannel.setEnabled(clients.stream().anyMatch(c -> c.id != selfId && c.channelId != defaultChannel)); + kickChannel.addActionListener(a -> actions.kickClientsFromChannel(clients)); + menu.add(kickChannel); + JMenuItem kickServer = new JMenuItem("Kick Clients from Server", Icons.of("KICK_FROM_SERVER")); + kickServer.setEnabled(others); + kickServer.addActionListener(a -> actions.kickClientsFromServer(clients)); + menu.add(kickServer); + menu.addSeparator(); + JMenuItem moveHere = new JMenuItem("Move Clients to own Channel", Icons.of("MOVE_CLIENT_TO_OWN_CHANNEL")); + moveHere.setEnabled(others); + moveHere.addActionListener(a -> actions.moveClientsToOwnChannel(clients)); + menu.add(moveHere); + return menu; + } + /** * The contact entries, as TeamSpeak offers them: a client not on the list can be * added as a friend or blocked; one on it can be edited or removed. diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientSelectionModel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientSelectionModel.java new file mode 100644 index 0000000..5fa557f --- /dev/null +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientSelectionModel.java @@ -0,0 +1,54 @@ +package eu.lixko.ts3j.client.ui; + +import eu.lixko.ts3j.client.net.ClientEntry; + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.TreePath; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * The server tree's selection: one row of any kind, or several clients, for moving or + * kicking them together. Ctrl adds a client to clients already selected, and a Shift range + * keeps the clients in it; anything else that would mix kinds selects just the new row. + */ +final class ClientSelectionModel extends DefaultTreeSelectionModel { + + @Override + public void setSelectionPaths(TreePath[] paths) { + super.setSelectionPaths(paths == null || paths.length < 2 ? paths : clientsOrLast(paths)); + } + + @Override + public void addSelectionPaths(TreePath[] paths) { + TreePath[] current = getSelectionPaths(); + if (paths == null || paths.length == 0 || current == null) { + setSelectionPaths(paths); + return; + } + if (allClients(current) && allClients(paths)) { + super.addSelectionPaths(paths); + } else { + setSelectionPaths(new TreePath[]{paths[paths.length - 1]}); + } + } + + /** The client rows among {@code paths}, or the last path alone when there are none. */ + private static TreePath[] clientsOrLast(TreePath[] paths) { + List clients = new ArrayList<>(paths.length); + for (TreePath path : paths) { + if (isClient(path)) clients.add(path); + } + return clients.isEmpty() ? new TreePath[]{paths[paths.length - 1]} : clients.toArray(new TreePath[0]); + } + + private static boolean allClients(TreePath[] paths) { + return Arrays.stream(paths).allMatch(ClientSelectionModel::isClient); + } + + static boolean isClient(TreePath path) { + return ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject() instanceof ClientEntry; + } +} diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java index 573f5c5..1e58e10 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabTreeActions.java @@ -12,6 +12,8 @@ import eu.lixko.ts3j.client.text.TsLink; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import java.awt.Component; +import java.util.ArrayList; +import java.util.List; /** * Context-menu and drag/drop actions for one server's tree, plus tracking which @@ -114,13 +116,8 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { } @Override - public void moveClientToChannel(ClientEntry client, ChannelNode target) { - if (!conn.isConnected()) return; - if (client.id == conn.getSelfClientId()) { - conn.joinChannel(target.id, null); - } else { - conn.moveClient(client.id, target.id, null); - } + public void moveClientsToChannel(List clients, ChannelNode target) { + if (conn.isConnected()) conn.moveClients(ids(clients), target.id); } @Override @@ -149,21 +146,29 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { } @Override - public void kickClientFromChannel(ClientEntry client) { - String reason = kickReason("Kick Client from Channel", client); - if (reason != null) conn.kickFromChannel(client.id, reason); + public void kickClientsFromChannel(List clients) { + String reason = kickReason("Channel", clients); + if (reason != null) conn.kickFromChannel(ids(clients), reason); } @Override - public void kickClientFromServer(ClientEntry client) { - String reason = kickReason("Kick Client from Server", client); - if (reason != null) conn.kickFromServer(client.id, reason); + public void kickClientsFromServer(List clients) { + String reason = kickReason("Server", clients); + if (reason != null) conn.kickFromServer(ids(clients), reason); } - private String kickReason(String title, ClientEntry client) { + private String kickReason(String from, List clients) { if (!conn.isConnected()) return null; - return ReasonDialog.prompt(host, title, "Reason for kicking " + client.nickname + ":", - TeamspeakConnection.KICK_REASON_LIMIT); + boolean one = clients.size() == 1; + String whom = one ? clients.get(0).nickname : clients.size() + " clients"; + return ReasonDialog.prompt(host, "Kick " + (one ? "Client" : "Clients") + " from " + from, + "Reason for kicking " + whom + ":", TeamspeakConnection.KICK_REASON_LIMIT); + } + + private static List ids(List clients) { + List ids = new ArrayList<>(clients.size()); + for (ClientEntry client : clients) ids.add(client.id); + return ids; } @Override @@ -195,10 +200,10 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions { } @Override - public void moveClientToOwnChannel(ClientEntry client) { - if (!conn.isConnected() || client.id == conn.getSelfClientId()) return; + public void moveClientsToOwnChannel(List clients) { + if (!conn.isConnected()) return; ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); - if (self != null) conn.moveClient(client.id, self.channelId, null); + if (self != null) conn.moveClients(ids(clients), self.channelId); } @Override diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java index 1d9ef26..b837bf1 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeDragAndDrop.java @@ -14,11 +14,16 @@ import javax.swing.tree.TreePath; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.StringJoiner; import java.util.function.Function; /** - * Drag-and-drop for the {@link ServerTreePanel} tree: dragging a client onto a - * channel moves it there, dragging a channel reorders/reparents it, and dropping + * Drag-and-drop for the {@link ServerTreePanel} tree: dragging clients onto a + * channel moves them there, dragging a channel reorders/reparents it, and dropping * either outside the tree yields its TS3 link BBCode, which the chat input accepts * as plain text. */ @@ -52,10 +57,10 @@ final class ServerTreeDragAndDrop { } /** - * The channel a dragged client would land in, or {@code null} if the drop makes - * no sense (outside a channel, or the channel the client is already in). + * The channel dragged clients would land in, or {@code null} if the drop makes + * no sense (outside a channel, or the channel all of them are already in). */ - private ChannelNode resolveClientDrop(JTree.DropLocation loc, ClientEntry dragged) { + private ChannelNode resolveClientDrop(JTree.DropLocation loc, List dragged) { DefaultMutableTreeNode target = nodeOf(loc.getPath()); if (target == null) return null; Object obj = target.getUserObject(); @@ -66,8 +71,8 @@ final class ServerTreeDragAndDrop { channel = model.getChannel(((ClientEntry) obj).channelId); } if (channel == null || Spacers.isSpacer(channel.name)) return null; - if (channel.id == dragged.channelId) return null; - return channel; + int channelId = channel.id; + return dragged.stream().allMatch(c -> c.channelId == channelId) ? null : channel; } /** @@ -131,12 +136,19 @@ final class ServerTreeDragAndDrop { @Override protected Transferable createTransferable(JComponent c) { - TreePath path = tree.getSelectionPath(); - if (path == null) return null; - Object obj = nodeOf(path).getUserObject(); + TreePath[] paths = tree.getSelectionPaths(); + if (paths == null) return null; + Arrays.sort(paths, Comparator.comparingInt(tree::getRowForPath)); + Object obj = nodeOf(paths[0]).getUserObject(); if (obj instanceof ClientEntry) { - ClientEntry cl = (ClientEntry) obj; - return new NodeTransferable(cl, TsLink.clientBBCode(cl.id, cl.uniqueId, cl.nickname)); + List clients = new ArrayList<>(paths.length); + StringJoiner links = new StringJoiner(" "); + for (TreePath path : paths) { + ClientEntry cl = (ClientEntry) nodeOf(path).getUserObject(); + clients.add(cl); + links.add(TsLink.clientBBCode(cl.id, cl.uniqueId, cl.nickname)); + } + return new NodeTransferable(new DraggedClients(clients), links.toString()); } if (obj instanceof ChannelNode) { ChannelNode ch = (ChannelNode) obj; @@ -177,8 +189,8 @@ final class ServerTreeDragAndDrop { Object dragged = draggedNode(support); Object resolved = resolve(support); tree.highlightChannel(null); - if (dragged instanceof ClientEntry) { - actions.moveClientToChannel((ClientEntry) dragged, (ChannelNode) resolved); + if (dragged instanceof DraggedClients) { + actions.moveClientsToChannel(((DraggedClients) dragged).clients(), (ChannelNode) resolved); } else if (dragged instanceof ChannelNode) { int[] place = (int[]) resolved; actions.moveChannel((ChannelNode) dragged, place[0], place[1]); @@ -191,7 +203,7 @@ final class ServerTreeDragAndDrop { Object dragged = draggedNode(support); if (!(support.getDropLocation() instanceof JTree.DropLocation)) return null; JTree.DropLocation loc = (JTree.DropLocation) support.getDropLocation(); - if (dragged instanceof ClientEntry) return resolveClientDrop(loc, (ClientEntry) dragged); + if (dragged instanceof DraggedClients) return resolveClientDrop(loc, ((DraggedClients) dragged).clients()); if (dragged instanceof ChannelNode) return resolveChannelDrop(loc, (ChannelNode) dragged); return null; } @@ -205,6 +217,10 @@ final class ServerTreeDragAndDrop { } } + /** The clients being dragged; the selection holds several clients or none. */ + private record DraggedClients(List clients) { + } + /** Offers the dragged node locally and its TS3 link BBCode to other applications. */ private static final class NodeTransferable implements Transferable { private final Object node; diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java index 02b7468..845ccf9 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreePanel.java @@ -29,6 +29,8 @@ import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -49,9 +51,9 @@ public final class ServerTreePanel extends JPanel { void complainAboutClient(ClientEntry client); - void kickClientFromChannel(ClientEntry client); + void kickClientsFromChannel(List clients); - void kickClientFromServer(ClientEntry client); + void kickClientsFromServer(List clients); void banClient(ClientEntry client); @@ -59,8 +61,8 @@ public final class ServerTreePanel extends JPanel { void showConnectionInfo(ClientEntry client); - /** Moves a client into the channel we are currently in. */ - void moveClientToOwnChannel(ClientEntry client); + /** Moves clients into the channel we are currently in. */ + void moveClientsToOwnChannel(List clients); /** Opens the channel editor for a channel. */ void editChannel(ChannelNode channel); @@ -102,8 +104,8 @@ public final class ServerTreePanel extends JPanel { /** A channel or client node was selected (or {@code null} when cleared). */ void onSelectionChanged(Object userObject); - /** Drag-and-drop of a client onto a channel. */ - void moveClientToChannel(ClientEntry client, ChannelNode target); + /** Drag-and-drop of clients (ourselves among them, possibly) onto a channel. */ + void moveClientsToChannel(List clients, ChannelNode target); /** * Drag-and-drop of a channel to a new place in the tree. @@ -213,6 +215,7 @@ public final class ServerTreePanel extends JPanel { // Lays out only the rows on screen. The default cache measures every row as it is // expanded, which freezes the window for seconds on servers with hundreds of channels. tree.setLargeModel(true); + tree.setSelectionModel(new ClientSelectionModel()); tree.setBackground(Theme.treeBg()); tree.setFont(Theme.uiFont()); ServerTreeCellRenderer renderer = new ServerTreeCellRenderer(id -> id == selfClientId, contacts, settings); @@ -274,13 +277,7 @@ public final class ServerTreePanel extends JPanel { }); tree.addTreeSelectionListener(e -> { - if (rebuilding) return; - TreePath path = tree.getSelectionPath(); - Object obj = null; - if (path != null) { - obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - } - actions.onSelectionChanged(obj); + if (!rebuilding) actions.onSelectionChanged(selectedUserObject()); }); tree.addMouseListener(new MouseAdapter() { @@ -322,8 +319,10 @@ public final class ServerTreePanel extends JPanel { */ private void selectRowUnder(MouseEvent e) { if (!SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) return; + // Ctrl and Shift build a selection of several clients, which Swing does itself. + if (e.isControlDown() || e.isShiftDown() || e.isMetaDown()) return; TreePath path = tree.pathAt(e.getY()); - if (path == null || path.equals(tree.getSelectionPath())) return; + if (path == null || tree.isPathSelected(path)) return; Rectangle bounds = tree.getPathBounds(path); // Left of the label is the expand handle, which Swing works the row without selecting it. if (bounds != null && e.getX() < bounds.x) return; @@ -360,9 +359,12 @@ public final class ServerTreePanel extends JPanel { if (!e.isPopupTrigger()) return; TreePath path = tree.pathAt(e.getY()); if (path == null) return; - tree.setSelectionPath(path); + if (!tree.isPathSelected(path)) tree.setSelectionPath(path); Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - if (obj instanceof ClientEntry) { + List selected = selectedClients(); + if (selected.size() > 1) { + ClientMenu.buildForMany(selected, selfClientId, model, actions).show(tree, e.getX(), e.getY()); + } else if (obj instanceof ClientEntry) { showClientMenu((ClientEntry) obj, e); } else if (obj instanceof ChannelNode) { showChannelMenu((ChannelNode) obj, e); @@ -382,6 +384,15 @@ public final class ServerTreePanel extends JPanel { ChannelMenu.build(channel, actions).show(tree, e.getX(), e.getY()); } + /** The selected clients, in tree order; empty when a channel or the server is selected. */ + private List selectedClients() { + List clients = new ArrayList<>(); + for (Object obj : selectedUserObjects()) { + if (obj instanceof ClientEntry) clients.add((ClientEntry) obj); + } + return clients; + } + /** The path of the tree node showing {@code target}, or {@code null}. */ private TreePath pathOf(Object target) { java.util.Enumeration nodes = root.breadthFirstEnumeration(); @@ -400,6 +411,7 @@ public final class ServerTreePanel extends JPanel { * nodes are in place, so a selection sticks until the user changes it. */ public void rebuild() { + List selection = selectedUserObjects(); Object selected = selectedUserObject(); rebuilding = true; try { @@ -413,10 +425,18 @@ public final class ServerTreePanel extends JPanel { } treeModel.reload(); expandOpenChannels(root, new TreePath(root)); - if (selected != null) { - TreePath path = pathOf(selected); - if (path != null) tree.setSelectionPath(path); + List paths = new ArrayList<>(selection.size()); + for (Object obj : selection) { + TreePath path = pathOf(obj); + if (path != null) paths.add(path); } + // The last path becomes the lead, the row the info panel shows. + TreePath lead = selected == null ? null : pathOf(selected); + if (lead != null) { + paths.remove(lead); + paths.add(lead); + } + if (!paths.isEmpty()) tree.setSelectionPaths(paths.toArray(new TreePath[0])); } finally { rebuilding = false; } @@ -442,8 +462,21 @@ public final class ServerTreePanel extends JPanel { } } + /** What the selected rows show, in tree order. */ + private List selectedUserObjects() { + int[] rows = tree.getSelectionRows(); + if (rows == null) return List.of(); + Arrays.sort(rows); + List objects = new ArrayList<>(rows.length); + for (int row : rows) { + objects.add(((DefaultMutableTreeNode) tree.getPathForRow(row).getLastPathComponent()).getUserObject()); + } + return objects; + } + + /** The row last added to the selection, which the info panel shows. */ private Object selectedUserObject() { - TreePath path = tree.getSelectionPath(); + TreePath path = tree.getSelectionModel().getLeadSelectionPath(); return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); }