Android: create, edit and delete channels

A one-page channel editor with what the desktop dialog has but the
permissions and the icon: name, password, topic, description, type,
sorting, talk power, codec preset or codec and quality, and the limits.
Create channel is on the server sheet; create sub-channel, edit and
delete on the channel sheet, each only with the permission for it.

The codec list, presets and bandwidth move to core for both editors.
Core gains channel delete, and the desktop channel menu a Delete Channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-09 22:19:52 +00:00
co-authored by Claude Opus 5.5
parent 60ef727f22
commit 7938b49b07
14 changed files with 449 additions and 40 deletions
@@ -4,6 +4,7 @@ import android.net.Uri
import com.ts3client.config.Bookmark
import com.ts3client.contacts.ContactType
import com.ts3client.net.ChannelNode
import com.ts3client.net.ChannelSettings
import com.ts3client.net.ConnectionStats
import com.ts3client.net.Details
import com.ts3client.net.GroupChoice
@@ -183,6 +184,36 @@ class ServerController internal constructor(
conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) }
}
// ---- channel administration ----
val canCreateChannels: Boolean get() = session.canCreateChannels()
val canEditChannels: Boolean get() = session.canEditChannels()
val canDeleteChannels: Boolean get() = session.canDeleteChannels()
/** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */
fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> =
if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId)
/** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = suspendCoroutine { done ->
conn.requestChannelSettings(channelId) { settings, error ->
done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */
suspend fun editChannel(channelId: Int, changes: Map<String, String>): String? =
if (changes.isEmpty()) null
else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } }
suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done ->
conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) }
}
/** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): String? =
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
// ---- moderation ----
val canKickFromChannel: Boolean get() = session.canKickFromChannel()
@@ -0,0 +1,211 @@
package com.ts3client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import com.ts3client.android.ServerController
import com.ts3client.net.ChannelCodec
import com.ts3client.net.ChannelSettings
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/** The channel being edited ([channelId] > 0), or one to create below [parentId] (0: the top level). */
data class ChannelEdit(val channelId: Int, val parentId: Int = 0)
/**
* TeamSpeak's channel editor on one page: name, password, topic and description, then the
* channel's type, sorting, audio and limits. Only what changed is sent, as the server refuses
* an edit carrying one property we may not change.
*/
@Composable
fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () -> Unit) {
val creating = edit.channelId <= 0
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
/** The channel as the server described it, which changes are measured against. */
var original by remember { mutableStateOf<ChannelSettings?>(null) }
var edited by remember { mutableStateOf<ChannelSettings?>(null) }
var passwordText by remember { mutableStateOf("") }
var saving by remember { mutableStateOf(false) }
LaunchedEffect(edit) {
if (creating) {
// Made from a channel's sheet, a channel is usually a throwaway one, as in TeamSpeak;
// the server puts a new channel after its siblings.
val fresh = ChannelSettings().apply {
type = ChannelSettings.Type.TEMPORARY
parentId = edit.parentId
order = server.sortChoices(0, edit.parentId).lastOrNull()?.id ?: 0
}
original = fresh
edited = fresh.copy()
} else {
server.channelSettings(edit.channelId)
.onSuccess { original = it; edited = it.copy() }
.onFailure { snackbar.showSnackbar("Could not read the channel: ${it.message}"); onDone() }
}
}
val change = { f: ChannelSettings.() -> Unit -> edited = edited?.copy()?.apply(f) }
val save = save@{
val e = edited ?: return@save
val o = original ?: return@save
if (e.name.isBlank()) {
scope.launch { snackbar.showSnackbar("The channel needs a name.") }
return@save
}
saving = true
scope.launch {
val trimmed = e.copy().apply { name = name.trim() }
val error = if (creating) server.createChannel(edit.parentId, trimmed)
else server.editChannel(edit.channelId, trimmed.changesFrom(o))
saving = false
if (error == null) onDone()
else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error)
}
}
val title = when {
!creating -> "Edit channel"
edit.parentId > 0 -> "New sub-channel"
else -> "New channel"
}
SubScreen(title, onBack = onDone, snackbar = snackbar, actions = {
TextButton(onClick = save, enabled = edited != null && !saving) { Text(if (creating) "Create" else "Save") }
}) { padding ->
val e = edited
if (e == null) {
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
return@SubScreen
}
Column(Modifier.padding(padding).imePadding().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(e.name, { change { name = it } }, Modifier.fillMaxWidth(), label = { Text("Name") },
singleLine = true)
OutlinedTextField(passwordText, {
passwordText = it
change { password = it }
}, Modifier.fillMaxWidth(), label = { Text("Password") }, singleLine = true,
placeholder = if (e.hasPassword && e.password == null) ({ Text("Unchanged") }) else null,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
if (e.hasPassword && e.password == null) {
TextButton(onClick = { change { password = "" } }) { Text("Remove password") }
}
OutlinedTextField(e.topic, { change { topic = it } }, Modifier.fillMaxWidth(), label = { Text("Topic") },
singleLine = true)
OutlinedTextField(e.description, { change { description = it } }, Modifier.fillMaxWidth(),
label = { Text("Description") }, minLines = 3, maxLines = 10)
}
Section("Channel type")
Segments(listOf(
ChannelSettings.Type.TEMPORARY to "Temporary",
ChannelSettings.Type.SEMI_PERMANENT to "Semi-permanent",
ChannelSettings.Type.PERMANENT to "Permanent",
), e.type) { change { type = it } }
// The default channel cannot stop being one; another has to take over.
if (original?.defaultChannel != true) {
Toggle("Default channel", e.defaultChannel) { change { defaultChannel = it } }
}
val siblings = remember(edit) {
server.sortChoices(edit.channelId, edit.parentId).filter { it.id != edit.channelId }
}
Picker("Sort after", listOf(0 to "(first)") + siblings.map { it.id to it.name },
e.order.takeIf { o -> o == 0 || siblings.any { it.id == o } } ?: 0) { change { order = it } }
NumberField("Needed talk power", e.neededTalkPower, 0..9999) { change { neededTalkPower = it } }
Section("Audio")
val preset = ChannelCodec.Preset.of(e.codec, e.codecQuality)
var custom by remember { mutableStateOf(preset == null) }
val presets: List<Pair<ChannelCodec.Preset?, String>> =
ChannelCodec.Preset.entries.map { it to it.label } + (null to "Custom")
Segments(presets, if (custom) null else preset) { picked ->
custom = picked == null
if (picked != null) change { codec = picked.codec; codecQuality = picked.quality }
}
if (custom) {
Picker("Codec", ChannelCodec.NAMES.indices.map { it to ChannelCodec.NAMES[it] },
ChannelCodec.clampCodec(e.codec)) { change { codec = it } }
Level("Quality", e.codecQuality.toFloat(), 0f..ChannelCodec.MAX_QUALITY.toFloat(),
{ it.roundToInt().toString() }, steps = ChannelCodec.MAX_QUALITY - 1) {
change { codecQuality = it.roundToInt() }
}
}
Hint("Bandwidth: ${ChannelCodec.bandwidthText(e.codec, e.codecQuality)} per talking client")
Section("Advanced")
Column(Modifier.padding(horizontal = 16.dp)) {
OutlinedTextField(e.phoneticName, { change { phoneticName = it } }, Modifier.fillMaxWidth(),
label = { Text("Phonetic name") }, singleLine = true)
}
if (e.type == ChannelSettings.Type.TEMPORARY) {
NumberField("Delete delay (seconds)", e.deleteDelay, 0..ChannelSettings.MAX_DELETE_DELAY) {
change { deleteDelay = it }
}
}
Toggle("Voice encrypted", e.encrypted) { change { encrypted = it } }
Text("Max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
Segments(listOf(true to "Unlimited", false to "Limited"), e.maxClientsUnlimited) {
change { maxClientsUnlimited = it }
}
if (!e.maxClientsUnlimited) NumberField("Users", e.maxClients, 0..65535) { change { maxClients = it } }
Text("Family max users", Modifier.padding(start = 16.dp, top = 8.dp), style = MaterialTheme.typography.bodyLarge)
val family = when {
e.familyInherited -> FamilyLimit.INHERITED
e.familyUnlimited -> FamilyLimit.UNLIMITED
else -> FamilyLimit.LIMITED
}
Segments(FamilyLimit.entries.map { it to it.label }, family) {
change {
familyInherited = it == FamilyLimit.INHERITED
familyUnlimited = it == FamilyLimit.UNLIMITED
}
}
if (family == FamilyLimit.LIMITED) {
NumberField("Users", e.maxFamilyClients, 0..65535) { change { maxFamilyClients = it } }
}
}
}
}
private enum class FamilyLimit(val label: String) { INHERITED("Inherited"), UNLIMITED("Unlimited"), LIMITED("Limited") }
/** A whole number within [range]; what does not parse leaves the value alone. */
@Composable
private fun NumberField(label: String, value: Int, range: IntRange, onChange: (Int) -> Unit) {
var text by remember(value) { mutableStateOf(value.toString()) }
Row(Modifier.padding(horizontal = 16.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(text, {
text = it.filter(Char::isDigit).take(7)
text.toIntOrNull()?.let { n -> onChange(n.coerceIn(range)) }
}, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
}
}
@@ -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.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
@@ -48,6 +49,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -80,6 +82,7 @@ import com.ts3client.config.Settings
import com.ts3client.myts.ChatAttachment
import com.ts3client.session.ServerLink
import com.ts3client.text.TsLink
import kotlinx.coroutines.launch
private val ChatKeySaver = Saver<ChatKey, String>(
save = { key ->
@@ -98,6 +101,11 @@ private val ChatKeySaver = Saver<ChatKey, String>(
},
)
private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } },
restore = { ChannelEdit(it[0], it[1]) },
)
/** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -135,6 +143,8 @@ fun ServerScreen(
var serverSheet by remember { mutableStateOf(false) }
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
var banList by rememberSaveable { mutableStateOf(false) }
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
var deletingChannel by remember { mutableStateOf<Int?>(null) }
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
/** The client to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Int?>(null) }
@@ -217,6 +227,10 @@ fun ServerScreen(
BanListScreen(server, vm.banReasons, onBack = { banList = false })
return
}
channelEdit?.let {
ChannelEditScreen(server, it, onDone = { channelEdit = null })
return
}
connectionInfo?.let { id ->
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
return
@@ -383,6 +397,9 @@ fun ServerScreen(
onJoin = { join(channel); channelSheet = null },
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
onBookmark = { channelSheet = null; bookmarkHere(id) },
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
)
}
}
@@ -396,11 +413,30 @@ fun ServerScreen(
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
)
}
deletingChannel?.let { id ->
val channel = tree.channel(id)
val scope = rememberCoroutineScope()
AlertDialog(
onDismissRequest = { deletingChannel = null },
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = {
deletingChannel = null
scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
)
}
if (serverSheet) {
remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
onBookmark = { serverSheet = false; bookmarkHere(state.channelId) },
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null)
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null,
onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null)
}
}
}
@@ -141,6 +141,10 @@ fun ChannelSheet(
onJoin: () -> Unit,
onSubscribe: (Boolean) -> Unit,
onBookmark: () -> Unit,
/** Each null when we may not. */
onCreateSub: (() -> Unit)?,
onEdit: (() -> Unit)?,
onDelete: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
@@ -156,6 +160,9 @@ fun ChannelSheet(
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
}
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) }
}
}
}
@@ -169,6 +176,7 @@ fun ServerSheet(
onDismiss: () -> Unit,
onBookmark: () -> Unit,
onBanList: (() -> Unit)?,
onCreateChannel: (() -> Unit)?,
) {
ModalBottomSheet(onDismissRequest = onDismiss) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
@@ -179,6 +187,7 @@ fun ServerSheet(
}
DetailsSection(details, onLink)
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateChannel?.let { Action("CHANNEL_CREATE", "Create channel", onClick = it) }
onBanList?.let { Action("BAN_LIST", "Ban list", onClick = it) }
}
}
@@ -97,6 +97,13 @@ final class ChannelAdmin {
conn.socket().executeCommand(cmd).complete();
}
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */
void delete(int channelId, boolean force) throws Exception {
conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)),
new CommandSingleParameter("force", force ? "1" : "0"))).complete();
}
// ---- channel permissions ----
/**
@@ -0,0 +1,73 @@
package com.ts3client.net;
/**
* The voice codecs a channel can use, in TeamSpeak's own id order, with the editor's
* presets and what one talking client costs in bandwidth.
*/
public final class ChannelCodec {
/** Codec names, indexed by {@link ChannelSettings#codec}. */
public static final String[] NAMES = {
"Speex Narrowband", "Speex Wideband", "Speex Ultra-Wideband",
"CELT Mono", "Opus Voice", "Opus Music"};
public static final int OPUS_VOICE = 4;
public static final int OPUS_MUSIC = 5;
public static final int MAX_QUALITY = 10;
/** The channel editor's presets; a codec and quality matching none of them is custom. */
public enum Preset {
VOICE_MOBILE("Voice Mobile", OPUS_VOICE, 4),
VOICE_DESKTOP("Voice Desktop", OPUS_VOICE, 6),
MUSIC("Music", OPUS_MUSIC, 6);
public final String label;
public final int codec;
public final int quality;
Preset(String label, int codec, int quality) {
this.label = label;
this.codec = codec;
this.quality = quality;
}
/** The preset with this codec and quality, or null for a custom setting. */
public static Preset of(int codec, int quality) {
for (Preset p : values()) {
if (p.codec == codec && p.quality == quality) return p;
}
return null;
}
}
/**
* Bandwidth per talking client in KiB/s at quality 0 and 10, per codec, as published by
* TeamSpeak. The steps in between are interpolated: the client shows a figure per
* quality step, and only the two ends of each codec's range are documented.
*/
private static final double[][] BANDWIDTH_RANGE = {
{2.49, 5.22}, {2.69, 7.37}, {2.73, 7.57}, {6.10, 13.92}, {2.73, 7.71}, {3.08, 11.87}};
private ChannelCodec() {
}
public static String name(int codec) {
return NAMES[clampCodec(codec)];
}
public static int clampCodec(int codec) {
return Math.max(0, Math.min(NAMES.length - 1, codec));
}
/** KiB/s one talking client costs. */
public static double bandwidth(int codec, int quality) {
double[] range = BANDWIDTH_RANGE[clampCodec(codec)];
int q = Math.max(0, Math.min(MAX_QUALITY, quality));
return range[0] + (range[1] - range[0]) * q / MAX_QUALITY;
}
/** {@link #bandwidth} as the editor shows it. */
public static String bandwidthText(int codec, int quality) {
return String.format("%.2f KiB/s", bandwidth(codec, quality));
}
}
@@ -18,6 +18,9 @@ public final class ChannelSettings {
/** How long a channel outlives its last occupant. */
public enum Type {TEMPORARY, SEMI_PERMANENT, PERMANENT}
/** TeamSpeak's ceiling for {@code channel_delete_delay}, in seconds. */
public static final int MAX_DELETE_DELAY = 604800;
public int id;
public int parentId;
public String name = "";
@@ -1432,6 +1432,18 @@ public final class TeamspeakConnection implements TS3Listener {
});
}
/**
* Deletes a channel; with {@code force}, also one that has sub-channels or clients in it.
*
* @param callback given {@code null} on success, or the failure message
*/
public void deleteChannel(int channelId, boolean force, Consumer<String> callback) {
run((ignored, error) -> callback.accept(error), () -> {
channels.delete(channelId, force);
return null;
});
}
/** The ids of the icons uploaded to this virtual server. */
public void requestServerIcons(BiConsumer<List<Long>, String> callback) {
run(callback, channels::listIcons);
@@ -630,6 +630,29 @@ public final class ServerSession {
return hasPower("i_client_ban_power");
}
public boolean canCreateChannels() {
return permitsAny("b_channel_create_temporary", "b_channel_create_semi_permanent",
"b_channel_create_permanent");
}
public boolean canEditChannels() {
return permitsAny("b_channel_modify_name", "b_channel_modify_topic", "b_channel_modify_description",
"b_channel_modify_password", "b_channel_modify_codec", "b_channel_modify_maxclients");
}
public boolean canDeleteChannels() {
return permitsAny("b_channel_delete_temporary", "b_channel_delete_semi_permanent",
"b_channel_delete_permanent");
}
private boolean permitsAny(String... permissions) {
if (!conn.isConnected()) return false;
for (String p : permissions) {
if (conn.getModel().permits(p)) return true;
}
return false;
}
/**
* Whether we have any of a power; whether it beats the client's needed power only the
* server knows, so it is left to refuse.
@@ -28,12 +28,9 @@ import java.awt.Insets;
*/
final class ChannelAdvancedPanel extends JPanel implements ChannelDialog.Tab {
/** TeamSpeak's ceiling for {@code channel_delete_delay}, in seconds. */
private static final int MAX_DELETE_DELAY = 604800;
private final JTextField phoneticName = new JTextField();
private final JSpinner deleteDelay =
Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, MAX_DELETE_DELAY, 1)));
Spinners.compact(new JSpinner(new SpinnerNumberModel(0, 0, ChannelSettings.MAX_DELETE_DELAY, 1)));
private final JButton deleteDelayMax = new JButton("max");
private final JCheckBox encrypted = new JCheckBox("Voice Data encrypted");
@@ -55,7 +52,7 @@ final class ChannelAdvancedPanel extends JPanel implements ChannelDialog.Tab {
deleteDelay.setToolTipText("<html><p>Delay in seconds after temporary channels are deleted"
+ " after the last user left the channel.</p></html>");
deleteDelayMax.setToolTipText("Set delete delay to maximum value");
deleteDelayMax.addActionListener(a -> deleteDelay.setValue(MAX_DELETE_DELAY));
deleteDelayMax.addActionListener(a -> deleteDelay.setValue(ChannelSettings.MAX_DELETE_DELAY));
encrypted.setToolTipText("Voice data in this channel will be encrypted.");
ButtonGroup users = new ButtonGroup();
@@ -105,7 +102,7 @@ final class ChannelAdvancedPanel extends JPanel implements ChannelDialog.Tab {
@Override
public void read(ChannelSettings settings) {
phoneticName.setText(settings.phoneticName);
deleteDelay.setValue(Math.min(MAX_DELETE_DELAY, Math.max(0, settings.deleteDelay)));
deleteDelay.setValue(Math.min(ChannelSettings.MAX_DELETE_DELAY, Math.max(0, settings.deleteDelay)));
encrypted.setSelected(settings.encrypted);
if (settings.maxClientsUnlimited) maxUsersUnlimited.setSelected(true);
@@ -2,6 +2,7 @@ package com.ts3client.ui;
import com.formdev.flatlaf.util.ScaledEmptyBorder;
import com.formdev.flatlaf.util.UIScale;
import com.ts3client.net.ChannelCodec;
import com.ts3client.net.ChannelSettings;
import javax.swing.BorderFactory;
@@ -24,27 +25,11 @@ import java.awt.Insets;
*/
final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab {
/** Codec names in TeamSpeak's own id order, which is what the combo box index is. */
private static final String[] CODEC_NAMES = {
"Speex Narrowband", "Speex Wideband", "Speex Ultra-Wideband",
"CELT Mono", "Opus Voice", "Opus Music"};
/**
* Bandwidth per talking client in KiB/s at quality 0 and 10, per codec, as published by
* TeamSpeak. The steps in between are interpolated: the client shows a figure per
* quality step, and only the two ends of each codec's range are documented.
*/
private static final double[][] BANDWIDTH_RANGE = {
{2.49, 5.22}, {2.69, 7.37}, {2.73, 7.57}, {6.10, 13.92}, {2.73, 7.71}, {3.08, 11.87}};
private static final int CODEC_OPUS_VOICE = 4;
private static final int CODEC_OPUS_MUSIC = 5;
private final JRadioButton voiceMobile = new JRadioButton("Voice Mobile");
private final JRadioButton voiceDesktop = new JRadioButton("Voice Desktop");
private final JRadioButton music = new JRadioButton("Music");
private final JRadioButton custom = new JRadioButton("Custom");
private final JComboBox<String> codec = new JComboBox<>(CODEC_NAMES);
private final JComboBox<String> codec = new JComboBox<>(ChannelCodec.NAMES);
private final JSlider quality = new JSlider(0, 10, 6);
private final JLabel qualityValue = new JLabel("6");
private final JLabel bandwidth = new JLabel();
@@ -59,9 +44,9 @@ final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab {
presets.add(voiceDesktop);
presets.add(music);
presets.add(custom);
voiceMobile.addActionListener(a -> applyPreset(CODEC_OPUS_VOICE, 4));
voiceDesktop.addActionListener(a -> applyPreset(CODEC_OPUS_VOICE, 6));
music.addActionListener(a -> applyPreset(CODEC_OPUS_MUSIC, 6));
voiceMobile.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_MOBILE));
voiceDesktop.addActionListener(a -> applyPreset(ChannelCodec.Preset.VOICE_DESKTOP));
music.addActionListener(a -> applyPreset(ChannelCodec.Preset.MUSIC));
custom.addActionListener(a -> setCustomEnabled(true));
codec.addActionListener(a -> updateBandwidth());
@@ -77,12 +62,15 @@ final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab {
@Override
public void read(ChannelSettings settings) {
codec.setSelectedIndex(Math.max(0, Math.min(CODEC_NAMES.length - 1, settings.codec)));
quality.setValue(Math.max(0, Math.min(10, settings.codecQuality)));
if (settings.codec == CODEC_OPUS_VOICE && settings.codecQuality == 4) voiceMobile.setSelected(true);
else if (settings.codec == CODEC_OPUS_VOICE && settings.codecQuality == 6) voiceDesktop.setSelected(true);
else if (settings.codec == CODEC_OPUS_MUSIC && settings.codecQuality == 6) music.setSelected(true);
else custom.setSelected(true);
codec.setSelectedIndex(ChannelCodec.clampCodec(settings.codec));
quality.setValue(Math.max(0, Math.min(ChannelCodec.MAX_QUALITY, settings.codecQuality)));
ChannelCodec.Preset preset = ChannelCodec.Preset.of(settings.codec, settings.codecQuality);
if (preset == null) custom.setSelected(true);
else switch (preset) {
case VOICE_MOBILE -> voiceMobile.setSelected(true);
case VOICE_DESKTOP -> voiceDesktop.setSelected(true);
case MUSIC -> music.setSelected(true);
}
setCustomEnabled(custom.isSelected());
updateBandwidth();
}
@@ -93,9 +81,9 @@ final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab {
settings.codecQuality = quality.getValue();
}
private void applyPreset(int codecId, int qualityValue) {
codec.setSelectedIndex(codecId);
quality.setValue(qualityValue);
private void applyPreset(ChannelCodec.Preset preset) {
codec.setSelectedIndex(preset.codec);
quality.setValue(preset.quality);
setCustomEnabled(false);
updateBandwidth();
}
@@ -107,10 +95,7 @@ final class ChannelAudioPanel extends JPanel implements ChannelDialog.Tab {
private void updateBandwidth() {
qualityValue.setText(Integer.toString(quality.getValue()));
int index = Math.max(0, Math.min(BANDWIDTH_RANGE.length - 1, codec.getSelectedIndex()));
double[] range = BANDWIDTH_RANGE[index];
double value = range[0] + (range[1] - range[0]) * quality.getValue() / 10.0;
bandwidth.setText(String.format("%.2f KiB/s", value));
bandwidth.setText(ChannelCodec.bandwidthText(codec.getSelectedIndex(), quality.getValue()));
}
private JPanel presetBox() {
@@ -32,6 +32,9 @@ final class ChannelMenu {
JMenuItem edit = new JMenuItem("Edit Channel", Icons.of("CHANNEL_EDIT"));
edit.addActionListener(a -> actions.editChannel(channel));
menu.add(edit);
JMenuItem delete = new JMenuItem("Delete Channel", Icons.of("CHANNEL_DELETE"));
delete.addActionListener(a -> actions.deleteChannel(channel));
menu.add(delete);
menu.addSeparator();
addSubscriptionItems(menu, channel, actions);
JMenuItem files = new JMenuItem("Browse files", Icons.of("FILETRANSFER"));
@@ -297,6 +297,23 @@ final class ServerTabTreeActions implements ServerTreePanel.Actions {
ChannelDialog.toEdit(host, conn, groupIcons, channel).setVisible(true);
}
@Override
public void deleteChannel(ChannelNode channel) {
if (!conn.isConnected()) return;
// Like TeamSpeak, a channel that is not empty takes its sub-channels along and sends its clients away.
boolean occupied = !channel.children.isEmpty() || !channel.clients.isEmpty();
String question = "Delete channel \"" + channel.name + "\""
+ (occupied ? " with its sub-channels and the clients in it?" : "?");
if (JOptionPane.showConfirmDialog(host, question, "Delete Channel", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
return;
}
conn.deleteChannel(channel.id, true, error -> {
if (error != null) SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(host,
"Could not delete the channel: " + error, "Error", JOptionPane.ERROR_MESSAGE));
});
}
@Override
public void createChannel(ChannelNode parent, ChannelSettings.Type type) {
if (!conn.isConnected()) return;
@@ -65,6 +65,8 @@ public final class ServerTreePanel extends JPanel {
/** Opens the channel editor for a channel. */
void editChannel(ChannelNode channel);
void deleteChannel(ChannelNode channel);
/**
* Opens the channel creator.
*