Select several clients in the tree to move or kick them together

Desktop: Ctrl/Shift in the tree (ClientSelectionModel keeps a selection to
one row of any kind or several clients; a Shift range keeps its clients),
drag them onto a channel, or right-click for Kick Clients from Channel /
Server and Move Clients to own Channel. The selection survives rebuilds.
Android: long-press a client, tap more; a bar offers Move to…, Move to my
channel and both kicks (as far as we may), Back clears it.

Core sends one piped clientmove / clientkick. The server refuses the whole
pipe when one row fails ("already member of channel"), so it leaves out
clients already in the target, and for a channel kick those already in
the default channel, which the model now tracks (channel_flag_default).
Verified on a local 3.13.7 server with both frontends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-11 00:50:32 +00:00
co-authored by Claude Opus 5.5
parent 96e926168c
commit c41b86f704
12 changed files with 371 additions and 92 deletions
@@ -191,8 +191,11 @@ class ServerController internal constructor(
val canMoveClients: Boolean get() = session.canMoveClients() val canMoveClients: Boolean get() = session.canMoveClients()
fun moveClient(clientId: Int, channelId: Int) { /** The channel kicked clients go back to; 0 until the server named it. */
if (session.isConnected) conn.moveClient(clientId, channelId, null) val defaultChannelId: Int get() = conn.model.defaultChannelId()
fun moveClients(clientIds: Collection<Int>, channelId: Int) {
if (session.isConnected) conn.moveClients(clientIds, channelId)
} }
fun poke(clientId: Int, message: String) { 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. */ /** The longest ban we may hand out in seconds; 0 or -1 for no limit. */
val maxBanSeconds: Long get() = conn.model.maxBanSeconds() val maxBanSeconds: Long get() = conn.model.maxBanSeconds()
fun kickFromChannel(clientId: Int, reason: String) { fun kickFromChannel(clientIds: Collection<Int>, reason: String) {
if (session.isConnected) conn.kickFromChannel(clientId, reason) if (session.isConnected) conn.kickFromChannel(clientIds, reason)
} }
fun kickFromServer(clientId: Int, reason: String) { fun kickFromServer(clientIds: Collection<Int>, reason: String) {
if (session.isConnected) conn.kickFromServer(clientId, reason) if (session.isConnected) conn.kickFromServer(clientIds, reason)
} }
/** Bans a client for [seconds], or for good with 0. */ /** Bans a client for [seconds], or for good with 0. */
@@ -153,6 +153,10 @@ fun ChannelTree(
listState: LazyListState = rememberLazyListState(), listState: LazyListState = rememberLazyListState(),
/** Brings our own client into view; its row may sit in folded channels. */ /** Brings our own client into view; its row may sit in folded channels. */
onShowSelf: () -> Unit = {}, onShowSelf: () -> Unit = {},
/** Clients picked to be moved or kicked together. */
selected: Set<Int> = 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) } val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
var flashing by remember { mutableStateOf<TreeRef?>(null) } var flashing by remember { mutableStateOf<TreeRef?>(null) }
@@ -201,16 +205,17 @@ fun ChannelTree(
} }
items(rows, key = { it.key }) { row -> items(rows, key = { it.key }) { row ->
val background = rowBackground( val background = rowBackground(
when (row.ref) { when {
flashing -> FLASH row.ref == flashing -> FLASH
foundCurrent -> findCurrentColor() !row.ref.channel && row.ref.id in selected -> MaterialTheme.colorScheme.secondaryContainer
in found -> findMatchColor() row.ref == foundCurrent -> findCurrentColor()
row.ref in found -> findMatchColor()
else -> Color.Transparent else -> Color.Transparent
}, },
) )
when (row) { when (row) {
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap) 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. */ /** The colour under [background], which a flash or find match goes over. */
tint: Color = Color.Transparent, tint: Color = Color.Transparent,
onDoubleClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null,
onLongClick: (() -> Unit)? = null,
content: @Composable RowScope.() -> Unit, content: @Composable RowScope.() -> Unit,
) { ) {
Row( Row(
@@ -247,7 +253,7 @@ private fun RowLayout(
.background(tint) .background(tint)
.background(background) .background(background)
.height(ROW) .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), .padding(start = 4.dp + INDENT * depth, end = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
@@ -315,9 +321,16 @@ private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
} }
@Composable @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 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)) Spacer(Modifier.width(ICON + 4.dp))
StatusIcon(client.status) StatusIcon(client.status)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) { Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
@@ -211,7 +211,7 @@ fun ClientModeration(server: ServerController, client: ClientItem, onDone: () ->
onDismiss = { kick = null }, onDismiss = { kick = null },
) { reason -> ) { reason ->
kick = null 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() onDone()
} }
} }
@@ -22,6 +22,7 @@ import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox 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. */ /** 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<Pair<String, (WhisperList) -> Unit>?>(null) } var toWhisperList by remember { mutableStateOf<Pair<String, (WhisperList) -> Unit>?>(null) }
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) } var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
/** The client to move, while a channel for them is being picked. */ /** The clients to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Int?>(null) } var moving by remember { mutableStateOf<Set<Int>?>(null) }
/** Clients picked by a long press, to be moved or kicked together; those who left fall out. */
var picked by remember { mutableStateOf(emptySet<Int>()) }
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<Boolean?>(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<Int> ->
server.moveClients(clients, channelId)
moving = null
picked = emptySet()
}
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle() val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val chatRequest by server.chatRequest.collectAsStateWithLifecycle() val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
@@ -261,6 +277,7 @@ fun ServerScreen(
BackHandler(showChat) { showChat = false } BackHandler(showChat) { showChat = false }
BackHandler(moving != null && !showChat) { moving = null } BackHandler(moving != null && !showChat) { moving = null }
BackHandler(moving == null && selection.isNotEmpty() && !showChat) { picked = emptySet() }
BackHandler(find.open) { find.open = false } BackHandler(find.open) { find.open = false }
Scaffold( Scaffold(
@@ -304,13 +321,24 @@ fun ServerScreen(
) { padding -> ) { padding ->
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) { Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) {
if (!showChat) { if (!showChat) {
moving?.let { id -> val movingNow = moving
val client = tree.client(id) if (movingNow != null) {
if (client == null) { val clients = movingNow.mapNotNull { tree.client(it) }
LaunchedEffect(id) { moving = null } if (clients.isEmpty()) {
LaunchedEffect(movingNow) { moving = null }
} else { } 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( ChannelTree(
serverName = state.title, serverName = state.title,
@@ -323,22 +351,28 @@ fun ServerScreen(
else filterCollapsed += it.id else filterCollapsed += it.id
}, },
onChannel = { channel -> onChannel = { channel ->
val client = moving val clients = moving
when { when {
channel.spacer != null -> {} channel.spacer != null -> {}
client != null -> { server.moveClient(client, channel.id); moving = null } clients != null -> moveTo(channel.id, clients)
else -> channelSheet = channel.id else -> channelSheet = channel.id
} }
}, },
onChannelDoubleTap = { channel -> onChannelDoubleTap = { channel ->
val client = moving val clients = moving
when { when {
client != null -> { server.moveClient(client, channel.id); moving = null } clients != null -> moveTo(channel.id, clients)
channel.id == state.channelId -> {} channel.id == state.channelId -> {}
else -> join(channel) 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 }, onServer = { serverSheet = true },
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
reveal = reveal, reveal = reveal,
@@ -346,6 +380,10 @@ fun ServerScreen(
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }, found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) }, foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) },
listState = treeList, listState = treeList,
selected = selection,
onClientLongPress = if (server.canMoveClients || server.canKickFromChannel || server.canKickFromServer) {
{ picked = selection + it.id }
} else null,
onShowSelf = { onShowSelf = {
val path = tree.pathTo(state.selfClientId).orEmpty() val path = tree.pathTo(state.selfClientId).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path) if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
@@ -403,9 +441,9 @@ fun ServerScreen(
clientSheet = null clientSheet = null
server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } } server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } }
}) else null, }) 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) { 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, } else null,
onFindInTree = if (clientSheetFromTree) null else ({ onFindInTree = if (clientSheetFromTree) null else ({
clientSheet = null 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 -> joinLocked?.let { id ->
TextPrompt( TextPrompt(
title = "Join ${tree.channel(id)?.name.orEmpty()}", 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 = 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) 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]. */ /** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable @Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) { private fun MovePrompt(name: String, onCancel: () -> Unit) {
@@ -452,8 +452,11 @@ final class ConnectionEventHandler implements TS3Listener {
} }
/** The properties a channel event carries that the model keeps; each only when present. */ /** 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_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. // 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 (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"); if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id");
@@ -42,6 +42,8 @@ public final class ServerModel {
private final Map<String, String> serverProperties = new HashMap<>(); private final Map<String, String> serverProperties = new HashMap<>();
/** The channel group everyone starts in, e.g. "Guest" — not worth offering to (re)assign. */ /** The channel group everyone starts in, e.g. "Guest" — not worth offering to (re)assign. */
private int defaultChannelGroupId; 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() { public synchronized void clear() {
channels.clear(); channels.clear();
@@ -55,6 +57,7 @@ public final class ServerModel {
unreportedValues.clear(); unreportedValues.clear();
serverProperties.clear(); serverProperties.clear();
defaultChannelGroupId = 0; defaultChannelGroupId = 0;
defaultChannelId = 0;
} }
// ---- groups ---- // ---- groups ----
@@ -352,6 +355,15 @@ public final class ServerModel {
return c; 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) { public synchronized ChannelNode getChannel(int id) {
return channels.get(id); return channels.get(id);
} }
@@ -752,20 +752,66 @@ public final class TeamspeakConnection implements TS3Listener {
(password == null || password.isEmpty()) ? null : password)); (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<Integer> clientIds, int channelId) {
List<SingleCommand> 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. */ /** Kicks a client out of its channel, back into the server's default one. */
public void kickFromChannel(int clientId, String reason) { 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<Integer> clientIds, String reason) {
int defaultChannel = model.defaultChannelId();
List<Integer> 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. */ /** Kicks a client off the server entirely. */
public void kickFromServer(int clientId, String reason) { 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<Integer> clientIds, String reason) {
kick(clientIds, REASON_KICK_SERVER, reason, "server");
}
private void kick(Collection<Integer> clientIds, int reasonId, String reason, String from) {
List<SingleCommand> 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 -> { act(errorPrefix, sock -> {
SingleCommand cmd = new SingleCommand("clientkick", ProtocolRole.CLIENT); MultiCommand cmd = new MultiCommand("clientkick", ProtocolRole.CLIENT, rows);
cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId)));
cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId))); cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId)));
if (reason != null && !reason.isEmpty()) { if (reason != null && !reason.isEmpty()) {
cmd.add(new CommandSingleParameter("reasonmsg", reason)); cmd.add(new CommandSingleParameter("reasonmsg", reason));
@@ -42,10 +42,10 @@ final class ClientMenu {
menu.add(complain); menu.add(complain);
menu.addSeparator(); menu.addSeparator();
JMenuItem kickChannel = new JMenuItem("Kick Client from Channel", Icons.of("KICK_FROM_CHANNEL")); 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); menu.add(kickChannel);
JMenuItem kickServer = new JMenuItem("Kick Client from Server", Icons.of("KICK_FROM_SERVER")); 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); menu.add(kickServer);
JMenuItem ban = new JMenuItem("Ban Client", Icons.of("BAN_CLIENT")); JMenuItem ban = new JMenuItem("Ban Client", Icons.of("BAN_CLIENT"));
ban.addActionListener(a -> actions.banClient(client)); ban.addActionListener(a -> actions.banClient(client));
@@ -93,12 +93,34 @@ final class ClientMenu {
joinChannel.addActionListener(a -> actions.joinChannel(client.channelId)); joinChannel.addActionListener(a -> actions.joinChannel(client.channelId));
menu.add(joinChannel); menu.add(joinChannel);
JMenuItem moveHere = new JMenuItem("Move Client to own Channel", Icons.of("MOVE_CLIENT_TO_OWN_CHANNEL")); 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); menu.add(moveHere);
} }
return menu; return menu;
} }
/** The context menu for several clients selected together; we may be among them. */
static JPopupMenu buildForMany(List<ClientEntry> 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 * 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. * added as a friend or blocked; one on it can be edited or removed.
@@ -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<TreePath> 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;
}
}
@@ -12,6 +12,8 @@ import eu.lixko.ts3j.client.text.TsLink;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import java.awt.Component; 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 * 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 @Override
public void moveClientToChannel(ClientEntry client, ChannelNode target) { public void moveClientsToChannel(List<ClientEntry> clients, ChannelNode target) {
if (!conn.isConnected()) return; if (conn.isConnected()) conn.moveClients(ids(clients), target.id);
if (client.id == conn.getSelfClientId()) {
conn.joinChannel(target.id, null);
} else {
conn.moveClient(client.id, target.id, null);
}
} }
@Override @Override
@@ -149,21 +146,29 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
} }
@Override @Override
public void kickClientFromChannel(ClientEntry client) { public void kickClientsFromChannel(List<ClientEntry> clients) {
String reason = kickReason("Kick Client from Channel", client); String reason = kickReason("Channel", clients);
if (reason != null) conn.kickFromChannel(client.id, reason); if (reason != null) conn.kickFromChannel(ids(clients), reason);
} }
@Override @Override
public void kickClientFromServer(ClientEntry client) { public void kickClientsFromServer(List<ClientEntry> clients) {
String reason = kickReason("Kick Client from Server", client); String reason = kickReason("Server", clients);
if (reason != null) conn.kickFromServer(client.id, reason); if (reason != null) conn.kickFromServer(ids(clients), reason);
} }
private String kickReason(String title, ClientEntry client) { private String kickReason(String from, List<ClientEntry> clients) {
if (!conn.isConnected()) return null; if (!conn.isConnected()) return null;
return ReasonDialog.prompt(host, title, "Reason for kicking " + client.nickname + ":", boolean one = clients.size() == 1;
TeamspeakConnection.KICK_REASON_LIMIT); 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<Integer> ids(List<ClientEntry> clients) {
List<Integer> ids = new ArrayList<>(clients.size());
for (ClientEntry client : clients) ids.add(client.id);
return ids;
} }
@Override @Override
@@ -195,10 +200,10 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
} }
@Override @Override
public void moveClientToOwnChannel(ClientEntry client) { public void moveClientsToOwnChannel(List<ClientEntry> clients) {
if (!conn.isConnected() || client.id == conn.getSelfClientId()) return; if (!conn.isConnected()) return;
ClientEntry self = conn.getModel().getClient(conn.getSelfClientId()); 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 @Override
@@ -14,11 +14,16 @@ import javax.swing.tree.TreePath;
import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable; import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException; 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; import java.util.function.Function;
/** /**
* Drag-and-drop for the {@link ServerTreePanel} tree: dragging a client onto a * Drag-and-drop for the {@link ServerTreePanel} tree: dragging clients onto a
* channel moves it there, dragging a channel reorders/reparents it, and dropping * 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 * either outside the tree yields its TS3 link BBCode, which the chat input accepts
* as plain text. * 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 * The channel dragged clients would land in, or {@code null} if the drop makes
* no sense (outside a channel, or the channel the client is already in). * 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<ClientEntry> dragged) {
DefaultMutableTreeNode target = nodeOf(loc.getPath()); DefaultMutableTreeNode target = nodeOf(loc.getPath());
if (target == null) return null; if (target == null) return null;
Object obj = target.getUserObject(); Object obj = target.getUserObject();
@@ -66,8 +71,8 @@ final class ServerTreeDragAndDrop {
channel = model.getChannel(((ClientEntry) obj).channelId); channel = model.getChannel(((ClientEntry) obj).channelId);
} }
if (channel == null || Spacers.isSpacer(channel.name)) return null; if (channel == null || Spacers.isSpacer(channel.name)) return null;
if (channel.id == dragged.channelId) return null; int channelId = channel.id;
return channel; return dragged.stream().allMatch(c -> c.channelId == channelId) ? null : channel;
} }
/** /**
@@ -131,12 +136,19 @@ final class ServerTreeDragAndDrop {
@Override @Override
protected Transferable createTransferable(JComponent c) { protected Transferable createTransferable(JComponent c) {
TreePath path = tree.getSelectionPath(); TreePath[] paths = tree.getSelectionPaths();
if (path == null) return null; if (paths == null) return null;
Object obj = nodeOf(path).getUserObject(); Arrays.sort(paths, Comparator.comparingInt(tree::getRowForPath));
Object obj = nodeOf(paths[0]).getUserObject();
if (obj instanceof ClientEntry) { if (obj instanceof ClientEntry) {
ClientEntry cl = (ClientEntry) obj; List<ClientEntry> clients = new ArrayList<>(paths.length);
return new NodeTransferable(cl, TsLink.clientBBCode(cl.id, cl.uniqueId, cl.nickname)); 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) { if (obj instanceof ChannelNode) {
ChannelNode ch = (ChannelNode) obj; ChannelNode ch = (ChannelNode) obj;
@@ -177,8 +189,8 @@ final class ServerTreeDragAndDrop {
Object dragged = draggedNode(support); Object dragged = draggedNode(support);
Object resolved = resolve(support); Object resolved = resolve(support);
tree.highlightChannel(null); tree.highlightChannel(null);
if (dragged instanceof ClientEntry) { if (dragged instanceof DraggedClients) {
actions.moveClientToChannel((ClientEntry) dragged, (ChannelNode) resolved); actions.moveClientsToChannel(((DraggedClients) dragged).clients(), (ChannelNode) resolved);
} else if (dragged instanceof ChannelNode) { } else if (dragged instanceof ChannelNode) {
int[] place = (int[]) resolved; int[] place = (int[]) resolved;
actions.moveChannel((ChannelNode) dragged, place[0], place[1]); actions.moveChannel((ChannelNode) dragged, place[0], place[1]);
@@ -191,7 +203,7 @@ final class ServerTreeDragAndDrop {
Object dragged = draggedNode(support); Object dragged = draggedNode(support);
if (!(support.getDropLocation() instanceof JTree.DropLocation)) return null; if (!(support.getDropLocation() instanceof JTree.DropLocation)) return null;
JTree.DropLocation loc = (JTree.DropLocation) support.getDropLocation(); 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); if (dragged instanceof ChannelNode) return resolveChannelDrop(loc, (ChannelNode) dragged);
return null; return null;
} }
@@ -205,6 +217,10 @@ final class ServerTreeDragAndDrop {
} }
} }
/** The clients being dragged; the selection holds several clients or none. */
private record DraggedClients(List<ClientEntry> clients) {
}
/** Offers the dragged node locally and its TS3 link BBCode to other applications. */ /** Offers the dragged node locally and its TS3 link BBCode to other applications. */
private static final class NodeTransferable implements Transferable { private static final class NodeTransferable implements Transferable {
private final Object node; private final Object node;
@@ -29,6 +29,8 @@ import java.awt.Rectangle;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -49,9 +51,9 @@ public final class ServerTreePanel extends JPanel {
void complainAboutClient(ClientEntry client); void complainAboutClient(ClientEntry client);
void kickClientFromChannel(ClientEntry client); void kickClientsFromChannel(List<ClientEntry> clients);
void kickClientFromServer(ClientEntry client); void kickClientsFromServer(List<ClientEntry> clients);
void banClient(ClientEntry client); void banClient(ClientEntry client);
@@ -59,8 +61,8 @@ public final class ServerTreePanel extends JPanel {
void showConnectionInfo(ClientEntry client); void showConnectionInfo(ClientEntry client);
/** Moves a client into the channel we are currently in. */ /** Moves clients into the channel we are currently in. */
void moveClientToOwnChannel(ClientEntry client); void moveClientsToOwnChannel(List<ClientEntry> clients);
/** Opens the channel editor for a channel. */ /** Opens the channel editor for a channel. */
void editChannel(ChannelNode 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). */ /** A channel or client node was selected (or {@code null} when cleared). */
void onSelectionChanged(Object userObject); void onSelectionChanged(Object userObject);
/** Drag-and-drop of a client onto a channel. */ /** Drag-and-drop of clients (ourselves among them, possibly) onto a channel. */
void moveClientToChannel(ClientEntry client, ChannelNode target); void moveClientsToChannel(List<ClientEntry> clients, ChannelNode target);
/** /**
* Drag-and-drop of a channel to a new place in the tree. * 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 // 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. // expanded, which freezes the window for seconds on servers with hundreds of channels.
tree.setLargeModel(true); tree.setLargeModel(true);
tree.setSelectionModel(new ClientSelectionModel());
tree.setBackground(Theme.treeBg()); tree.setBackground(Theme.treeBg());
tree.setFont(Theme.uiFont()); tree.setFont(Theme.uiFont());
ServerTreeCellRenderer renderer = new ServerTreeCellRenderer(id -> id == selfClientId, contacts, settings); ServerTreeCellRenderer renderer = new ServerTreeCellRenderer(id -> id == selfClientId, contacts, settings);
@@ -274,13 +277,7 @@ public final class ServerTreePanel extends JPanel {
}); });
tree.addTreeSelectionListener(e -> { tree.addTreeSelectionListener(e -> {
if (rebuilding) return; if (!rebuilding) actions.onSelectionChanged(selectedUserObject());
TreePath path = tree.getSelectionPath();
Object obj = null;
if (path != null) {
obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
}
actions.onSelectionChanged(obj);
}); });
tree.addMouseListener(new MouseAdapter() { tree.addMouseListener(new MouseAdapter() {
@@ -322,8 +319,10 @@ public final class ServerTreePanel extends JPanel {
*/ */
private void selectRowUnder(MouseEvent e) { private void selectRowUnder(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e) && !e.isPopupTrigger()) return; 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()); 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); Rectangle bounds = tree.getPathBounds(path);
// Left of the label is the expand handle, which Swing works the row without selecting it. // Left of the label is the expand handle, which Swing works the row without selecting it.
if (bounds != null && e.getX() < bounds.x) return; if (bounds != null && e.getX() < bounds.x) return;
@@ -360,9 +359,12 @@ public final class ServerTreePanel extends JPanel {
if (!e.isPopupTrigger()) return; if (!e.isPopupTrigger()) return;
TreePath path = tree.pathAt(e.getY()); TreePath path = tree.pathAt(e.getY());
if (path == null) return; if (path == null) return;
tree.setSelectionPath(path); if (!tree.isPathSelected(path)) tree.setSelectionPath(path);
Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); Object obj = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
if (obj instanceof ClientEntry) { List<ClientEntry> 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); showClientMenu((ClientEntry) obj, e);
} else if (obj instanceof ChannelNode) { } else if (obj instanceof ChannelNode) {
showChannelMenu((ChannelNode) obj, e); showChannelMenu((ChannelNode) obj, e);
@@ -382,6 +384,15 @@ public final class ServerTreePanel extends JPanel {
ChannelMenu.build(channel, actions).show(tree, e.getX(), e.getY()); 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<ClientEntry> selectedClients() {
List<ClientEntry> 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}. */ /** The path of the tree node showing {@code target}, or {@code null}. */
private TreePath pathOf(Object target) { private TreePath pathOf(Object target) {
java.util.Enumeration<?> nodes = root.breadthFirstEnumeration(); 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. * nodes are in place, so a selection sticks until the user changes it.
*/ */
public void rebuild() { public void rebuild() {
List<Object> selection = selectedUserObjects();
Object selected = selectedUserObject(); Object selected = selectedUserObject();
rebuilding = true; rebuilding = true;
try { try {
@@ -413,10 +425,18 @@ public final class ServerTreePanel extends JPanel {
} }
treeModel.reload(); treeModel.reload();
expandOpenChannels(root, new TreePath(root)); expandOpenChannels(root, new TreePath(root));
if (selected != null) { List<TreePath> paths = new ArrayList<>(selection.size());
TreePath path = pathOf(selected); for (Object obj : selection) {
if (path != null) tree.setSelectionPath(path); 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 { } finally {
rebuilding = false; rebuilding = false;
} }
@@ -442,8 +462,21 @@ public final class ServerTreePanel extends JPanel {
} }
} }
/** What the selected rows show, in tree order. */
private List<Object> selectedUserObjects() {
int[] rows = tree.getSelectionRows();
if (rows == null) return List.of();
Arrays.sort(rows);
List<Object> 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() { private Object selectedUserObject() {
TreePath path = tree.getSelectionPath(); TreePath path = tree.getSelectionModel().getLeadSelectionPath();
return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
} }