Settings values are Setting<T>: one key each, change listeners

Each setting is declared once with its key, type and range, and loaded
and saved from that list. Output device, volume and receive buffer, the
status bar and the master volume slider take effect through listeners
instead of calls wherever they change; Android does the same for output
settings and country flags. The Playback page previews voice volume with
the master volume applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 22:53:37 +00:00
co-authored by Claude Opus 5.5
parent bbe741d5cf
commit 203082d040
55 changed files with 581 additions and 615 deletions
@@ -43,7 +43,7 @@ class IconTheme(private val context: Context, private val settings: Settings) {
} }
fun select(pack: IconPack) { fun select(pack: IconPack) {
settings.iconPack = pack.id() settings.iconPack.set(pack.id())
settings.save() settings.save()
reload() reload()
} }
@@ -100,7 +100,7 @@ class IconTheme(private val context: Context, private val settings: Settings) {
private fun reload() { private fun reload() {
val packs = IconPacks.findAll(folder, null) val packs = IconPacks.findAll(folder, null)
val active = IconPacks.select(packs, settings.iconPack) ?: material val active = IconPacks.select(packs, settings.iconPack.get()) ?: material
lookupOrder = IconPacks.lookupOrder(active, packs, material) lookupOrder = IconPacks.lookupOrder(active, packs, material)
cache.evictAll() cache.evictAll()
_packs.value = packs _packs.value = packs
@@ -61,7 +61,7 @@ class IdentityManager(
} }
private fun snapshot(): List<IdentityInfo> = store.all().map { private fun snapshot(): List<IdentityInfo> = store.all().map {
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId, IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId.get(),
it.nickname, it.phoneticNickname) it.nickname, it.phoneticNickname)
} }
@@ -93,9 +93,9 @@ class IdentityManager(
/** Makes [entry], or else the first identity, the default while there is none. */ /** Makes [entry], or else the first identity, the default while there is none. */
private fun adoptDefault(entry: IdentityEntry?) { private fun adoptDefault(entry: IdentityEntry?) {
if (store.byId(settings.defaultIdentityId) != null) return if (store.byId(settings.defaultIdentityId.get()) != null) return
val fallback = entry ?: store.all().firstOrNull() ?: return val fallback = entry ?: store.all().firstOrNull() ?: return
settings.defaultIdentityId = fallback.id settings.defaultIdentityId.set(fallback.id)
settings.save() settings.save()
} }
@@ -124,10 +124,10 @@ class IdentityManager(
/** The nickname of the identity a connect with [id] uses; empty when it has none. */ /** The nickname of the identity a connect with [id] uses; empty when it has none. */
fun nicknameOf(id: String): String = fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty() (store.byId(id) ?: store.byId(settings.defaultIdentityId.get()))?.nickname.orEmpty()
fun setDefault(id: String) { fun setDefault(id: String) {
settings.defaultIdentityId = id settings.defaultIdentityId.set(id)
settings.save() settings.save()
refresh() refresh()
} }
@@ -90,6 +90,8 @@ class LevelMonitor(private val settings: Settings, private val audio: AudioBacke
} }
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */ /** Push-to-talk would never open without the button, and the test is there to tune the gate. */
private fun testMode() = private fun testMode(): Settings.InputMode {
if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode val mode = settings.inputMode.get()
return if (mode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else mode
}
} }
@@ -467,7 +467,7 @@ class ServerController internal constructor(
away = session.isAway, away = session.isAway,
selfClientId = if (session.isConnected) session.selfClientId() else 0, selfClientId = if (session.isConnected) session.selfClientId() else 0,
channelId = if (session.isConnected) self?.channelId ?: 0 else 0, channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
inputMode = app.settings.inputMode, inputMode = app.settings.inputMode.get(),
hostButton = if (session.isConnected) session.model().hostButton() else null, hostButton = if (session.isConnected) session.model().hostButton() else null,
self = session.selfState(), self = session.selfState(),
whisper = session.whisper()?.label, whisper = session.whisper()?.label,
@@ -489,8 +489,8 @@ class ServerController internal constructor(
delay(TREE_FRAME_MS) delay(TREE_FRAME_MS)
treePending.set(false) treePending.set(false)
if (structureChanged.getAndSet(false)) roots = session.model().buildTree() if (structureChanged.getAndSet(false)) roots = session.model().buildTree()
_tree.value = ServerTree.of(roots, session.model(), session.contacts().store(), app.settings.colorContacts, _tree.value = ServerTree.of(roots, session.model(), session.contacts().store(),
app.settings.countryFlags, app.settings.clientRowColors) app.settings.colorContacts.get(), app.settings.countryFlags.get(), app.settings.clientRowColors)
val serverName = if (session.isConnected) session.model().serverName.orEmpty() else "" val serverName = if (session.isConnected) session.model().serverName.orEmpty() else ""
val channelName = session.currentChannel()?.name.orEmpty() val channelName = session.currentChannel()?.name.orEmpty()
_chats.update { _chats.update {
@@ -508,7 +508,7 @@ class ServerController internal constructor(
override fun onSystemMessage(text: String) = system(text) override fun onSystemMessage(text: String) = system(text)
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) { override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) {
val self = session.model().getClient(session.selfClientId())?.nickname ?: app.settings.nickname val self = session.model().getClient(session.selfClientId())?.nickname ?: app.settings.nickname.get()
val html = ChatHtml.message(session.selfClientId(), session.selfUniqueId(), "$self (you)", text, room) val html = ChatHtml.message(session.selfClientId(), session.selfUniqueId(), "$self (you)", text, room)
append(key(scope, peerClientId), peerName, html) append(key(scope, peerClientId), peerName, html)
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text))
@@ -15,6 +15,7 @@ import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists import eu.lixko.ts3j.client.config.WhisperLists
@@ -185,19 +186,21 @@ class SessionController(private val context: Context) {
_contacts.value = contactCopies() _contacts.value = contactCopies()
_servers.value.forEach(ServerController::contactsChanged) _servers.value.forEach(ServerController::contactsChanged)
} }
Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer)
settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } }
} }
/** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */ /** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */
fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname } fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname.get() }
val lastAddress: String get() = settings.lastAddress val lastAddress: String get() = settings.lastAddress.get()
// ---- connection ---- // ---- connection ----
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */ /** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") { fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
val (host, port) = parseAddress(address) val (host, port) = parseAddress(address)
settings.lastAddress = address settings.lastAddress.set(address)
if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname if (identities.nicknameOf(identityId).isBlank()) settings.nickname.set(nickname)
settings.save() settings.save()
start(host, port, nickname, password, identityId, "", "") start(host, port, nickname, password, identityId, "", "")
} }
@@ -532,9 +535,8 @@ class SessionController(private val context: Context) {
val soundPack: SoundPack? get() = sounds.pack() val soundPack: SoundPack? get() = sounds.pack()
fun setCountryFlags(shown: Boolean) { fun setCountryFlags(shown: Boolean) {
settings.countryFlags = shown settings.countryFlags.set(shown)
settings.save() settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
} }
/** Puts new client row colours, already set in [settings], into effect. */ /** Puts new client row colours, already set in [settings], into effect. */
@@ -544,7 +546,7 @@ class SessionController(private val context: Context) {
} }
fun setDescriptionPictures(shown: Boolean) { fun setDescriptionPictures(shown: Boolean) {
settings.descriptionPictures = shown settings.descriptionPictures.set(shown)
settings.save() settings.save()
} }
@@ -598,21 +600,17 @@ class SessionController(private val context: Context) {
/** Switches between push to talk and voice activation; returns the new mode. */ /** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode { fun toggleInputMode(): Settings.InputMode {
settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK)
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK)
applySettings() applySettings()
return settings.inputMode return settings.inputMode.get()
} }
/** Saves the settings and puts the voice and device ones into effect at once. */ /** Saves the settings and puts the voice ones into effect at once. */
fun applySettings() { fun applySettings() {
settings.save() settings.save()
soundPlayer.setOutputDevice(settings.outputDevice)
try { try {
for (server in _servers.value) { for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume)
server.playback?.setOutputDevice(settings.outputDevice)
server.playback?.setReceiveBuffer(settings.receiveBuffer)
server.microphone?.apply(settings) server.microphone?.apply(settings)
server.refresh() server.refresh()
server.scheduleTree(structure = false) server.scheduleTree(structure = false)
@@ -623,6 +621,16 @@ class SessionController(private val context: Context) {
} }
} }
/** Output device, volume and receive buffer are global, so they go to every connection. */
private fun applyOutputSettings() {
soundPlayer.setOutputDevice(settings.outputDevice.get())
for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume.get())
server.playback?.setOutputDevice(settings.outputDevice.get())
server.playback?.setReceiveBuffer(settings.receiveBuffer.get())
}
}
/** Microphone preset and playback usage; the open lines move over at once. */ /** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) { fun setRoute(route: AudioRoute) {
routePrefs.save(route) routePrefs.save(route)
@@ -39,7 +39,7 @@ class WebPictures(cacheDir: File, private val settings: Settings) {
fun retryFailed() = downloads.retryFailed() fun retryFailed() = downloads.retryFailed()
/** Whether pictures are shown at all, rather than links to them. */ /** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures val enabled: Boolean get() = settings.descriptionPictures.get()
suspend fun state(url: String): State { suspend fun state(url: String): State {
decoded.get(url)?.let { return State.Shown(it) } decoded.get(url)?.let { return State.Shown(it) }
@@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.roundToInt import kotlin.math.roundToInt
@@ -23,56 +24,56 @@ private const val MAX_BITRATE_KBITS = 160f
@Composable @Composable
fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) {
val settings = vm.settings val settings = vm.settings
fun change(edit: Settings.() -> Unit) { fun <T> change(setting: Setting<T>, value: T) {
settings.edit() setting.set(value)
vm.applySettings() vm.applySettings()
} }
var vbr by remember { mutableStateOf(settings.vbr) } var vbr by remember { mutableStateOf(settings.vbr.get()) }
var fec by remember { mutableStateOf(settings.fec) } var fec by remember { mutableStateOf(settings.fec.get()) }
var music by remember { mutableStateOf(settings.music) } var music by remember { mutableStateOf(settings.music.get()) }
var redundancy by remember { mutableStateOf(settings.redundancyDelay) } var redundancy by remember { mutableStateOf(settings.redundancyDelay.get()) }
var copies by remember { mutableStateOf(settings.redundancyCopies) } var copies by remember { mutableStateOf(settings.redundancyCopies.get()) }
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) } var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer.get()) }
SubScreen("Network", onBack) { padding -> SubScreen("Network", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Encoder") Section("Encoder")
Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { Level("Bitrate", settings.bitrate.get() / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
change { bitrate = it.roundToInt() * 1000 } change(settings.bitrate, it.roundToInt() * 1000)
} }
Toggle("Variable bitrate (VBR)", vbr) { Toggle("Variable bitrate (VBR)", vbr) {
vbr = it vbr = it
change { this.vbr = it } change(settings.vbr, it)
} }
Toggle("Forward error correction (FEC)", fec) { Toggle("Forward error correction (FEC)", fec) {
fec = it fec = it
change { this.fec = it } change(settings.fec, it)
} }
Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { Level("Complexity", settings.complexity.get().toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
change { complexity = it.roundToInt() } change(settings.complexity, it.roundToInt())
} }
Toggle("Music codec (stereo, higher fidelity)", music) { Toggle("Music codec (stereo, higher fidelity)", music) {
music = it music = it
change { this.music = it } change(settings.music, it)
} }
Section("Redundancy") Section("Redundancy")
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) { ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
redundancy = it redundancy = it
change { redundancyDelay = it } change(settings.redundancyDelay, it)
} }
if (redundancy > 0) { if (redundancy > 0) {
Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" }, Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" },
steps = Settings.MAX_REDUNDANCY_COPIES - 2) { steps = Settings.MAX_REDUNDANCY_COPIES - 2) {
copies = it.roundToInt() copies = it.roundToInt()
change { redundancyCopies = copies } change(settings.redundancyCopies, copies)
} }
} }
Section("Receive") Section("Receive")
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) { ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
receiveBuffer = it receiveBuffer = it
change { this.receiveBuffer = it } change(settings.receiveBuffer, it)
} }
} }
} }
@@ -72,13 +72,13 @@ private fun DesignScreen(vm: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding -> SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(vm.icons) IconPackPicker(vm.icons)
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) } var pictures by remember { mutableStateOf(vm.settings.descriptionPictures.get()) }
Toggle("Show pictures in descriptions", pictures) { Toggle("Show pictures in descriptions", pictures) {
pictures = it pictures = it
vm.setDescriptionPictures(it) vm.setDescriptionPictures(it)
} }
Section("Channel tree") Section("Channel tree")
var flags by remember { mutableStateOf(vm.settings.countryFlags) } var flags by remember { mutableStateOf(vm.settings.countryFlags.get()) }
Toggle("Show country flags in the channel tree", flags) { Toggle("Show country flags in the channel tree", flags) {
flags = it flags = it
vm.setCountryFlags(it) vm.setCountryFlags(it)
@@ -35,6 +35,7 @@ import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.audio.AudioRoute import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.audio.InputLevel import eu.lixko.ts3j.client.audio.InputLevel
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import kotlin.math.roundToInt import kotlin.math.roundToInt
@@ -44,17 +45,17 @@ private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB")
@Composable @Composable
fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
val settings = vm.settings val settings = vm.settings
fun change(edit: Settings.() -> Unit) { fun <T> change(setting: Setting<T>, value: T) {
settings.edit() setting.set(value)
vm.applySettings() vm.applySettings()
} }
var inputMode by remember { mutableStateOf(settings.inputMode) } var inputMode by remember { mutableStateOf(settings.inputMode.get()) }
var vadMode by remember { mutableStateOf(settings.vadMode) } var vadMode by remember { mutableStateOf(settings.vadMode.get()) }
var agc by remember { mutableStateOf(settings.agc) } var agc by remember { mutableStateOf(settings.agc.get()) }
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) } var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning.get()) }
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) } var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) }
var inputDevice by remember { mutableStateOf(settings.inputDevice) } var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) }
var outputDevice by remember { mutableStateOf(settings.outputDevice) } var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) }
val inputs by vm.inputDevices.collectAsStateWithLifecycle() val inputs by vm.inputDevices.collectAsStateWithLifecycle()
val outputs by vm.outputDevices.collectAsStateWithLifecycle() val outputs by vm.outputDevices.collectAsStateWithLifecycle()
val route by vm.route.collectAsStateWithLifecycle() val route by vm.route.collectAsStateWithLifecycle()
@@ -71,11 +72,11 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
Section("Devices") Section("Devices")
DevicePicker("Microphone", inputs, inputDevice) { DevicePicker("Microphone", inputs, inputDevice) {
inputDevice = it inputDevice = it
change { this.inputDevice = it } change(settings.inputDevice, it)
} }
DevicePicker("Speaker", outputs, outputDevice) { DevicePicker("Speaker", outputs, outputDevice) {
outputDevice = it outputDevice = it
change { this.outputDevice = it } change(settings.outputDevice, it)
} }
Picker( Picker(
"Microphone preset", "Microphone preset",
@@ -95,7 +96,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
for ((mode, label) in INPUT_MODES) { for ((mode, label) in INPUT_MODES) {
Choice(label, inputMode == mode) { Choice(label, inputMode == mode) {
inputMode = mode inputMode = mode
change { this.inputMode = mode } change(settings.inputMode, mode)
} }
} }
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm) if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm)
@@ -110,46 +111,45 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
for ((mode, label) in VAD_MODES) { for ((mode, label) in VAD_MODES) {
Choice(label, vadMode == mode) { Choice(label, vadMode == mode) {
vadMode = mode vadMode = mode
change { this.vadMode = mode } change(settings.vadMode, mode)
} }
} }
if (vadMode != Settings.VadMode.AUTOMATIC) { if (vadMode != Settings.VadMode.AUTOMATIC) {
Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" }, Level("Volume threshold", settings.vadThresholdDb.get().toFloat(), -50f..50f, { "${it.roundToInt()}" },
onChange = { threshold = it }) { onChange = { threshold = it }) {
change { vadThresholdDb = it.roundToInt().toDouble() } change(settings.vadThresholdDb, it.roundToInt().toDouble())
} }
} }
if (vadMode != Settings.VadMode.VOLUME_GATE) { if (vadMode != Settings.VadMode.VOLUME_GATE) {
Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { Level("Speech likelihood", settings.speechThreshold.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { speechThreshold = it.toDouble() } change(settings.speechThreshold, it.toDouble())
} }
} }
} }
Section("Processing") Section("Processing")
val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0 val suppression = if (settings.denoise.get()) settings.denoiserLevel.get() + 1 else 0
Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(), Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(),
{ DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) { { DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) {
val step = it.roundToInt() val step = it.roundToInt()
change { settings.denoise.set(step > 0)
denoise = step > 0 if (step > 0) settings.denoiserLevel.set(step - 1)
if (step > 0) denoiserLevel = step - 1 vm.applySettings()
}
} }
Toggle("Automatic gain control", agc) { Toggle("Automatic gain control", agc) {
agc = it agc = it
change { this.agc = it } change(settings.agc, it)
} }
if (agc) { if (agc) {
Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(), Level("Boost quiet speech", settings.agcBoostDb.get().toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) { { "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
change { agcBoostDb = it.roundToInt() } change(settings.agcBoostDb, it.roundToInt())
} }
} }
Section("Playback") Section("Playback")
Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { Level("Volume", settings.outputVolume.get().toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
change { outputVolume = it.toDouble() } change(settings.outputVolume, it.toDouble())
} }
Section("Notification sounds") Section("Notification sounds")
@@ -161,12 +161,12 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
pack = id pack = id
} }
} }
Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { Level("Volume", settings.soundVolume.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { soundVolume = it.toDouble() } change(settings.soundVolume, it.toDouble())
} }
Toggle("Beep when talking while muted", mutedTalkWarning) { Toggle("Beep when talking while muted", mutedTalkWarning) {
mutedTalkWarning = it mutedTalkWarning = it
change { this.mutedTalkWarning = it } change(settings.mutedTalkWarning, it)
} }
} }
} }
+2 -2
View File
@@ -18,8 +18,8 @@ Items are worked through in the order below. Status: open, done (commit), or clo
| 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | done (`9107bdd`): `OwnClient` owns the devices and our flags, and publishes them; `Recording` the recorder. `ServerSession` no longer keeps its own copy of the flags, and they are cleared when a connect starts rather than once it is done | | 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | done (`9107bdd`): `OwnClient` owns the devices and our flags, and publishes them; `Recording` the recorder. `ServerSession` no longer keeps its own copy of the flags, and they are cleared when a connect starts rather than once it is done |
| 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | done (`de42429`): `connection()` is gone; frontends reach the model, our ids, devices and the helpers through `ServerSession`. New helpers took the remaining actions off the connection: `ClientAdmin` (move, kick, ban, groups, talk power, poke, details), `ChannelFiles`, `ClientContacts`; `ChannelAdmin` also joins, moves and subscribes. Dialogs take the session, or only the helper they use | | 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | done (`de42429`): `connection()` is gone; frontends reach the model, our ids, devices and the helpers through `ServerSession`. New helpers took the remaining actions off the connection: `ClientAdmin` (move, kick, ban, groups, talk power, poke, details), `ChannelFiles`, `ClientContacts`; `ChannelAdmin` also joins, moves and subscribes. Dialogs take the session, or only the helper they use |
| 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (`f7cf040`): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray | | 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (`f7cf040`): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray |
| 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding || done (`e214f21`): the five extend `AbstractServerListDialog`, which lays out the toolbar, list, status line and Reload/Close, follows the server's name, binds F5/Ctrl+W/Escape, guards loading, reloads after a change and reports its failure; `ServerTab` keeps them in one map. All five now take F5, show load failures in red, and keep the status line's height; the ban list's own placeholder field is FlatLaf's. The table models stay per dialog: their rows and columns share nothing | | 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding | done (`e214f21`): the five extend `AbstractServerListDialog`, which lays out the toolbar, list, status line and Reload/Close, follows the server's name, binds F5/Ctrl+W/Escape, guards loading, reloads after a change and reports its failure; `ServerTab` keeps them in one map. All five now take F5, show load failures in red, and keep the status line's height; the ban list's own placeholder field is FlatLaf's. The table models stay per dialog: their rows and columns share nothing |
| 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | open | | 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | done: each value is a `Setting<T>` (`get`/`set`, listeners), declared once with its key, type and range, and loaded and saved from that list. Output device, volume and receive buffer reach every connection, and the status bar and master volume slider follow their toggles, through listeners instead of calls at each place that changes them; Android puts output settings and country flags into effect the same way. `SplitRatio` takes the setting itself. The sections with their own load/store (row colours, server log, notifications, contact defaults) are unchanged. The Playback page now previews the voice volume with the master volume applied, as Apply sets it |
| 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | open | | 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | open |
| 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | open | | 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | open |
| 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open | | 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | open |
@@ -24,12 +24,12 @@ public interface AudioBackend {
} }
default VoiceOutput createOutput(Settings settings) { default VoiceOutput createOutput(Settings settings) {
return new StreamingVoiceOutput(io(), opus(), settings.outputDevice, outputLines()); return new StreamingVoiceOutput(io(), opus(), settings.outputDevice.get(), outputLines());
} }
/** Player for notification sounds (sound packs); shared by all connections. */ /** Player for notification sounds (sound packs); shared by all connections. */
default SoundPlayer createSoundPlayer(Settings settings) { default SoundPlayer createSoundPlayer(Settings settings) {
return new PackSoundPlayer(io(), opus(), settings.outputDevice); return new PackSoundPlayer(io(), opus(), settings.outputDevice.get());
} }
/** Human-readable codec/backend description, e.g. for an "about" line. */ /** Human-readable codec/backend description, e.g. for an "about" line. */
@@ -103,21 +103,21 @@ public final class CaptureVoiceInput implements VoiceInput {
public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) { public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) {
this.io = io; this.io = io;
this.opus = opus; this.opus = opus;
this.deviceName = settings.inputDevice; this.deviceName = settings.inputDevice.get();
this.mode = settings.inputMode; this.mode = settings.inputMode.get();
this.vadMode = settings.vadMode; this.vadMode = settings.vadMode.get();
this.thresholdDb = settings.vadThresholdDb; this.thresholdDb = settings.vadThresholdDb.get();
this.speechThreshold = settings.speechThreshold; this.speechThreshold = settings.speechThreshold.get();
this.vadOverPtt = settings.vadOverPtt; this.vadOverPtt = settings.vadOverPtt.get();
this.inputGain = settings.inputVolume; this.inputGain = settings.inputVolume.get();
this.params = OpusParameters.from(settings); this.params = OpusParameters.from(settings);
this.codec = codecFor(params); this.codec = codecFor(params);
setRedundancy(settings.redundancyDelay, settings.redundancyCopies); setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get());
processor.setNoiseSuppression(settings.denoise); processor.setNoiseSuppression(settings.denoise.get());
processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel)); processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel.get()));
processor.setTransientSuppression(settings.typingAttenuation); processor.setTransientSuppression(settings.typingAttenuation.get());
processor.setGainControl(settings.agc); processor.setGainControl(settings.agc.get());
processor.setGainBoost(settings.agcBoostDb); processor.setGainBoost(settings.agcBoostDb.get());
} }
// ---- live configuration (safe to call from the UI thread) ---- // ---- live configuration (safe to call from the UI thread) ----
@@ -9,7 +9,8 @@ import eu.lixko.ts3j.client.config.Settings;
public final class OpusParameters { public final class OpusParameters {
public static OpusParameters from(Settings s) { public static OpusParameters from(Settings s) {
return new OpusParameters(s.bitrate, s.complexity, s.vbr, s.fec, s.packetLoss, s.music); return new OpusParameters(s.bitrate.get(), s.complexity.get(), s.vbr.get(), s.fec.get(), s.packetLoss.get(),
s.music.get());
} }
/** Target bitrate in bits per second. */ /** Target bitrate in bits per second. */
@@ -92,19 +92,19 @@ public interface VoiceInput extends Microphone {
/** Takes on the voice settings, as they stand now, while capturing. */ /** Takes on the voice settings, as they stand now, while capturing. */
default void apply(Settings settings) { default void apply(Settings settings) {
setInputDevice(settings.inputDevice); setInputDevice(settings.inputDevice.get());
setMode(settings.inputMode); setMode(settings.inputMode.get());
setVadMode(settings.vadMode); setVadMode(settings.vadMode.get());
setThresholdDb(settings.vadThresholdDb); setThresholdDb(settings.vadThresholdDb.get());
setSpeechThreshold(settings.speechThreshold); setSpeechThreshold(settings.speechThreshold.get());
setVadOverPtt(settings.vadOverPtt); setVadOverPtt(settings.vadOverPtt.get());
setInputGain(settings.inputVolume); setInputGain(settings.inputVolume.get());
setNoiseSuppression(settings.denoise); setNoiseSuppression(settings.denoise.get());
setDenoiserLevel(settings.denoiserLevel); setDenoiserLevel(settings.denoiserLevel.get());
setTypingAttenuation(settings.typingAttenuation); setTypingAttenuation(settings.typingAttenuation.get());
setAgc(settings.agc); setAgc(settings.agc.get());
setAgcBoost(settings.agcBoostDb); setAgcBoost(settings.agcBoostDb.get());
setOpusParameters(OpusParameters.from(settings)); setOpusParameters(OpusParameters.from(settings));
setRedundancy(settings.redundancyDelay, settings.redundancyCopies); setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get());
} }
} }
@@ -117,10 +117,10 @@ public final class IdentityStore {
IdentityEntry e = byId(preferredId); IdentityEntry e = byId(preferredId);
if (e != null) return e; if (e != null) return e;
e = byId(settings.defaultIdentityId); e = byId(settings.defaultIdentityId.get());
if (e == null) { if (e == null) {
e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0); e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0);
settings.defaultIdentityId = e.getId(); settings.defaultIdentityId.set(e.getId());
settings.save(); settings.save();
} }
return e; return e;
@@ -197,8 +197,8 @@ public final class IdentityStore {
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
entry.getFile().delete(); entry.getFile().delete();
if (entry.getId().equals(settings.defaultIdentityId)) { if (entry.getId().equals(settings.defaultIdentityId.get())) {
settings.defaultIdentityId = entries.isEmpty() ? "" : entries.get(0).getId(); settings.defaultIdentityId.set(entries.isEmpty() ? "" : entries.get(0).getId());
settings.save(); settings.save();
} }
if (bookmarks != null) { if (bookmarks != null) {
@@ -0,0 +1,78 @@
package eu.lixko.ts3j.client.config;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/**
* One value of {@link Settings}: its key in the settings file, how it is written there, and who
* to tell when it changes. Listeners run on the thread that sets the value.
*/
public final class Setting<T> {
private final String key;
private final Function<String, T> parse;
private final Function<T, String> format;
private final UnaryOperator<T> constrain;
private final List<Consumer<? super T>> listeners = new CopyOnWriteArrayList<>();
private volatile T value;
/**
* @param parse reads the file's text; throws {@link IllegalArgumentException} for text it
* can't read, which keeps the default
* @param constrain brings a value into range, both when read and when set
*/
Setting(String key, T initial, Function<String, T> parse, Function<T, String> format, UnaryOperator<T> constrain) {
this.key = key;
this.parse = parse;
this.format = format;
this.constrain = constrain;
this.value = initial;
}
public String key() {
return key;
}
public T get() {
return value;
}
public void set(T newValue) {
T constrained = constrain.apply(Objects.requireNonNull(newValue));
if (constrained.equals(value)) return;
value = constrained;
for (Consumer<? super T> listener : listeners) listener.accept(constrained);
}
public void addListener(Consumer<? super T> listener) {
listeners.add(listener);
}
public void removeListener(Consumer<? super T> listener) {
listeners.remove(listener);
}
/** Runs {@code action} whenever any of {@code settings} changes. */
public static void onAnyChange(Runnable action, Setting<?>... settings) {
for (Setting<?> setting : settings) setting.addListener(v -> action.run());
}
void load(Properties props) {
String text = props.getProperty(key);
if (text == null) return;
try {
value = constrain.apply(parse.apply(text));
} catch (IllegalArgumentException unreadable) {
// keeps the default
}
}
void store(Properties props) {
props.setProperty(key, format.apply(value));
}
}
@@ -1,5 +1,6 @@
package eu.lixko.ts3j.client.config; package eu.lixko.ts3j.client.config;
import eu.lixko.ts3j.client.audio.InputLevel;
import eu.lixko.ts3j.client.contacts.ContactDefaults; import eu.lixko.ts3j.client.contacts.ContactDefaults;
import eu.lixko.ts3j.client.sound.NotificationSettings; import eu.lixko.ts3j.client.sound.NotificationSettings;
@@ -7,15 +8,18 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/** /**
* Simple persistent settings backed by a properties file in the user's home * Simple persistent settings backed by a properties file in the user's home
* directory (~/.ts3jclient/settings.properties). * directory (~/.ts3jclient/settings.properties).
* *
* <p>Holds connection defaults, audio device selection and voice-activation * <p>Holds connection defaults, audio device selection and voice-activation
* parameters. Loaded once at startup and saved whenever the user changes * parameters. Loaded once at startup; whoever changes a {@link Setting} saves.
* something in the options dialog.
*/ */
public final class Settings { public final class Settings {
@@ -70,143 +74,147 @@ public final class Settings {
} }
private final Properties props = new Properties(); private final Properties props = new Properties();
private final List<Setting<?>> all = new ArrayList<>();
// ---- connection ---- // ---- connection ----
public String lastAddress = "localhost"; public final Setting<String> lastAddress = text("lastAddress", "localhost");
public String nickname = System.getProperty("user.name", "TS3j User"); public final Setting<String> nickname = text("nickname", System.getProperty("user.name", "TS3j User"));
public String serverPassword = ""; public final Setting<String> serverPassword = text("serverPassword", "");
/** Legacy single-identity file; only used to migrate into the identity store. */ /** Legacy single-identity file; only used to migrate into the identity store. */
public String identityFile = AppDirs.file("identity.ini").getAbsolutePath(); public final Setting<String> identityFile = text("identityFile", AppDirs.file("identity.ini").getAbsolutePath());
/** Id of the identity used when a server doesn't select one of its own. */ /** Id of the identity used when a server doesn't select one of its own. */
public String defaultIdentityId = ""; public final Setting<String> defaultIdentityId = text("defaultIdentityId", "");
// ---- reported client version ---- // ---- reported client version ----
/** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */ /** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */
public boolean customVersion = false; public final Setting<Boolean> customVersion = flag("customVersion", false);
/** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */ /** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */
public String clientVersion = ClientVersion.DEFAULT.version(); public final Setting<String> clientVersion = text("clientVersion", ClientVersion.DEFAULT.version());
/** Operating system other clients see, e.g. "Windows". */ /** Operating system other clients see, e.g. "Windows". */
public String clientPlatform = ClientVersion.DEFAULT.platform(); public final Setting<String> clientPlatform = text("clientPlatform", ClientVersion.DEFAULT.platform());
/** TeamSpeak's signature over the version and platform; servers may verify it. */ /** TeamSpeak's signature over the version and platform; servers may verify it. */
public String clientVersionSign = ClientVersion.DEFAULT.sign(); public final Setting<String> clientVersionSign = text("clientVersionSign", ClientVersion.DEFAULT.sign());
// ---- audio devices (mixer names; empty = system default) ---- // ---- audio devices (mixer names; empty = system default) ----
public String inputDevice = ""; public final Setting<String> inputDevice = text("inputDevice", "");
public String outputDevice = ""; public final Setting<String> outputDevice = text("outputDevice", "");
// ---- voice ---- // ---- voice ----
public InputMode inputMode = InputMode.VOICE_ACTIVATION; public final Setting<InputMode> inputMode = choice("inputMode", InputMode.VOICE_ACTIVATION);
/** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */ /** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */
public VadMode vadMode = VadMode.HYBRID; public final Setting<VadMode> vadMode = choice("vadMode", VadMode.HYBRID);
/** /**
* Volume-gate threshold on {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, the same one * Volume-gate threshold on {@link InputLevel}'s scale, the same one
* the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40. * the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40.
*/ */
public double vadThresholdDb = -40.0; public final Setting<Double> vadThresholdDb = decimal("vadLevelDb", -40.0);
/** /**
* Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this * Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this
* {@code vad_likelihood} and also defaults it to 0.5. * {@code vad_likelihood} and also defaults it to 0.5.
*/ */
public double speechThreshold = 0.5; public final Setting<Double> speechThreshold = decimal("speechThreshold", 0.5);
/** Keep voice activation running while in push-to-talk mode. */ /** Keep voice activation running while in push-to-talk mode. */
public boolean vadOverPtt = false; public final Setting<Boolean> vadOverPtt = flag("vadOverPtt", false);
/** Opus target bitrate in bits/sec. */ /** Opus target bitrate in bits/sec. */
public int bitrate = 48000; public final Setting<Integer> bitrate = number("bitrate", 48000);
/** Opus complexity 0..10. */ /** Opus complexity 0..10. */
public int complexity = 10; public final Setting<Integer> complexity = number("complexity", 10);
/** Opus variable bitrate. */ /** Opus variable bitrate. */
public boolean vbr = true; public final Setting<Boolean> vbr = flag("vbr", true);
/** Opus in-band forward error correction. */ /** Opus in-band forward error correction. */
public boolean fec = true; public final Setting<Boolean> fec = flag("fec", true);
/** Expected packet loss percent (drives FEC). */ /** Expected packet loss percent (drives FEC). */
public int packetLoss = 5; public final Setting<Integer> packetLoss = number("packetLoss", 5);
/** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */ /** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */
public boolean music = false; public final Setting<Boolean> music = flag("music", false);
/** /**
* Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off. * Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off.
* Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with * Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with
* about {@code redundancyDelay * redundancyCopies} of latency. * about {@code redundancyDelay * redundancyCopies} of latency.
*/ */
public int redundancyDelay = 0; public final Setting<Integer> redundancyDelay = number("redundancyDelay", 0);
/** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */ /** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */
public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200}; public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200};
/** How many times every voice packet is sent again. */ /** How many times every voice packet is sent again. */
public int redundancyCopies = 1; public final Setting<Integer> redundancyCopies = number("redundancyCopies", 1);
public static final int MAX_REDUNDANCY_COPIES = 4; public static final int MAX_REDUNDANCY_COPIES = 4;
/** /**
* Milliseconds of playback delay held on top of what the jitter buffer measures it needs, * Milliseconds of playback delay held on top of what the jitter buffer measures it needs,
* so late packets and error correction copies still make it on a bad connection. * so late packets and error correction copies still make it on a bad connection.
*/ */
public int receiveBuffer = 0; public final Setting<Integer> receiveBuffer = number("receiveBuffer", 0);
/** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */ /** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */
public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500}; public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500};
/** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */ /** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */
public double outputVolume = 1.0; public final Setting<Double> outputVolume = decimal("outputVolume", 1.0);
/** /**
* Global multiplier on top of {@link #outputVolume} and {@link #soundVolume}, * Global multiplier on top of {@link #outputVolume} and {@link #soundVolume},
* controlled from the toolbar's Master Volume slider so both can be ridden * controlled from the toolbar's Master Volume slider so both can be ridden
* with one control. 0..2, same boost headroom as the other volumes. * with one control. 0..2, same boost headroom as the other volumes.
*/ */
public double masterVolume = 1.0; public final Setting<Double> masterVolume = decimal("masterVolume", 1.0);
/** Microphone input gain multiplier applied before VAD/encode. */ /** Microphone input gain multiplier applied before VAD/encode. */
public double inputVolume = 1.0; public final Setting<Double> inputVolume = decimal("inputVolume", 1.0);
/** Remove steady background noise from the microphone (WebRTC noise suppression). */ /** Remove steady background noise from the microphone (WebRTC noise suppression). */
public boolean denoise = true; public final Setting<Boolean> denoise = flag("denoise", true);
/** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */ /** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */
public int denoiserLevel = 1; public final Setting<Integer> denoiserLevel = number("denoiserLevel", 1);
/** Attenuate keyboard clicks while typing. */ /** Attenuate keyboard clicks while typing. */
public boolean typingAttenuation = true; public final Setting<Boolean> typingAttenuation = flag("typingAttenuation", true);
/** Automatic gain control: normalise microphone loudness to a target level. */ /** Automatic gain control: normalise microphone loudness to a target level. */
public boolean agc = true; public final Setting<Boolean> agc = flag("agc", true);
public static final int MAX_AGC_BOOST_DB = 20; public static final int MAX_AGC_BOOST_DB = 20;
/** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */ /** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */
public int agcBoostDb = 0; public final Setting<Integer> agcBoostDb = number("agcBoostDb", 0, 0, MAX_AGC_BOOST_DB);
/** Beep when speech is picked up while the microphone is muted. */ /** Beep when speech is picked up while the microphone is muted. */
public boolean mutedTalkWarning = true; public final Setting<Boolean> mutedTalkWarning = flag("mutedTalkWarning", true);
// ---- notification sounds ---- // ---- notification sounds ----
/** Directory name of the active sound pack; empty picks the first one found. */ /** Directory name of the active sound pack; empty picks the first one found. */
public String soundPack = "default"; public final Setting<String> soundPack = text("soundPack", "default");
/** Notification sound volume, 0..1. */ /** Notification sound volume, 0..1. */
public double soundVolume = 1.0; public final Setting<Double> soundVolume = decimal("soundVolume", 1.0);
/** Extra folder to look for sound packs in, on top of the well-known locations. */ /** Extra folder to look for sound packs in, on top of the well-known locations. */
public String soundPackDir = ""; public final Setting<String> soundPackDir = text("soundPackDir", "");
/** Whether pokes and private messages show a desktop notification while the window is in the background. */ /** Whether pokes and private messages show a desktop notification while the window is in the background. */
public boolean desktopNotifications = true; public final Setting<Boolean> desktopNotifications = flag("desktopNotifications", true);
// ---- icons ---- // ---- icons ----
/** File name of the active icon pack; empty uses the built-in icons. */ /** File name of the active icon pack; empty uses the built-in icons. */
public String iconPack = "default_colored_2014.zip"; public final Setting<String> iconPack = text("iconPack", "default_colored_2014.zip");
/** /**
* Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags; * Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags;
* their details show it beside their name either way. * their details show it beside their name either way.
*/ */
public boolean countryFlags = false; public final Setting<Boolean> countryFlags = flag("countryFlags", false);
/** Background colours of client rows in the channel tree. */ /** Background colours of client rows in the channel tree. */
public final ClientRowColors clientRowColors = new ClientRowColors(); public final ClientRowColors clientRowColors = new ClientRowColors();
/** Extra folder to look for icon packs in, on top of the well-known locations. */ /** Extra folder to look for icon packs in, on top of the well-known locations. */
public String iconPackDir = ""; public final Setting<String> iconPackDir = text("iconPackDir", "");
/** Look-and-feel variant; see {@link Appearance}. */ /** Look-and-feel variant; see {@link Appearance}. */
public Appearance appearance = Appearance.LIGHT; public final Setting<Appearance> appearance = choice("appearance", Appearance.LIGHT);
/** Interface scale factor, 1.0 being 100&nbsp;%; 0 follows the desktop. Read at startup. */ /** Interface scale factor, 1.0 being 100&nbsp;%; 0 follows the desktop. Read at startup. */
public double uiScale = 0; public final Setting<Double> uiScale = decimal("uiScale", 0);
// ---- window chrome ---- // ---- window chrome ----
/** Whether the status bar at the bottom of the window is shown. */ /** Whether the status bar at the bottom of the window is shown. */
public boolean showStatusBar = true; public final Setting<Boolean> showStatusBar = flag("showStatusBar", true);
/** Whether the Master Volume slider is shown on the toolbar. */ /** Whether the Master Volume slider is shown on the toolbar. */
public boolean showMasterVolumeSlider = true; public final Setting<Boolean> showMasterVolumeSlider = flag("showMasterVolumeSlider", true);
/** Share of the tree/info column the tree takes, i.e. where their divider sits. */ /** Share of the tree/info column the tree takes, i.e. where their divider sits. */
public double infoSplitRatio = 0.68; public final Setting<Double> infoSplitRatio = decimal("infoSplitRatio", 0.68);
/** Share of the window's width the tree/info column takes, beside the chat. */ /** Share of the window's width the tree/info column takes, beside the chat. */
public double chatSplitRatio = 0.45; public final Setting<Double> chatSplitRatio = decimal("chatSplitRatio", 0.45);
/** The main window's bounds when not maximised; a width of 0 until it has been placed. */ /** The main window's bounds when not maximised; a width of 0 until it has been placed. */
public int windowX, windowY, windowWidth, windowHeight; public final Setting<Integer> windowX = number("windowX", 0);
public boolean windowMaximized; public final Setting<Integer> windowY = number("windowY", 0);
public final Setting<Integer> windowWidth = number("windowWidth", 0);
public final Setting<Integer> windowHeight = number("windowHeight", 0);
public final Setting<Boolean> windowMaximized = flag("windowMaximized", false);
/** Whether the ban list shows the bans we created ourselves in bold. */ /** Whether the ban list shows the bans we created ourselves in bold. */
public boolean banHighlightOwn = true; public final Setting<Boolean> banHighlightOwn = flag("banHighlightOwn", true);
/** The ban list columns the user shows, comma-separated column names; empty for the default set. */ /** The ban list columns the user shows, comma-separated column names; empty for the default set. */
public String banListColumns = ""; public final Setting<String> banListColumns = text("banListColumns", "");
/** What the Server Log window shows and how. */ /** What the Server Log window shows and how. */
public final ServerLogSettings serverLog = new ServerLogSettings(); public final ServerLogSettings serverLog = new ServerLogSettings();
@@ -218,22 +226,22 @@ public final class Settings {
/** What a client starts out with when added to the contacts as a friend, blocked or neutral. */ /** What a client starts out with when added to the contacts as a friend, blocked or neutral. */
public final ContactDefaults contactDefaults = new ContactDefaults(); public final ContactDefaults contactDefaults = new ContactDefaults();
/** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */ /** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */
public boolean colorContacts = true; public final Setting<Boolean> colorContacts = flag("colorContacts", true);
/** Whose whispers are played. */ /** Whose whispers are played. */
public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED; public final Setting<WhisperPolicy> whisperPolicy = choice("whisperPolicy", WhisperPolicy.ALLOW_UNLESS_DENIED);
/** Keep chat logs, and show their history when a chat opens. */ /** Keep chat logs, and show their history when a chat opens. */
public boolean chatLogs = true; public final Setting<Boolean> chatLogs = flag("chatLogs", true);
/** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */ /** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */
public String chatLogDir = ""; public final Setting<String> chatLogDir = text("chatLogDir", "");
/** The folder recordings were last saved to; empty for {@code ~/Recordings}. */ /** The folder recordings were last saved to; empty for {@code ~/Recordings}. */
public String recordingDir = ""; public final Setting<String> recordingDir = text("recordingDir", "");
/** Whether descriptions show their pictures, fetched from the web, or only links to them. */ /** Whether descriptions show their pictures, fetched from the web, or only links to them. */
public boolean descriptionPictures = true; public final Setting<Boolean> descriptionPictures = flag("descriptionPictures", true);
/** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100&nbsp;%. */ /** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100&nbsp;%. */
public double chatZoom = 1.0; public final Setting<Double> chatZoom = decimal("chatZoom", 1.0);
/** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100&nbsp;%. */ /** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100&nbsp;%. */
public double infoZoom = 1.0; public final Setting<Double> infoZoom = decimal("infoZoom", 1.0);
public static Settings load() { public static Settings load() {
Settings s = new Settings(); Settings s = new Settings();
@@ -242,7 +250,12 @@ public final class Settings {
try (FileInputStream in = new FileInputStream(file())) { try (FileInputStream in = new FileInputStream(file())) {
s.props.load(in); s.props.load(in);
} }
s.applyFromProps(); s.migrateThreshold();
for (Setting<?> setting : s.all) setting.load(s.props);
s.clientRowColors.load(s.props);
s.notifications.load(s.props);
s.serverLog.load(s.props);
s.contactDefaults.load(s.props);
} }
} catch (Exception ignored) { } catch (Exception ignored) {
// Corrupt/unreadable settings -> fall back to defaults. // Corrupt/unreadable settings -> fall back to defaults.
@@ -253,210 +266,81 @@ public final class Settings {
public void save() { public void save() {
try { try {
AppDirs.createProfile(); AppDirs.createProfile();
writeToProps(); for (Setting<?> setting : all) setting.store(props);
clientRowColors.store(props);
notifications.store(props);
serverLog.store(props);
contactDefaults.store(props);
ProfileFiles.write(file(), out -> props.store(out, "TeamSpook TS3j settings")); ProfileFiles.write(file(), out -> props.store(out, "TeamSpook TS3j settings"));
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
public File identityFile() { public File identityFile() {
return new File(identityFile); return new File(identityFile.get());
} }
public Path recordingFolder() { public Path recordingFolder() {
return recordingDir.isBlank() return recordingDir.get().isBlank()
? Paths.get(System.getProperty("user.home", "."), "Recordings") ? Paths.get(System.getProperty("user.home", "."), "Recordings")
: Paths.get(recordingDir); : Paths.get(recordingDir.get());
} }
/** {@link #outputVolume} scaled by the Master Volume slider. */ /** {@link #outputVolume} scaled by the Master Volume slider. */
public double effectiveOutputVolume() { public double effectiveOutputVolume() {
return outputVolume * masterVolume; return outputVolume.get() * masterVolume.get();
} }
/** {@link #soundVolume} scaled by the Master Volume slider. */ /** {@link #soundVolume} scaled by the Master Volume slider. */
public double effectiveSoundVolume() { public double effectiveSoundVolume() {
return soundVolume * masterVolume; return soundVolume.get() * masterVolume.get();
} }
private void applyFromProps() { private <T> Setting<T> add(String key, T initial, Function<String, T> parse, Function<T, String> format,
lastAddress = props.getProperty("lastAddress", lastAddress); UnaryOperator<T> constrain) {
nickname = props.getProperty("nickname", nickname); Setting<T> setting = new Setting<>(key, initial, parse, format, constrain);
serverPassword = props.getProperty("serverPassword", serverPassword); all.add(setting);
identityFile = props.getProperty("identityFile", identityFile); return setting;
defaultIdentityId = props.getProperty("defaultIdentityId", defaultIdentityId);
customVersion = parseB(props.getProperty("customVersion"), customVersion);
clientVersion = props.getProperty("clientVersion", clientVersion);
clientPlatform = props.getProperty("clientPlatform", clientPlatform);
clientVersionSign = props.getProperty("clientVersionSign", clientVersionSign);
inputDevice = props.getProperty("inputDevice", inputDevice);
outputDevice = props.getProperty("outputDevice", outputDevice);
inputMode = parseEnum(InputMode.class, props.getProperty("inputMode"), inputMode);
vadMode = parseEnum(VadMode.class, props.getProperty("vadMode"), vadMode);
vadThresholdDb = parseD(props.getProperty("vadLevelDb"),
migrateThreshold(props.getProperty("vadThresholdDb"), vadThresholdDb));
speechThreshold = parseD(props.getProperty("speechThreshold"), speechThreshold);
vadOverPtt = parseB(props.getProperty("vadOverPtt"), vadOverPtt);
bitrate = parseI(props.getProperty("bitrate"), bitrate);
complexity = parseI(props.getProperty("complexity"), complexity);
vbr = parseB(props.getProperty("vbr"), vbr);
fec = parseB(props.getProperty("fec"), fec);
packetLoss = parseI(props.getProperty("packetLoss"), packetLoss);
music = parseB(props.getProperty("music"), music);
redundancyDelay = parseI(props.getProperty("redundancyDelay"), redundancyDelay);
redundancyCopies = parseI(props.getProperty("redundancyCopies"), redundancyCopies);
receiveBuffer = parseI(props.getProperty("receiveBuffer"), receiveBuffer);
outputVolume = parseD(props.getProperty("outputVolume"), outputVolume);
masterVolume = parseD(props.getProperty("masterVolume"), masterVolume);
inputVolume = parseD(props.getProperty("inputVolume"), inputVolume);
denoise = parseB(props.getProperty("denoise"), denoise);
denoiserLevel = parseI(props.getProperty("denoiserLevel"), denoiserLevel);
typingAttenuation = parseB(props.getProperty("typingAttenuation"), typingAttenuation);
mutedTalkWarning = parseB(props.getProperty("mutedTalkWarning"), mutedTalkWarning);
agc = parseB(props.getProperty("agc"), agc);
agcBoostDb = Math.max(0, Math.min(MAX_AGC_BOOST_DB, parseI(props.getProperty("agcBoostDb"), agcBoostDb)));
soundPack = props.getProperty("soundPack", soundPack);
soundVolume = parseD(props.getProperty("soundVolume"), soundVolume);
soundPackDir = props.getProperty("soundPackDir", soundPackDir);
desktopNotifications = parseB(props.getProperty("desktopNotifications"), desktopNotifications);
iconPack = props.getProperty("iconPack", iconPack);
countryFlags = parseB(props.getProperty("countryFlags"), countryFlags);
clientRowColors.load(props);
iconPackDir = props.getProperty("iconPackDir", iconPackDir);
appearance = parseEnum(Appearance.class, props.getProperty("appearance"), appearance);
uiScale = parseD(props.getProperty("uiScale"), uiScale);
showStatusBar = parseB(props.getProperty("showStatusBar"), showStatusBar);
showMasterVolumeSlider = parseB(props.getProperty("showMasterVolumeSlider"), showMasterVolumeSlider);
infoSplitRatio = parseD(props.getProperty("infoSplitRatio"), infoSplitRatio);
chatSplitRatio = parseD(props.getProperty("chatSplitRatio"), chatSplitRatio);
windowX = parseI(props.getProperty("windowX"), windowX);
windowY = parseI(props.getProperty("windowY"), windowY);
windowWidth = parseI(props.getProperty("windowWidth"), windowWidth);
windowHeight = parseI(props.getProperty("windowHeight"), windowHeight);
windowMaximized = parseB(props.getProperty("windowMaximized"), windowMaximized);
banHighlightOwn = parseB(props.getProperty("banHighlightOwn"), banHighlightOwn);
banListColumns = props.getProperty("banListColumns", banListColumns);
notifications.load(props);
serverLog.load(props);
contactDefaults.load(props);
colorContacts = parseB(props.getProperty("colorContacts"), colorContacts);
descriptionPictures = parseB(props.getProperty("descriptionPictures"), descriptionPictures);
whisperPolicy = parseEnum(WhisperPolicy.class, props.getProperty("whisperPolicy"), whisperPolicy);
chatLogs = parseB(props.getProperty("chatLogs"), chatLogs);
chatLogDir = props.getProperty("chatLogDir", chatLogDir);
recordingDir = props.getProperty("recordingDir", recordingDir);
} }
private void writeToProps() { private Setting<String> text(String key, String initial) {
props.setProperty("lastAddress", lastAddress); return add(key, initial, Function.identity(), Function.identity(), UnaryOperator.identity());
props.setProperty("nickname", nickname);
props.setProperty("serverPassword", serverPassword);
props.setProperty("identityFile", identityFile);
props.setProperty("defaultIdentityId", defaultIdentityId);
props.setProperty("customVersion", Boolean.toString(customVersion));
props.setProperty("clientVersion", clientVersion);
props.setProperty("clientPlatform", clientPlatform);
props.setProperty("clientVersionSign", clientVersionSign);
props.setProperty("inputDevice", inputDevice);
props.setProperty("outputDevice", outputDevice);
props.setProperty("inputMode", inputMode.name());
props.setProperty("vadMode", vadMode.name());
props.setProperty("vadLevelDb", Double.toString(vadThresholdDb));
props.remove("vadThresholdDb");
props.setProperty("speechThreshold", Double.toString(speechThreshold));
props.setProperty("vadOverPtt", Boolean.toString(vadOverPtt));
props.setProperty("bitrate", Integer.toString(bitrate));
props.setProperty("complexity", Integer.toString(complexity));
props.setProperty("vbr", Boolean.toString(vbr));
props.setProperty("fec", Boolean.toString(fec));
props.setProperty("packetLoss", Integer.toString(packetLoss));
props.setProperty("music", Boolean.toString(music));
props.setProperty("redundancyDelay", Integer.toString(redundancyDelay));
props.setProperty("redundancyCopies", Integer.toString(redundancyCopies));
props.setProperty("receiveBuffer", Integer.toString(receiveBuffer));
props.setProperty("outputVolume", Double.toString(outputVolume));
props.setProperty("masterVolume", Double.toString(masterVolume));
props.setProperty("inputVolume", Double.toString(inputVolume));
props.setProperty("denoise", Boolean.toString(denoise));
props.setProperty("denoiserLevel", Integer.toString(denoiserLevel));
props.setProperty("typingAttenuation", Boolean.toString(typingAttenuation));
props.setProperty("mutedTalkWarning", Boolean.toString(mutedTalkWarning));
props.setProperty("agc", Boolean.toString(agc));
props.setProperty("agcBoostDb", Integer.toString(agcBoostDb));
props.setProperty("soundPack", soundPack);
props.setProperty("soundVolume", Double.toString(soundVolume));
props.setProperty("soundPackDir", soundPackDir);
props.setProperty("desktopNotifications", Boolean.toString(desktopNotifications));
props.setProperty("iconPack", iconPack);
props.setProperty("countryFlags", Boolean.toString(countryFlags));
clientRowColors.store(props);
props.setProperty("iconPackDir", iconPackDir);
props.setProperty("appearance", appearance.name());
props.setProperty("uiScale", Double.toString(uiScale));
props.setProperty("showStatusBar", Boolean.toString(showStatusBar));
props.setProperty("showMasterVolumeSlider", Boolean.toString(showMasterVolumeSlider));
props.setProperty("infoSplitRatio", Double.toString(infoSplitRatio));
props.setProperty("chatSplitRatio", Double.toString(chatSplitRatio));
props.setProperty("windowX", Integer.toString(windowX));
props.setProperty("windowY", Integer.toString(windowY));
props.setProperty("windowWidth", Integer.toString(windowWidth));
props.setProperty("windowHeight", Integer.toString(windowHeight));
props.setProperty("windowMaximized", Boolean.toString(windowMaximized));
props.setProperty("banHighlightOwn", Boolean.toString(banHighlightOwn));
props.setProperty("banListColumns", banListColumns);
notifications.store(props);
serverLog.store(props);
contactDefaults.store(props);
props.setProperty("colorContacts", Boolean.toString(colorContacts));
props.setProperty("descriptionPictures", Boolean.toString(descriptionPictures));
props.setProperty("whisperPolicy", whisperPolicy.name());
props.setProperty("chatLogs", Boolean.toString(chatLogs));
props.setProperty("chatLogDir", chatLogDir);
props.setProperty("recordingDir", recordingDir);
} }
private static <E extends Enum<E>> E parseEnum(Class<E> type, String v, E def) { private Setting<Boolean> flag(String key, boolean initial) {
if (v == null) return def; return add(key, initial, Boolean::parseBoolean, String::valueOf, UnaryOperator.identity());
try { }
return Enum.valueOf(type, v.trim());
} catch (IllegalArgumentException e) { private Setting<Integer> number(String key, int initial) {
return def; return add(key, initial, Integer::parseInt, String::valueOf, UnaryOperator.identity());
} }
private Setting<Integer> number(String key, int initial, int min, int max) {
return add(key, initial, Integer::parseInt, String::valueOf, v -> Math.max(min, Math.min(max, v)));
}
private Setting<Double> decimal(String key, double initial) {
return add(key, initial, Double::parseDouble, String::valueOf, UnaryOperator.identity());
}
private <E extends Enum<E>> Setting<E> choice(String key, E initial) {
return add(key, initial, v -> Enum.valueOf(initial.getDeclaringClass(), v.trim()), Enum::name,
UnaryOperator.identity());
} }
/** /**
* Converts a threshold saved under the old {@code vadThresholdDb} key, which was in * Converts a threshold saved under the old {@code vadThresholdDb} key, which was in
* dBFS ({@code 20*log10(rms)}), to {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, so * dBFS ({@code 20*log10(rms)}), to {@link InputLevel}'s scale, so upgrading doesn't silently
* upgrading doesn't silently change how sensitive the gate is. * change how sensitive the gate is.
*/ */
private static double migrateThreshold(String legacy, double def) { private void migrateThreshold() {
double dbfs = parseD(legacy, Double.NaN); String legacy = (String) props.remove("vadThresholdDb");
if (Double.isNaN(dbfs)) { if (legacy == null || props.containsKey(vadThresholdDb.key())) return;
return def;
}
double converted = eu.lixko.ts3j.client.audio.InputLevel.powerToDb(Math.pow(10.0, dbfs / 10.0));
return Math.min(eu.lixko.ts3j.client.audio.InputLevel.MAX_DB, converted);
}
private static double parseD(String v, double def) {
if (v == null) return def;
try { try {
return Double.parseDouble(v); double converted = InputLevel.powerToDb(Math.pow(10.0, Double.parseDouble(legacy) / 10.0));
} catch (NumberFormatException e) { props.setProperty(vadThresholdDb.key(), Double.toString(Math.min(InputLevel.MAX_DB, converted)));
return def; } catch (NumberFormatException ignored) {
// keeps the default
} }
} }
private static int parseI(String v, int def) {
if (v == null) return def;
try {
return Integer.parseInt(v);
} catch (NumberFormatException e) {
return def;
}
}
private static boolean parseB(String v, boolean def) {
return v == null ? def : Boolean.parseBoolean(v);
}
} }
@@ -30,13 +30,13 @@ final class ChatLog {
*/ */
void open(String serverUniqueId) { void open(String serverUniqueId) {
store = null; store = null;
if (!settings.chatLogs) return; if (!settings.chatLogs.get()) return;
try { try {
if (serverUniqueId == null) { if (serverUniqueId == null) {
ui.onStatus("Chat logs unavailable: the server's unique id is not known"); ui.onStatus("Chat logs unavailable: the server's unique id is not known");
return; return;
} }
String dir = settings.chatLogDir == null ? "" : settings.chatLogDir.trim(); String dir = settings.chatLogDir.get() == null ? "" : settings.chatLogDir.get().trim();
// Android < API 34 lacks Path.of; original: // Android < API 34 lacks Path.of; original:
// ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId); // ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId);
ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), serverUniqueId); ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), serverUniqueId);
@@ -46,7 +46,7 @@ public final class ClientContacts {
* client's contact entry. A client that has already left is judged by the policy alone. * client's contact entry. A client that has already left is judged by the policy alone.
*/ */
boolean isWhisperAllowed(int clientId) { boolean isWhisperAllowed(int clientId) {
Settings.WhisperPolicy policy = settings.whisperPolicy; Settings.WhisperPolicy policy = settings.whisperPolicy.get();
if (policy == Settings.WhisperPolicy.NOBODY) return false; if (policy == Settings.WhisperPolicy.NOBODY) return false;
ClientEntry c = model.getClient(clientId); ClientEntry c = model.getClient(clientId);
Contact contact = c == null ? null : store.find(c.uniqueId); Contact contact = c == null ? null : store.find(c.uniqueId);
@@ -130,7 +130,7 @@ public final class OwnClient {
VoiceOutput out = audio.createOutput(settings); VoiceOutput out = audio.createOutput(settings);
out.setMasterVolume(settings.effectiveOutputVolume()); out.setMasterVolume(settings.effectiveOutputVolume());
out.setReceiveBuffer(settings.receiveBuffer); out.setReceiveBuffer(settings.receiveBuffer.get());
out.setTalkListener((clientId, talking) -> { out.setTalkListener((clientId, talking) -> {
ClientEntry c = model.getClient(clientId); ClientEntry c = model.getClient(clientId);
if (c != null) c.talking = talking; if (c != null) c.talking = talking;
@@ -212,7 +212,7 @@ public final class OwnClient {
/** Reminds the user, at most every few seconds, that the microphone is muted. */ /** Reminds the user, at most every few seconds, that the microphone is muted. */
private void onTalkingWhileMuted() { private void onTalkingWhileMuted() {
if (!settings.mutedTalkWarning) return; if (!settings.mutedTalkWarning.get()) return;
long now = System.nanoTime(); long now = System.nanoTime();
if (now - lastMutedTalkNanos < MUTED_TALK_COOLDOWN_NANOS) return; if (now - lastMutedTalkNanos < MUTED_TALK_COOLDOWN_NANOS) return;
lastMutedTalkNanos = now; lastMutedTalkNanos = now;
@@ -359,7 +359,7 @@ public final class TeamspeakConnection implements TS3Listener {
* hand, and the bare message does not point anywhere. * hand, and the bare message does not point anywhere.
*/ */
private String versionHint(Exception e) { private String versionHint(Exception e) {
if (!settings.customVersion) return ""; if (!settings.customVersion.get()) return "";
String message = RequestException.rootMessage(e); String message = RequestException.rootMessage(e);
return message != null && message.contains("client is modified") return message != null && message.contains("client is modified")
? " — the server did not accept the custom client version; pick a newer one" ? " — the server did not accept the custom client version; pick a newer one"
@@ -374,10 +374,10 @@ public final class TeamspeakConnection implements TS3Listener {
* platform it was issued for, or a server may refuse the connection. * platform it was issued for, or a server may refuse the connection.
*/ */
private void applyClientVersion(LocalTeamspeakClientSocket client) { private void applyClientVersion(LocalTeamspeakClientSocket client) {
if (!settings.customVersion) return; if (!settings.customVersion.get()) return;
setIfPresent(client, "client.version_string", settings.clientVersion); setIfPresent(client, "client.version_string", settings.clientVersion.get());
setIfPresent(client, "client.version_platform", settings.clientPlatform); setIfPresent(client, "client.version_platform", settings.clientPlatform.get());
setIfPresent(client, "client.version_sign", settings.clientVersionSign); setIfPresent(client, "client.version_sign", settings.clientVersionSign.get());
} }
private static void setIfPresent(LocalTeamspeakClientSocket client, String option, String value) { private static void setIfPresent(LocalTeamspeakClientSocket client, String option, String value) {
@@ -801,7 +801,8 @@ public final class TeamspeakConnection implements TS3Listener {
private void keepSentChat(ConnectionListener.ChatScope scope, String peerUniqueId, String message) { private void keepSentChat(ConnectionListener.ChatScope scope, String peerUniqueId, String message) {
ClientEntry self = own.entry(); ClientEntry self = own.entry();
String uid = identity != null ? identity.getUid().toBase64() : ""; String uid = identity != null ? identity.getUid().toBase64() : "";
chatLog.sent(scope, selfClientId, uid, self != null ? self.nickname : settings.nickname, peerUniqueId, message); String nickname = self != null ? self.nickname : settings.nickname.get();
chatLog.sent(scope, selfClientId, uid, nickname, peerUniqueId, message);
} }
// ---- helpers ---- // ---- helpers ----
@@ -301,7 +301,7 @@ public final class ServerSession {
private String nicknameFor(String serverNickname, IdentityEntry identity) { private String nicknameFor(String serverNickname, IdentityEntry identity) {
if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim(); if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim();
if (!identity.getNickname().isBlank()) return identity.getNickname(); if (!identity.getNickname().isBlank()) return identity.getNickname();
return settings.nickname; return settings.nickname.get();
} }
/** /**
@@ -49,8 +49,8 @@ public final class SoundNotifier {
/** Re-scans the installed packs and selects the configured one. */ /** Re-scans the installed packs and selects the configured one. */
public void reload() { public void reload() {
available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir); available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir.get());
pack = SoundPacks.select(available, settings.soundPack); pack = SoundPacks.select(available, settings.soundPack.get());
} }
public List<SoundPack> availablePacks() { public List<SoundPack> availablePacks() {
@@ -64,7 +64,7 @@ public final class SoundNotifier {
/** Switches packs and remembers the choice in the settings. */ /** Switches packs and remembers the choice in the settings. */
public void setPack(SoundPack pack) { public void setPack(SoundPack pack) {
this.pack = pack; this.pack = pack;
settings.soundPack = pack == null ? "" : pack.id(); settings.soundPack.set(pack == null ? "" : pack.id());
} }
/** /**
@@ -177,9 +177,9 @@ public final class TeamSpeakImporter {
imported.put(identity.uuid(), entry); imported.put(identity.uuid(), entry);
if (!identity.isDefault()) continue; if (!identity.isDefault()) continue;
// No default of our own yet: TeamSpeak's default identity and nickname become ours. // No default of our own yet: TeamSpeak's default identity and nickname become ours.
if (identities.byId(settings.defaultIdentityId) == null) { if (identities.byId(settings.defaultIdentityId.get()) == null) {
settings.defaultIdentityId = entry.getId(); settings.defaultIdentityId.set(entry.getId());
if (!identity.nickname().isBlank()) settings.nickname = identity.nickname(); if (!identity.nickname().isBlank()) settings.nickname.set(identity.nickname());
settingsChanged = true; settingsChanged = true;
} }
} }
@@ -8,6 +8,8 @@ import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -30,33 +32,33 @@ class SettingsTest {
@Test @Test
void whatIsSavedLoadsBack() { void whatIsSavedLoadsBack() {
Settings saved = new Settings(); Settings saved = new Settings();
saved.nickname = "Žofia"; saved.nickname.set("Žofia");
saved.inputMode = Settings.InputMode.PUSH_TO_TALK; saved.inputMode.set(Settings.InputMode.PUSH_TO_TALK);
saved.vadMode = Settings.VadMode.AUTOMATIC; saved.vadMode.set(Settings.VadMode.AUTOMATIC);
saved.vadThresholdDb = -33.5; saved.vadThresholdDb.set(-33.5);
saved.appearance = Settings.Appearance.DARK; saved.appearance.set(Settings.Appearance.DARK);
saved.whisperPolicy = Settings.WhisperPolicy.NOBODY; saved.whisperPolicy.set(Settings.WhisperPolicy.NOBODY);
saved.chatLogs = false; saved.chatLogs.set(false);
saved.chatLogDir = "/somewhere/else"; saved.chatLogDir.set("/somewhere/else");
saved.save(); saved.save();
Settings loaded = Settings.load(); Settings loaded = Settings.load();
assertEquals("Žofia", loaded.nickname); assertEquals("Žofia", loaded.nickname.get());
assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode); assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode.get());
assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode); assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode.get());
assertEquals(-33.5, loaded.vadThresholdDb); assertEquals(-33.5, loaded.vadThresholdDb.get());
assertEquals(Settings.Appearance.DARK, loaded.appearance); assertEquals(Settings.Appearance.DARK, loaded.appearance.get());
assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy); assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy.get());
assertFalse(loaded.chatLogs); assertFalse(loaded.chatLogs.get());
assertEquals("/somewhere/else", loaded.chatLogDir); assertEquals("/somewhere/else", loaded.chatLogDir.get());
} }
@Test @Test
void unknownValuesFallBackToDefaults() throws Exception { void unknownValuesFallBackToDefaults() throws Exception {
Files.writeString(dir.resolve("settings.properties"), "inputMode=TELEPATHY\nvadMode=\n"); Files.writeString(dir.resolve("settings.properties"), "inputMode=TELEPATHY\nvadMode=\n");
Settings loaded = Settings.load(); Settings loaded = Settings.load();
assertEquals(new Settings().inputMode, loaded.inputMode); assertEquals(new Settings().inputMode.get(), loaded.inputMode.get());
assertEquals(new Settings().vadMode, loaded.vadMode); assertEquals(new Settings().vadMode.get(), loaded.vadMode.get());
} }
@Test @Test
@@ -64,11 +66,31 @@ class SettingsTest {
Files.writeString(dir.resolve("settings.properties"), "vadThresholdDb=-40.0\n"); Files.writeString(dir.resolve("settings.properties"), "vadThresholdDb=-40.0\n");
Settings loaded = Settings.load(); Settings loaded = Settings.load();
double expected = InputLevel.powerToDb(Math.pow(10.0, -40.0 / 10.0)); double expected = InputLevel.powerToDb(Math.pow(10.0, -40.0 / 10.0));
assertEquals(expected, loaded.vadThresholdDb, 1e-9); assertEquals(expected, loaded.vadThresholdDb.get(), 1e-9);
loaded.save(); loaded.save();
String saved = Files.readString(dir.resolve("settings.properties")); String saved = Files.readString(dir.resolve("settings.properties"));
assertFalse(saved.contains("vadThresholdDb"), "the old key is dropped once converted"); assertFalse(saved.contains("vadThresholdDb"), "the old key is dropped once converted");
assertEquals(expected, Settings.load().vadThresholdDb, 1e-9); assertEquals(expected, Settings.load().vadThresholdDb.get(), 1e-9);
}
@Test
void listenersHearChangesOnly() {
Settings settings = new Settings();
List<Boolean> heard = new ArrayList<>();
settings.showStatusBar.addListener(heard::add);
settings.showStatusBar.set(true);
settings.showStatusBar.set(false);
settings.showStatusBar.set(false);
assertEquals(List.of(false), heard);
}
@Test
void outOfRangeValuesAreClamped() throws Exception {
Files.writeString(dir.resolve("settings.properties"), "agcBoostDb=99\n");
Settings loaded = Settings.load();
assertEquals(Settings.MAX_AGC_BOOST_DB, loaded.agcBoostDb.get());
loaded.agcBoostDb.set(-5);
assertEquals(0, loaded.agcBoostDb.get());
} }
} }
@@ -38,7 +38,7 @@ class TeamSpeakImporterTest {
@Test @Test
void importsBookmarksWithTheIdentitiesTheyUse() throws Exception { void importsBookmarksWithTheIdentitiesTheyUse() throws Exception {
Settings settings = new Settings(); Settings settings = new Settings();
settings.nickname = "Fallback"; settings.nickname.set("Fallback");
IdentityStore identities = IdentityStore.load(settings); IdentityStore identities = IdentityStore.load(settings);
Bookmarks bookmarks = new Bookmarks(); Bookmarks bookmarks = new Bookmarks();
bookmarks.add(new Bookmark("TeamSpeak Public", "VOICE.teamspeak.com", 9987, "me", "")); bookmarks.add(new Bookmark("TeamSpeak Public", "VOICE.teamspeak.com", 9987, "me", ""));
@@ -51,7 +51,7 @@ class TeamSpeakImporterTest {
IdentityEntry imported = identities.all().get(0); IdentityEntry imported = identities.all().get(0);
assertEquals("Default", imported.getName()); assertEquals("Default", imported.getName());
assertEquals(imported.getId(), settings.defaultIdentityId); assertEquals(imported.getId(), settings.defaultIdentityId.get());
assertTrue(imported.getFile().isFile()); assertTrue(imported.getFile().isFile());
List<Bookmark> all = bookmarks.all(); List<Bookmark> all = bookmarks.all();
@@ -70,7 +70,7 @@ class TeamSpeakImporterTest {
assertEquals("", byId.nickname, "takes the identity's nickname as it connects"); assertEquals("", byId.nickname, "takes the identity's nickname as it connects");
assertEquals("SyncTester", imported.getNickname()); assertEquals("SyncTester", imported.getNickname());
assertEquals("", byId.identityId, "connects with whatever the default identity is"); assertEquals("", byId.identityId, "connects with whatever the default identity is");
assertEquals("SyncTester", settings.nickname); assertEquals("SyncTester", settings.nickname.get());
// Running it again changes nothing. // Running it again changes nothing.
result = importer.importBookmarks(SyncItemsTest.fixture()); result = importer.importBookmarks(SyncItemsTest.fixture());
@@ -129,7 +129,7 @@ class TeamSpeakImporterTest {
assertEquals(1, first.identities()); assertEquals(1, first.identities());
assertEquals(1, second.identitiesKnown()); assertEquals(1, second.identitiesKnown());
assertEquals(before + first.identitiesAdded(), identities.all().size()); assertEquals(before + first.identitiesAdded(), identities.all().size());
assertNotNull(identities.byId(settings.defaultIdentityId)); assertNotNull(identities.byId(settings.defaultIdentityId.get()));
} }
@Test @Test
@@ -32,11 +32,11 @@ public final class Main {
if (link != null && InstanceChannel.send(link)) return; if (link != null && InstanceChannel.send(link)) return;
final Settings settings = Settings.load(); final Settings settings = Settings.load();
DisplayScale.configure(settings.uiScale); DisplayScale.configure(settings.uiScale.get());
WindowClass.apply(); WindowClass.apply();
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
LookAndFeelManager.install(settings.appearance); LookAndFeelManager.install(settings.appearance.get());
IconTheme.get().reload(settings); IconTheme.get().reload(settings);
DesktopEntry.install(); DesktopEntry.install();
MainFrame frame = new MainFrame(settings); MainFrame frame = new MainFrame(settings);
@@ -16,7 +16,7 @@ final class ApplicationPanel extends FormPanel {
this.settings = settings; this.settings = settings;
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
mutedWarning = new JCheckBox("Warn when talking while microphone is muted", settings.mutedTalkWarning); mutedWarning = new JCheckBox("Warn when talking while microphone is muted", settings.mutedTalkWarning.get());
clientVersion = new ClientVersionPanel(settings); clientVersion = new ClientVersionPanel(settings);
int row = 0; int row = 0;
@@ -29,7 +29,7 @@ final class ApplicationPanel extends FormPanel {
/** Copies the page into the settings; the caller saves them. */ /** Copies the page into the settings; the caller saves them. */
void apply() { void apply() {
settings.mutedTalkWarning = mutedWarning.isSelected(); settings.mutedTalkWarning.set(mutedWarning.isSelected());
clientVersion.apply(); clientVersion.apply();
} }
} }
@@ -195,9 +195,9 @@ final class BanListDialog extends AbstractServerListDialog {
onlyOwn.addActionListener(e -> applyFilter()); onlyOwn.addActionListener(e -> applyFilter());
highlightOwn.setToolTipText("Mark bans created by you as bold"); highlightOwn.setToolTipText("Mark bans created by you as bold");
highlightOwn.setOpaque(false); highlightOwn.setOpaque(false);
highlightOwn.setSelected(settings.banHighlightOwn); highlightOwn.setSelected(settings.banHighlightOwn.get());
highlightOwn.addActionListener(e -> { highlightOwn.addActionListener(e -> {
settings.banHighlightOwn = highlightOwn.isSelected(); settings.banHighlightOwn.set(highlightOwn.isSelected());
settings.save(); settings.save();
table.repaint(); table.repaint();
}); });
@@ -241,7 +241,7 @@ final class BanListDialog extends AbstractServerListDialog {
private Set<Column> savedColumns() { private Set<Column> savedColumns() {
Set<Column> columns = EnumSet.noneOf(Column.class); Set<Column> columns = EnumSet.noneOf(Column.class);
for (String name : settings.banListColumns.split(",")) { for (String name : settings.banListColumns.get().split(",")) {
try { try {
if (!name.isBlank()) columns.add(Column.valueOf(name.trim())); if (!name.isBlank()) columns.add(Column.valueOf(name.trim()));
} catch (IllegalArgumentException ignored) { } catch (IllegalArgumentException ignored) {
@@ -255,7 +255,7 @@ final class BanListDialog extends AbstractServerListDialog {
} }
private void saveColumns() { private void saveColumns() {
settings.banListColumns = visibleColumns.stream().map(Enum::name).collect(Collectors.joining(",")); settings.banListColumns.set(visibleColumns.stream().map(Enum::name).collect(Collectors.joining(",")));
settings.save(); settings.save();
} }
@@ -38,11 +38,11 @@ final class CapturePanel extends FormPanel {
this.activation = new VoiceActivationSection(settings, audio, liveMic, hotkeys, hotkeysPanel, audioSnapshot); this.activation = new VoiceActivationSection(settings, audio, liveMic, hotkeys, hotkeysPanel, audioSnapshot);
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice); inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice.get());
limitWidth(inputCombo, FIELD_WIDTH); limitWidth(inputCombo, FIELD_WIDTH);
inputCombo.addActionListener(e -> activation.restartTest()); inputCombo.addActionListener(e -> activation.restartTest());
inputGain = new JSlider(0, 200, (int) Math.round(settings.inputVolume * 100)); inputGain = new JSlider(0, 200, (int) Math.round(settings.inputVolume.get() * 100));
JLabel gainLabel = new JLabel(inputGain.getValue() + "%"); JLabel gainLabel = new JLabel(inputGain.getValue() + "%");
inputGain.addChangeListener(e -> { inputGain.addChangeListener(e -> {
gainLabel.setText(inputGain.getValue() + "%"); gainLabel.setText(inputGain.getValue() + "%");
@@ -51,14 +51,14 @@ final class CapturePanel extends FormPanel {
// Off, then TS3's four denoiser_level steps. // Off, then TS3's four denoiser_level steps.
denoise = new JSlider(0, DENOISE_STEPS.length - 1, denoise = new JSlider(0, DENOISE_STEPS.length - 1,
settings.denoise ? Math.max(0, Math.min(3, settings.denoiserLevel)) + 1 : 0); settings.denoise.get() ? Math.max(0, Math.min(3, settings.denoiserLevel.get())) + 1 : 0);
denoise.setMajorTickSpacing(1); denoise.setMajorTickSpacing(1);
denoise.setPaintTicks(true); denoise.setPaintTicks(true);
denoise.setSnapToTicks(true); denoise.setSnapToTicks(true);
JLabel denoiseLabel = new JLabel(DENOISE_STEPS[denoise.getValue()]); JLabel denoiseLabel = new JLabel(DENOISE_STEPS[denoise.getValue()]);
typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation); typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation.get());
agcCheck = new JCheckBox("Automatic gain control", settings.agc); agcCheck = new JCheckBox("Automatic gain control", settings.agc.get());
agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb); agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb.get());
agcBoost.setMajorTickSpacing(5); agcBoost.setMajorTickSpacing(5);
agcBoost.setPaintTicks(true); agcBoost.setPaintTicks(true);
limitWidth(agcBoost, SLIDER_WIDTH); limitWidth(agcBoost, SLIDER_WIDTH);
@@ -98,13 +98,13 @@ final class CapturePanel extends FormPanel {
/** Copies the page into {@code target}, without touching anything else. */ /** Copies the page into {@code target}, without touching anything else. */
void writeInto(Settings target) { void writeInto(Settings target) {
target.inputDevice = AudioDevices.selectedId(inputCombo); target.inputDevice.set(AudioDevices.selectedId(inputCombo));
target.inputVolume = inputGain.getValue() / 100.0; target.inputVolume.set(inputGain.getValue() / 100.0);
target.denoise = denoise.getValue() > 0; target.denoise.set(denoise.getValue() > 0);
if (target.denoise) target.denoiserLevel = denoise.getValue() - 1; if (target.denoise.get()) target.denoiserLevel.set(denoise.getValue() - 1);
target.typingAttenuation = typingCheck.isSelected(); target.typingAttenuation.set(typingCheck.isSelected());
target.agc = agcCheck.isSelected(); target.agc.set(agcCheck.isSelected());
target.agcBoostDb = agcBoost.getValue(); target.agcBoostDb.set(agcBoost.getValue());
activation.writeInto(target); activation.writeInto(target);
} }
@@ -30,11 +30,11 @@ final class ChatLogsPanel extends FormPanel {
this.settings = settings; this.settings = settings;
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
enabled.setSelected(settings.chatLogs); enabled.setSelected(settings.chatLogs.get());
enabled.setToolTipText("Write every chat to disk and show its history when it opens again"); enabled.setToolTipText("Write every chat to disk and show its history when it opens again");
enabled.addActionListener(e -> updateEnabled()); enabled.addActionListener(e -> updateEnabled());
folder.setText(settings.chatLogDir); folder.setText(settings.chatLogDir.get());
folder.putClientProperty("JTextField.placeholderText", "The TeamSpeak 3 client's folder"); folder.putClientProperty("JTextField.placeholderText", "The TeamSpeak 3 client's folder");
folder.setToolTipText("<html>Leave empty to share the TeamSpeak 3 client's logs:<br>" folder.setToolTipText("<html>Leave empty to share the TeamSpeak 3 client's logs:<br>"
+ AppDirs.chatLogs() + "</html>"); + AppDirs.chatLogs() + "</html>");
@@ -47,7 +47,7 @@ final class ChatLogsPanel extends FormPanel {
JLabel nextConnect = new JLabel("Takes effect on the next connect."); JLabel nextConnect = new JLabel("Takes effect on the next connect.");
nextConnect.setEnabled(false); nextConnect.setEnabled(false);
pictures.setSelected(settings.descriptionPictures); pictures.setSelected(settings.descriptionPictures.get());
pictures.setToolTipText("Off: only links to them, nothing fetched"); pictures.setToolTipText("Off: only links to them, nothing fetched");
int row = 0; int row = 0;
@@ -81,8 +81,8 @@ final class ChatLogsPanel extends FormPanel {
/** Copies the page into the settings; the caller saves them. */ /** Copies the page into the settings; the caller saves them. */
void apply() { void apply() {
settings.chatLogs = enabled.isSelected(); settings.chatLogs.set(enabled.isSelected());
settings.chatLogDir = folder.getText().trim(); settings.chatLogDir.set(folder.getText().trim());
settings.descriptionPictures = pictures.isSelected(); settings.descriptionPictures.set(pictures.isSelected());
} }
} }
@@ -57,10 +57,10 @@ final class ClientVersionPanel extends JPanel {
/** Copies the edited version into the settings; the caller saves them. */ /** Copies the edited version into the settings; the caller saves them. */
void apply() { void apply() {
settings.customVersion = enabled.isSelected(); settings.customVersion.set(enabled.isSelected());
settings.clientVersion = versionField.getText().trim(); settings.clientVersion.set(versionField.getText().trim());
settings.clientPlatform = String.valueOf(platformCombo.getEditor().getItem()).trim(); settings.clientPlatform.set(String.valueOf(platformCombo.getEditor().getItem()).trim());
settings.clientVersionSign = signField.getText().trim(); settings.clientVersionSign.set(signField.getText().trim());
} }
private JComponent buildForm() { private JComponent buildForm() {
@@ -117,11 +117,12 @@ final class ClientVersionPanel extends JPanel {
} }
private void load() { private void load() {
enabled.setSelected(settings.customVersion); enabled.setSelected(settings.customVersion.get());
ClientVersion preset = ClientVersion.match( ClientVersion preset = ClientVersion.match(
settings.clientVersion, settings.clientPlatform, settings.clientVersionSign); settings.clientVersion.get(), settings.clientPlatform.get(), settings.clientVersionSign.get());
fill(preset != null ? preset fill(preset != null ? preset
: new ClientVersion("", settings.clientVersion, settings.clientPlatform, settings.clientVersionSign)); : new ClientVersion("", settings.clientVersion.get(), settings.clientPlatform.get(),
settings.clientVersionSign.get()));
presetCombo.setSelectedItem(preset != null ? preset : CUSTOM); presetCombo.setSelectedItem(preset != null ? preset : CUSTOM);
} }
@@ -34,7 +34,7 @@ public final class ConnectDialog extends JDialog {
public ConnectDialog(Frame owner, Settings settings, IdentityStore identities) { public ConnectDialog(Frame owner, Settings settings, IdentityStore identities) {
super(owner, "Connect to Server", true); super(owner, "Connect to Server", true);
String addr = settings.lastAddress; String addr = settings.lastAddress.get();
int port = 9987; int port = 9987;
int colon = addr.lastIndexOf(':'); int colon = addr.lastIndexOf(':');
if (colon > 0) { if (colon > 0) {
@@ -47,9 +47,9 @@ public final class ConnectDialog extends JDialog {
addressField = new JTextField(addr, 18); addressField = new JTextField(addr, 18);
portField = new JTextField(Integer.toString(port), 6); portField = new JTextField(Integer.toString(port), 6);
nickField = new JTextField(settings.nickname, 18); nickField = new JTextField(settings.nickname.get(), 18);
passwordField = new JPasswordField(settings.serverPassword, 18); passwordField = new JPasswordField(settings.serverPassword.get(), 18);
identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId); identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId.get());
JPanel form = new JPanel(new GridBagLayout()); JPanel form = new JPanel(new GridBagLayout());
form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12));
@@ -30,10 +30,10 @@ final class ContactsPanel extends FormPanel {
this.settings = settings; this.settings = settings;
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
colorContacts.setSelected(settings.colorContacts); colorContacts.setSelected(settings.colorContacts.get());
colorContacts.setToolTipText("Friends in green and blocked clients in red, as the TeamSpeak client shows them"); colorContacts.setToolTipText("Friends in green and blocked clients in red, as the TeamSpeak client shows them");
whisperPolicy.setSelectedItem(settings.whisperPolicy); whisperPolicy.setSelectedItem(settings.whisperPolicy.get());
whisperPolicy.setRenderer(new DefaultListCellRenderer() { whisperPolicy.setRenderer(new DefaultListCellRenderer() {
@Override @Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, public Component getListCellRendererComponent(JList<?> list, Object value, int index,
@@ -68,7 +68,7 @@ final class ContactsPanel extends FormPanel {
/** Copies the page into the settings; the caller saves them. */ /** Copies the page into the settings; the caller saves them. */
void apply() { void apply() {
settings.colorContacts = colorContacts.isSelected(); settings.colorContacts.set(colorContacts.isSelected());
settings.whisperPolicy = (Settings.WhisperPolicy) whisperPolicy.getSelectedItem(); settings.whisperPolicy.set((Settings.WhisperPolicy) whisperPolicy.getSelectedItem());
} }
} }
@@ -92,7 +92,7 @@ final class DescriptionPictures {
* and asks for those not on their way yet. * and asks for those not on their way yet.
*/ */
String state(List<String> urls) { String state(List<String> urls) {
if (!settings.descriptionPictures) return ""; if (!settings.descriptionPictures.get()) return "";
StringBuilder state = new StringBuilder(urls.size()); StringBuilder state = new StringBuilder(urls.size());
for (String url : urls) { for (String url : urls) {
state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-'); state.append(downloads.get(url) != null ? 'y' : downloads.failed(url) ? 'n' : '-');
@@ -101,7 +101,7 @@ final class DescriptionPictures {
} }
private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) { private String picture(String url, String anchor, String href, int maxWidth, int maxHeight) {
if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href); if (!settings.descriptionPictures.get()) return link("ICONVIEWER", url, anchor, href);
File file = downloads.get(url); File file = downloads.get(url);
if (file == null) { if (file == null) {
return downloads.failed(url) ? link("BROKEN_IMAGE", url, anchor, href) : icon("LOADING_IMAGE"); return downloads.failed(url) ? link("BROKEN_IMAGE", url, anchor, href) : icon("LOADING_IMAGE");
@@ -70,10 +70,10 @@ final class DesignPanel extends JPanel {
DesignPanel(Settings settings) { DesignPanel(Settings settings) {
super(new BorderLayout(0, UIScale.scale(8))); super(new BorderLayout(0, UIScale.scale(8)));
this.settings = settings; this.settings = settings;
this.originalPackId = settings.iconPack; this.originalPackId = settings.iconPack.get();
this.originalPackDir = settings.iconPackDir; this.originalPackDir = settings.iconPackDir.get();
this.originalAppearance = settings.appearance; this.originalAppearance = settings.appearance.get();
this.packDirField = new JTextField(settings.iconPackDir, 18); this.packDirField = new JTextField(settings.iconPackDir.get(), 18);
this.anyColor = new RowColorCombo(settings.clientRowColors.any); this.anyColor = new RowColorCombo(settings.clientRowColors.any);
this.talkingColor = new RowColorCombo(settings.clientRowColors.talking); this.talkingColor = new RowColorCombo(settings.clientRowColors.talking);
this.mutedAwayColor = new RowColorCombo(settings.clientRowColors.mutedAway); this.mutedAwayColor = new RowColorCombo(settings.clientRowColors.mutedAway);
@@ -87,27 +87,27 @@ final class DesignPanel extends JPanel {
/** Copies the chosen appearance and pack into the settings; the caller saves them. */ /** Copies the chosen appearance and pack into the settings; the caller saves them. */
void apply() { void apply() {
settings.appearance = selectedAppearance(); settings.appearance.set(selectedAppearance());
if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale = scale; if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale.set(scale);
settings.iconPackDir = packDirField.getText().trim(); settings.iconPackDir.set(packDirField.getText().trim());
Object selected = packCombo.getSelectedItem(); Object selected = packCombo.getSelectedItem();
settings.iconPack = selected instanceof IconPack pack ? pack.id() : ""; settings.iconPack.set(selected instanceof IconPack pack ? pack.id() : "");
settings.countryFlags = countryFlags.isSelected(); settings.countryFlags.set(countryFlags.isSelected());
settings.clientRowColors.any = anyColor.value(); settings.clientRowColors.any = anyColor.value();
settings.clientRowColors.talking = talkingColor.value(); settings.clientRowColors.talking = talkingColor.value();
settings.clientRowColors.mutedAway = mutedAwayColor.value(); settings.clientRowColors.mutedAway = mutedAwayColor.value();
originalPackId = settings.iconPack; originalPackId = settings.iconPack.get();
originalPackDir = settings.iconPackDir; originalPackDir = settings.iconPackDir.get();
originalAppearance = settings.appearance; originalAppearance = settings.appearance.get();
} }
/** Puts back the appearance and pack last applied, for a cancelled edit. */ /** Puts back the appearance and pack last applied, for a cancelled edit. */
void revert() { void revert() {
settings.iconPack = originalPackId; settings.iconPack.set(originalPackId);
settings.iconPackDir = originalPackDir; settings.iconPackDir.set(originalPackDir);
IconTheme.get().reload(settings); IconTheme.get().reload(settings);
if (settings.appearance != originalAppearance) { if (settings.appearance.get() != originalAppearance) {
settings.appearance = originalAppearance; settings.appearance.set(originalAppearance);
LookAndFeelManager.switchTo(originalAppearance); LookAndFeelManager.switchTo(originalAppearance);
} }
} }
@@ -134,7 +134,7 @@ final class DesignPanel extends JPanel {
}); });
appearanceCombo.setToolTipText("Light or dark window colours"); appearanceCombo.setToolTipText("Light or dark window colours");
appearanceCombo.setSelectedItem(settings.appearance); appearanceCombo.setSelectedItem(settings.appearance.get());
appearanceCombo.setRenderer(new DefaultListCellRenderer() { appearanceCombo.setRenderer(new DefaultListCellRenderer() {
@Override @Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, public Component getListCellRendererComponent(JList<?> list, Object value, int index,
@@ -153,7 +153,7 @@ final class DesignPanel extends JPanel {
dirRow.add(browse, BorderLayout.EAST); dirRow.add(browse, BorderLayout.EAST);
packDirField.setToolTipText("Extra folder to look for icon packs in"); packDirField.setToolTipText("Extra folder to look for icon packs in");
packInfo.setEnabled(false); packInfo.setEnabled(false);
countryFlags.setSelected(settings.countryFlags); countryFlags.setSelected(settings.countryFlags.get());
int row = 0; int row = 0;
FormPanel.addSection(p, c, row++, "Appearance"); FormPanel.addSection(p, c, row++, "Appearance");
@@ -178,10 +178,10 @@ final class DesignPanel extends JPanel {
private void buildScaleCombo() { private void buildScaleCombo() {
for (double scale : SCALES) scaleCombo.addItem(scale); for (double scale : SCALES) scaleCombo.addItem(scale);
if (settings.uiScale > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale)) { if (settings.uiScale.get() > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale.get())) {
scaleCombo.addItem(settings.uiScale); scaleCombo.addItem(settings.uiScale.get());
} }
scaleCombo.setSelectedItem(Math.max(0, settings.uiScale)); scaleCombo.setSelectedItem(Math.max(0, settings.uiScale.get()));
scaleCombo.setToolTipText("Size of text, icons and controls; takes effect after a restart"); scaleCombo.setToolTipText("Size of text, icons and controls; takes effect after a restart");
scaleCombo.setRenderer(new DefaultListCellRenderer() { scaleCombo.setRenderer(new DefaultListCellRenderer() {
@Override @Override
@@ -248,8 +248,8 @@ final class DesignPanel extends JPanel {
private void onAppearanceSelected() { private void onAppearanceSelected() {
Settings.Appearance chosen = selectedAppearance(); Settings.Appearance chosen = selectedAppearance();
if (chosen == settings.appearance) return; if (chosen == settings.appearance.get()) return;
settings.appearance = chosen; settings.appearance.set(chosen);
LookAndFeelManager.switchTo(chosen); LookAndFeelManager.switchTo(chosen);
} }
@@ -276,7 +276,7 @@ final class DesignPanel extends JPanel {
if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current));
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); packDirField.setText(chooser.getSelectedFile().getAbsolutePath());
settings.iconPackDir = packDirField.getText(); settings.iconPackDir.set(packDirField.getText());
reloadPacks(); reloadPacks();
} }
} }
@@ -118,7 +118,7 @@ final class DesktopNotifier {
private boolean wanted() { private boolean wanted() {
// Some window of ours has the focus exactly when there is an active window. // Some window of ours has the focus exactly when there is an active window.
return settings.desktopNotifications return settings.desktopNotifications.get()
&& KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() == null; && KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() == null;
} }
@@ -338,7 +338,7 @@ final class DropIndicatorTree extends JTree {
model.serverGroupsOf(cl.serverGroupIds), model.channelGroup(cl.channelGroupId))); model.serverGroupsOf(cl.serverGroupIds), model.channelGroup(cl.channelGroupId)));
addIcon(icons, cl.talkRequest ? "TALK_POWER_REQUEST" : null); addIcon(icons, cl.talkRequest ? "TALK_POWER_REQUEST" : null);
// The country's flag comes last, at the row's edge, as in TeamSpeak. // The country's flag comes last, at the row's edge, as in TeamSpeak.
Icon flag = settings.countryFlags ? CountryFlagIcons.of(cl.country) : null; Icon flag = settings.countryFlags.get() ? CountryFlagIcons.of(cl.country) : null;
if (flag != null) icons.add(flag); if (flag != null) icons.add(flag);
return icons; return icons;
} }
@@ -75,8 +75,8 @@ public final class IconTheme {
/** Re-scans the pack folders and activates the one the settings name. */ /** Re-scans the pack folders and activates the one the settings name. */
public void reload(Settings settings) { public void reload(Settings settings) {
packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir); packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir.get());
IconPack pack = IconPacks.select(packs, settings.iconPack); IconPack pack = IconPacks.select(packs, settings.iconPack.get());
// The shipped pack survives a re-scan as the same object, so setPack alone may not notice. // The shipped pack survives a re-scan as the same object, so setPack alone may not notice.
lookupOrder = IconPacks.lookupOrder(pack, packs, null); lookupOrder = IconPacks.lookupOrder(pack, packs, null);
setPack(pack); setPack(pack);
@@ -173,7 +173,7 @@ public final class IdentitiesDialog extends JDialog {
} }
private String label(IdentityEntry e) { private String label(IdentityEntry e) {
return e.getId().equals(settings.defaultIdentityId) ? e.getName() + " (default)" : e.getName(); return e.getId().equals(settings.defaultIdentityId.get()) ? e.getName() + " (default)" : e.getName();
} }
private void reload() { private void reload() {
@@ -233,8 +233,8 @@ public final class IdentitiesDialog extends JDialog {
runWithProgress("Generating identity…", (cancelled, status) -> { runWithProgress("Generating identity…", (cancelled, status) -> {
IdentityEntry created = identities.generate(name.trim(), level); IdentityEntry created = identities.generate(name.trim(), level);
if (settings.defaultIdentityId == null || identities.byId(settings.defaultIdentityId) == null) { if (settings.defaultIdentityId.get() == null || identities.byId(settings.defaultIdentityId.get()) == null) {
settings.defaultIdentityId = created.getId(); settings.defaultIdentityId.set(created.getId());
settings.save(); settings.save();
} }
return created; return created;
@@ -249,8 +249,8 @@ public final class IdentitiesDialog extends JDialog {
File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile();
try { try {
IdentityEntry imported = identities.importFile(file, null); IdentityEntry imported = identities.importFile(file, null);
if (identities.byId(settings.defaultIdentityId) == null) { if (identities.byId(settings.defaultIdentityId.get()) == null) {
settings.defaultIdentityId = imported.getId(); settings.defaultIdentityId.set(imported.getId());
settings.save(); settings.save();
} }
reload(); reload();
@@ -315,7 +315,7 @@ public final class IdentitiesDialog extends JDialog {
private void setSelectedDefault() { private void setSelectedDefault() {
IdentityEntry e = list.getSelectedValue(); IdentityEntry e = list.getSelectedValue();
if (e == null) return; if (e == null) return;
settings.defaultIdentityId = e.getId(); settings.defaultIdentityId.set(e.getId());
settings.save(); settings.save();
reload(); reload();
} }
@@ -260,16 +260,16 @@ final class MainCommands {
/** Asks for a new nickname, used on every server. */ /** Asks for a new nickname, used on every server. */
void changeNickname() { void changeNickname() {
String nickname = JOptionPane.showInputDialog(frame, "New nickname:", settings.nickname); String nickname = JOptionPane.showInputDialog(frame, "New nickname:", settings.nickname.get());
if (nickname != null) changeNickname(nickname); if (nickname != null) changeNickname(nickname);
} }
/** Uses this nickname on every server; a blank one is ignored. */ /** Uses this nickname on every server; a blank one is ignored. */
void changeNickname(String nickname) { void changeNickname(String nickname) {
if (nickname == null || nickname.isBlank()) return; if (nickname == null || nickname.isBlank()) return;
settings.nickname = nickname.trim(); settings.nickname.set(nickname.trim());
settings.save(); settings.save();
sessions.setNickname(settings.nickname); sessions.setNickname(settings.nickname.get());
} }
void joinChannel(List<ServerSession> targets, String path) { void joinChannel(List<ServerSession> targets, String path) {
@@ -378,15 +378,6 @@ final class MainCommands {
// ---- the window ---- // ---- the window ----
/** Master volume, output device and receive buffer are global, so they go to every connection. */
void applyOutputSettings() {
frame.applyOutputSettingsToAllTabs();
}
void showStatusBar(boolean visible) {
frame.showStatusBar(visible);
}
// ---- the client's own windows ---- // ---- the client's own windows ----
void showGiantPtt() { void showGiantPtt() {
@@ -10,6 +10,7 @@ import eu.lixko.ts3j.client.config.Bookmark;
import eu.lixko.ts3j.client.config.Bookmarks; import eu.lixko.ts3j.client.config.Bookmarks;
import eu.lixko.ts3j.client.session.ServerLink; import eu.lixko.ts3j.client.session.ServerLink;
import eu.lixko.ts3j.client.config.IdentityStore; import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.config.Setting;
import eu.lixko.ts3j.client.config.Settings; import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.myts.ChatAttachments; import eu.lixko.ts3j.client.myts.ChatAttachments;
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin; import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin;
@@ -102,12 +103,12 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
public MainFrame(Settings settings) { public MainFrame(Settings settings) {
super("TeamSpook TS3j"); super("TeamSpook TS3j");
this.settings = settings; this.settings = settings;
this.chatZoom = new TextZoom(settings.chatZoom, z -> { this.chatZoom = new TextZoom(settings.chatZoom.get(), z -> {
settings.chatZoom = z; settings.chatZoom.set(z);
settings.save(); settings.save();
}); });
this.infoZoom = new TextZoom(settings.infoZoom, z -> { this.infoZoom = new TextZoom(settings.infoZoom.get(), z -> {
settings.infoZoom = z; settings.infoZoom.set(z);
settings.save(); settings.save();
}); });
this.identities = IdentityStore.load(settings); this.identities = IdentityStore.load(settings);
@@ -117,6 +118,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
this.soundPlayer = audio.createSoundPlayer(settings); this.soundPlayer = audio.createSoundPlayer(settings);
this.sounds.setPlayer(soundPlayer); this.sounds.setPlayer(soundPlayer);
this.notifier = new DesktopNotifier(this, settings); this.notifier = new DesktopNotifier(this, settings);
Setting.onAnyChange(this::applyOutputSettingsToAllTabs,
settings.outputDevice, settings.outputVolume, settings.masterVolume, settings.receiveBuffer);
pictures.addSource("tsattach:", attachments::fetchPicture); pictures.addSource("tsattach:", attachments::fetchPicture);
// Any of the client's windows coming to the front counts, a dialog included. // Any of the client's windows coming to the front counts, a dialog included.
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> { KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("activeWindow", e -> {
@@ -170,7 +173,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
statusBar = new StatusBar(commands::stopRecording, commands::showOfflineMessages, () -> { statusBar = new StatusBar(commands::stopRecording, commands::showOfflineMessages, () -> {
if (selected != null) selected.session().cancelReconnect(); if (selected != null) selected.session().cancelReconnect();
}); });
statusBar.setVisible(settings.showStatusBar); statusBar.setVisible(settings.showStatusBar.get());
settings.showStatusBar.addListener(this::showStatusBar);
add(statusBar, BorderLayout.SOUTH); add(statusBar, BorderLayout.SOUTH);
statusBar.setCodec(audio.description()); statusBar.setCodec(audio.description());
@@ -311,7 +315,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
menuBar.rebuildBookmarks(); menuBar.rebuildBookmarks();
} }
void showStatusBar(boolean visible) { private void showStatusBar(boolean visible) {
statusBar.setVisible(visible); statusBar.setVisible(visible);
revalidate(); revalidate();
repaint(); repaint();
@@ -413,9 +417,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
} }
void adjustMasterVolume(double delta) { void adjustMasterVolume(double delta) {
settings.outputVolume = Math.max(0, Math.min(2.0, settings.outputVolume + delta)); settings.outputVolume.set(Math.max(0, Math.min(2.0, settings.outputVolume.get() + delta)));
settings.save(); settings.save();
applyOutputSettingsToAllTabs();
updateStatusLabel(); updateStatusLabel();
} }
@@ -510,9 +513,9 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
private void startConnection(String address, int port, String nickname, String password, String identityId, private void startConnection(String address, int port, String nickname, String password, String identityId,
String channel, String channelPassword, boolean replaceCurrent, boolean mytsFeatures) { String channel, String channelPassword, boolean replaceCurrent, boolean mytsFeatures) {
settings.lastAddress = address + ":" + port; settings.lastAddress.set(address + ":" + port);
if (!nickname.isBlank()) settings.nickname = nickname; if (!nickname.isBlank()) settings.nickname.set(nickname);
settings.serverPassword = password; settings.serverPassword.set(password);
settings.save(); settings.save();
ServerTab tab = (replaceCurrent && selected != null) ? selected : tabForNewConnection(); ServerTab tab = (replaceCurrent && selected != null) ? selected : tabForNewConnection();
@@ -626,10 +629,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
sounds, hotkeys, sounds, hotkeys,
new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings, contacts), new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings, contacts),
this::bookmarksChanged, this::myTeamSpeakChanged), this::bookmarksChanged, this::myTeamSpeakChanged),
() -> { this::contactsChanged);
applyOutputSettingsToAllTabs();
contactsChanged();
});
dlg.setVisible(true); dlg.setVisible(true);
} }
@@ -661,14 +661,14 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener {
} }
/** Master volume, output device and receive buffer are global, so push them to every open connection. */ /** Master volume, output device and receive buffer are global, so push them to every open connection. */
void applyOutputSettingsToAllTabs() { private void applyOutputSettingsToAllTabs() {
soundPlayer.setOutputDevice(settings.outputDevice); soundPlayer.setOutputDevice(settings.outputDevice.get());
for (ServerTab tab : tabs) { for (ServerTab tab : tabs) {
VoiceOutput playback = tab.session().playback(); VoiceOutput playback = tab.session().playback();
if (playback == null) continue; if (playback == null) continue;
playback.setMasterVolume(settings.effectiveOutputVolume()); playback.setMasterVolume(settings.effectiveOutputVolume());
playback.setOutputDevice(settings.outputDevice); playback.setOutputDevice(settings.outputDevice.get());
playback.setReceiveBuffer(settings.receiveBuffer); playback.setReceiveBuffer(settings.receiveBuffer.get());
} }
} }
@@ -16,8 +16,6 @@ import javax.swing.JPopupMenu;
import javax.swing.JSlider; import javax.swing.JSlider;
import javax.swing.JToggleButton; import javax.swing.JToggleButton;
import javax.swing.JToolBar; import javax.swing.JToolBar;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.Component; import java.awt.Component;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.FlowLayout; import java.awt.FlowLayout;
@@ -96,7 +94,7 @@ final class MainToolbar extends JToolBar {
add(settingsButton); add(settingsButton);
add(Box.createHorizontalGlue()); add(Box.createHorizontalGlue());
masterVolumePanel = buildMasterVolumeControl(); masterVolumePanel = buildMasterVolumeControl();
masterVolumePanel.setVisible(settings.showMasterVolumeSlider); masterVolumePanel.setVisible(settings.showMasterVolumeSlider.get());
add(masterVolumePanel); add(masterVolumePanel);
hostButton = new HostButtonView(pictures); hostButton = new HostButtonView(pictures);
add(hostButton); add(hostButton);
@@ -136,14 +134,13 @@ final class MainToolbar extends JToolBar {
icon.setToolTipText("Master volume (voice + notifications)"); icon.setToolTipText("Master volume (voice + notifications)");
icon.setAlignmentY(Component.CENTER_ALIGNMENT); icon.setAlignmentY(Component.CENTER_ALIGNMENT);
JSlider slider = new JSlider(0, 200, (int) Math.round(settings.masterVolume * 100)); JSlider slider = new JSlider(0, 200, (int) Math.round(settings.masterVolume.get() * 100));
slider.setOpaque(false); slider.setOpaque(false);
slider.setToolTipText("Master volume (voice + notifications) — scroll to adjust"); slider.setToolTipText("Master volume (voice + notifications) — scroll to adjust");
slider.setAlignmentY(Component.CENTER_ALIGNMENT); slider.setAlignmentY(Component.CENTER_ALIGNMENT);
slider.setPreferredSize(new Dimension(UIScale.scale(135), slider.getPreferredSize().height)); slider.setPreferredSize(new Dimension(UIScale.scale(135), slider.getPreferredSize().height));
slider.addChangeListener(e -> { slider.addChangeListener(e -> {
settings.masterVolume = slider.getValue() / 100.0; settings.masterVolume.set(slider.getValue() / 100.0);
commands.applyOutputSettings();
// Only touch the disk once the drag (or a wheel step) has settled. // Only touch the disk once the drag (or a wheel step) has settled.
if (!slider.getValueIsAdjusting()) settings.save(); if (!slider.getValueIsAdjusting()) settings.save();
}); });
@@ -162,41 +159,27 @@ final class MainToolbar extends JToolBar {
private JPopupMenu buildContextMenu() { private JPopupMenu buildContextMenu() {
JPopupMenu menu = new JPopupMenu(); JPopupMenu menu = new JPopupMenu();
JCheckBoxMenuItem statusBarItem = new JCheckBoxMenuItem("Show Status Bar", settings.showStatusBar); JCheckBoxMenuItem statusBarItem = new JCheckBoxMenuItem("Show Status Bar", settings.showStatusBar.get());
statusBarItem.addActionListener(e -> { statusBarItem.addActionListener(e -> {
settings.showStatusBar = statusBarItem.isSelected(); settings.showStatusBar.set(statusBarItem.isSelected());
settings.save(); settings.save();
commands.showStatusBar(settings.showStatusBar);
}); });
settings.showStatusBar.addListener(statusBarItem::setSelected);
JCheckBoxMenuItem volumeItem = new JCheckBoxMenuItem("Show Master Volume Slider", settings.showMasterVolumeSlider); JCheckBoxMenuItem volumeItem = new JCheckBoxMenuItem("Show Master Volume Slider", settings.showMasterVolumeSlider.get());
volumeItem.addActionListener(e -> { volumeItem.addActionListener(e -> {
settings.showMasterVolumeSlider = volumeItem.isSelected(); settings.showMasterVolumeSlider.set(volumeItem.isSelected());
settings.save(); settings.save();
masterVolumePanel.setVisible(settings.showMasterVolumeSlider); });
settings.showMasterVolumeSlider.addListener(shown -> {
volumeItem.setSelected(shown);
masterVolumePanel.setVisible(shown);
revalidate(); revalidate();
repaint(); repaint();
}); });
menu.add(statusBarItem); menu.add(statusBarItem);
menu.add(volumeItem); menu.add(volumeItem);
// Either toggle can also be flipped elsewhere (or via settings.properties), so
// re-sync the ticks each time the menu is about to be shown.
menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
statusBarItem.setSelected(settings.showStatusBar);
volumeItem.setSelected(settings.showMasterVolumeSlider);
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
return menu; return menu;
} }
} }
@@ -60,7 +60,7 @@ final class MicrophoneTest {
input.setLevelListener(db -> SwingUtilities.invokeLater(() -> onLevel.accept(db))); input.setLevelListener(db -> SwingUtilities.invokeLater(() -> onLevel.accept(db)));
input.setTalkListener(talking -> SwingUtilities.invokeLater(() -> onTransmitting.accept(talking))); input.setTalkListener(talking -> SwingUtilities.invokeLater(() -> onTransmitting.accept(talking)));
input.setMonitorListener(this::enqueueForLoopback); input.setMonitorListener(this::enqueueForLoopback);
this.outputDevice = settings.outputDevice; this.outputDevice = settings.outputDevice.get();
try { try {
input.start(); input.start();
} catch (RuntimeException e) { } catch (RuntimeException e) {
@@ -34,7 +34,7 @@ final class NetworkPanel extends FormPanel {
this.liveMic = liveMic; this.liveMic = liveMic;
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
int kbits = Math.max(MIN_BITRATE_KBITS, Math.min(MAX_BITRATE_KBITS, settings.bitrate / 1000)); int kbits = Math.max(MIN_BITRATE_KBITS, Math.min(MAX_BITRATE_KBITS, settings.bitrate.get() / 1000));
bitrateSlider = new JSlider(MIN_BITRATE_KBITS, MAX_BITRATE_KBITS, kbits); bitrateSlider = new JSlider(MIN_BITRATE_KBITS, MAX_BITRATE_KBITS, kbits);
JLabel bitrateLabel = new JLabel(kbits + " kbit/s"); JLabel bitrateLabel = new JLabel(kbits + " kbit/s");
bitrateSlider.addChangeListener(e -> { bitrateSlider.addChangeListener(e -> {
@@ -42,28 +42,28 @@ final class NetworkPanel extends FormPanel {
pushEncoder.run(); pushEncoder.run();
}); });
vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr); vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr.get());
fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec); fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec.get());
vbrCheck.addActionListener(e -> pushEncoder.run()); vbrCheck.addActionListener(e -> pushEncoder.run());
fecCheck.addActionListener(e -> pushEncoder.run()); fecCheck.addActionListener(e -> pushEncoder.run());
complexitySlider = new JSlider(0, 10, settings.complexity); complexitySlider = new JSlider(0, 10, settings.complexity.get());
JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity)); JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity.get()));
complexitySlider.addChangeListener(e -> { complexitySlider.addChangeListener(e -> {
complexityLabel.setText(String.valueOf(complexitySlider.getValue())); complexityLabel.setText(String.valueOf(complexitySlider.getValue()));
pushEncoder.run(); pushEncoder.run();
}); });
musicCheck = new JCheckBox("Music codec (stereo, higher fidelity)", settings.music); musicCheck = new JCheckBox("Music codec (stereo, higher fidelity)", settings.music.get());
musicCheck.setToolTipText("<html>Transmits <b>OPUS_MUSIC</b>: stereo when the capture " musicCheck.setToolTipText("<html>Transmits <b>OPUS_MUSIC</b>: stereo when the capture "
+ "device has two channels, and without the voice pre-processing " + "device has two channels, and without the voice pre-processing "
+ "(noise removal, typing attenuation, AGC).<br>" + "(noise removal, typing attenuation, AGC).<br>"
+ "Voice mode (<b>OPUS_VOICE</b>) is mono, as in the official client.</html>"); + "Voice mode (<b>OPUS_VOICE</b>) is mono, as in the official client.</html>");
musicCheck.addActionListener(e -> pushEncoder.run()); musicCheck.addActionListener(e -> pushEncoder.run());
delaySlider = choiceSlider(Settings.REDUNDANCY_DELAYS, settings.redundancyDelay); delaySlider = choiceSlider(Settings.REDUNDANCY_DELAYS, settings.redundancyDelay.get());
JLabel delayLabel = new JLabel(delayLabel(selectedDelay())); JLabel delayLabel = new JLabel(delayLabel(selectedDelay()));
int copies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, settings.redundancyCopies)); int copies = Math.max(1, Math.min(Settings.MAX_REDUNDANCY_COPIES, settings.redundancyCopies.get()));
copiesSlider = new JSlider(1, Settings.MAX_REDUNDANCY_COPIES, copies); copiesSlider = new JSlider(1, Settings.MAX_REDUNDANCY_COPIES, copies);
copiesSlider.setMajorTickSpacing(1); copiesSlider.setMajorTickSpacing(1);
copiesSlider.setPaintTicks(true); copiesSlider.setPaintTicks(true);
@@ -84,7 +84,7 @@ final class NetworkPanel extends FormPanel {
pushRedundancy(); pushRedundancy();
}); });
receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer); receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer.get());
JLabel receiveBufferLabel = new JLabel(delayLabel(selectedReceiveBuffer())); JLabel receiveBufferLabel = new JLabel(delayLabel(selectedReceiveBuffer()));
receiveBufferSlider.addChangeListener(e -> receiveBufferLabel.setText(delayLabel(selectedReceiveBuffer()))); receiveBufferSlider.addChangeListener(e -> receiveBufferLabel.setText(delayLabel(selectedReceiveBuffer())));
@@ -138,13 +138,13 @@ final class NetworkPanel extends FormPanel {
/** Copies the page into {@code target}, without touching anything else. */ /** Copies the page into {@code target}, without touching anything else. */
void writeInto(Settings target) { void writeInto(Settings target) {
target.bitrate = bitrateSlider.getValue() * 1000; target.bitrate.set(bitrateSlider.getValue() * 1000);
target.vbr = vbrCheck.isSelected(); target.vbr.set(vbrCheck.isSelected());
target.fec = fecCheck.isSelected(); target.fec.set(fecCheck.isSelected());
target.complexity = complexitySlider.getValue(); target.complexity.set(complexitySlider.getValue());
target.music = musicCheck.isSelected(); target.music.set(musicCheck.isSelected());
target.redundancyDelay = selectedDelay(); target.redundancyDelay.set(selectedDelay());
target.redundancyCopies = copiesSlider.getValue(); target.redundancyCopies.set(copiesSlider.getValue());
target.receiveBuffer = selectedReceiveBuffer(); target.receiveBuffer.set(selectedReceiveBuffer());
} }
} }
@@ -88,10 +88,10 @@ final class NotificationsPanel extends JPanel {
this.settings = settings; this.settings = settings;
this.sounds = sounds; this.sounds = sounds;
this.working = settings.notifications.copy(); this.working = settings.notifications.copy();
this.originalPackId = settings.soundPack; this.originalPackId = settings.soundPack.get();
this.originalPackDir = settings.soundPackDir; this.originalPackDir = settings.soundPackDir.get();
this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume * 100)); this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume.get() * 100));
this.packDirField = new JTextField(settings.soundPackDir, 18); this.packDirField = new JTextField(settings.soundPackDir.get(), 18);
buildRows(); buildRows();
this.table = buildTable(); this.table = buildTable();
@@ -107,21 +107,21 @@ final class NotificationsPanel extends JPanel {
/** Copies the edited state into the settings; the caller saves them. */ /** Copies the edited state into the settings; the caller saves them. */
void apply() { void apply() {
settings.notifications.copyFrom(working); settings.notifications.copyFrom(working);
settings.soundVolume = volume.getValue() / 100.0; settings.soundVolume.set(volume.getValue() / 100.0);
String directory = packDirField.getText().trim(); String directory = packDirField.getText().trim();
boolean rescan = !directory.equals(settings.soundPackDir); boolean rescan = !directory.equals(settings.soundPackDir.get());
settings.soundPackDir = directory; settings.soundPackDir.set(directory);
settings.desktopNotifications = desktopNotifications.isSelected(); settings.desktopNotifications.set(desktopNotifications.isSelected());
sounds.setPack((SoundPack) packCombo.getSelectedItem()); sounds.setPack((SoundPack) packCombo.getSelectedItem());
if (rescan) sounds.reload(); if (rescan) sounds.reload();
originalPackId = settings.soundPack; originalPackId = settings.soundPack.get();
originalPackDir = settings.soundPackDir; originalPackDir = settings.soundPackDir.get();
} }
/** Puts back the pack (and folder) last applied, for a cancelled edit. */ /** Puts back the pack (and folder) last applied, for a cancelled edit. */
void revert() { void revert() {
settings.soundPackDir = originalPackDir; settings.soundPackDir.set(originalPackDir);
settings.soundPack = originalPackId; settings.soundPack.set(originalPackId);
sounds.reload(); sounds.reload();
} }
@@ -162,7 +162,7 @@ final class NotificationsPanel extends JPanel {
packDirField.setToolTipText("Extra folder to look for sound packs in"); packDirField.setToolTipText("Extra folder to look for sound packs in");
addRow(p, c, row++, new JLabel("Extra pack folder:"), dirRow); addRow(p, c, row++, new JLabel("Extra pack folder:"), dirRow);
desktopNotifications.setSelected(settings.desktopNotifications); desktopNotifications.setSelected(settings.desktopNotifications.get());
c.gridx = 0; c.gridx = 0;
c.gridy = row; c.gridy = row;
c.gridwidth = 2; c.gridwidth = 2;
@@ -283,7 +283,7 @@ final class NotificationsPanel extends JPanel {
if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current));
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); packDirField.setText(chooser.getSelectedFile().getAbsolutePath());
settings.soundPackDir = packDirField.getText(); settings.soundPackDir.set(packDirField.getText());
reloadPacks(); reloadPacks();
} }
@@ -29,15 +29,17 @@ final class PlaybackPanel extends FormPanel {
Consumer<String> onOutputDeviceChanged) { Consumer<String> onOutputDeviceChanged) {
GridBagConstraints c = gbc(); GridBagConstraints c = gbc();
outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice); outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice.get());
limitWidth(outputCombo, FIELD_WIDTH); limitWidth(outputCombo, FIELD_WIDTH);
outputCombo.addActionListener(e -> onOutputDeviceChanged.accept(AudioDevices.selectedId(outputCombo))); outputCombo.addActionListener(e -> onOutputDeviceChanged.accept(AudioDevices.selectedId(outputCombo)));
outputVol = new JSlider(0, 200, (int) Math.round(settings.outputVolume * 100)); outputVol = new JSlider(0, 200, (int) Math.round(settings.outputVolume.get() * 100));
JLabel volumeLabel = new JLabel(outputVol.getValue() + "%"); JLabel volumeLabel = new JLabel(outputVol.getValue() + "%");
outputVol.addChangeListener(e -> { outputVol.addChangeListener(e -> {
volumeLabel.setText(outputVol.getValue() + "%"); volumeLabel.setText(outputVol.getValue() + "%");
if (livePlayback != null) livePlayback.setMasterVolume(outputVol.getValue() / 100.0); if (livePlayback != null) {
livePlayback.setMasterVolume(outputVol.getValue() / 100.0 * settings.masterVolume.get());
}
}); });
JButton testSound = new JButton("Play Test Sound"); JButton testSound = new JButton("Play Test Sound");
@@ -56,7 +58,7 @@ final class PlaybackPanel extends FormPanel {
/** Copies the form into {@code target}, without touching anything else. */ /** Copies the form into {@code target}, without touching anything else. */
void writeInto(Settings target) { void writeInto(Settings target) {
target.outputDevice = AudioDevices.selectedId(outputCombo); target.outputDevice.set(AudioDevices.selectedId(outputCombo));
target.outputVolume = outputVol.getValue() / 100.0; target.outputVolume.set(outputVol.getValue() / 100.0);
} }
} }
@@ -35,7 +35,7 @@ final class RecordingActions {
if (chooser.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return; if (chooser.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return;
File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile();
if (!file.getName().toLowerCase().endsWith(".ogg")) file = new File(file.getParentFile(), file.getName() + ".ogg"); if (!file.getName().toLowerCase().endsWith(".ogg")) file = new File(file.getParentFile(), file.getName() + ".ogg");
settings.recordingDir = file.getParentFile().getAbsolutePath(); settings.recordingDir.set(file.getParentFile().getAbsolutePath());
settings.save(); settings.save();
session.startRecording(mode(multitrack), file.toPath()); session.startRecording(mode(multitrack), file.toPath());
} }
@@ -154,12 +154,11 @@ final class ServerTab {
leftColumn = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, infoPanel); leftColumn = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, infoPanel);
leftColumn.setContinuousLayout(true); leftColumn.setContinuousLayout(true);
normalDividerSize = leftColumn.getDividerSize(); normalDividerSize = leftColumn.getDividerSize();
SplitRatio.keep(leftColumn, () -> settings.infoSplitRatio, r -> settings.infoSplitRatio = r, SplitRatio.keep(leftColumn, settings.infoSplitRatio, infoPanel::isVisible);
infoPanel::isVisible);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftColumn, chatPanel); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftColumn, chatPanel);
split.setContinuousLayout(true); split.setContinuousLayout(true);
SplitRatio.keep(split, () -> settings.chatSplitRatio, r -> settings.chatSplitRatio = r, () -> true); SplitRatio.keep(split, settings.chatSplitRatio, () -> true);
this.component = split; this.component = split;
} }
@@ -59,7 +59,7 @@ final class ServerTabConnectionEvents implements ServerSession.Listener {
@Override @Override
public void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text) { public void onOwnChat(ChatScope scope, int peerClientId, String peerName, String text) {
String me = settings.nickname + " (you)"; String me = settings.nickname.get() + " (you)";
int myId = session.selfClientId(); int myId = session.selfClientId();
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
switch (scope) { switch (scope) {
@@ -84,7 +84,7 @@ final class ServerTreeCellRenderer extends DefaultTreeCellRenderer {
/** Friends and blocked clients stand out by colour, as in TeamSpeak, unless turned off. */ /** Friends and blocked clients stand out by colour, as in TeamSpeak, unless turned off. */
private Color contactColor(Contact contact) { private Color contactColor(Contact contact) {
if (contact == null || !settings.colorContacts) return Theme.treeText(); if (contact == null || !settings.colorContacts.get()) return Theme.treeText();
switch (contact.type) { switch (contact.type) {
case FRIEND: case FRIEND:
return Theme.friend(); return Theme.friend();
@@ -37,7 +37,6 @@ public final class SettingsDialog extends JDialog {
private static int lastPage; private static int lastPage;
private final Settings settings; private final Settings settings;
private final VoiceOutput livePlayback;
private final Runnable onApply; private final Runnable onApply;
private final ApplicationPanel applicationPanel; private final ApplicationPanel applicationPanel;
@@ -56,7 +55,6 @@ public final class SettingsDialog extends JDialog {
Runnable onApply) { Runnable onApply) {
super(owner, "Options", true); super(owner, "Options", true);
this.settings = settings; this.settings = settings;
this.livePlayback = livePlayback;
this.onApply = onApply; this.onApply = onApply;
applicationPanel = new ApplicationPanel(settings); applicationPanel = new ApplicationPanel(settings);
@@ -184,10 +182,10 @@ public final class SettingsDialog extends JDialog {
*/ */
private Settings audioSnapshot() { private Settings audioSnapshot() {
Settings snapshot = new Settings(); Settings snapshot = new Settings();
snapshot.packetLoss = settings.packetLoss; snapshot.packetLoss.set(settings.packetLoss.get());
writeAudioSettings(snapshot); writeAudioSettings(snapshot);
if (snapshot.inputMode == Settings.InputMode.PUSH_TO_TALK) { if (snapshot.inputMode.get() == Settings.InputMode.PUSH_TO_TALK) {
snapshot.inputMode = Settings.InputMode.VOICE_ACTIVATION; snapshot.inputMode.set(Settings.InputMode.VOICE_ACTIVATION);
} }
return snapshot; return snapshot;
} }
@@ -203,10 +201,6 @@ public final class SettingsDialog extends JDialog {
settings.save(); settings.save();
capturePanel.applyLive(m -> m.apply(settings)); capturePanel.applyLive(m -> m.apply(settings));
if (livePlayback != null) {
livePlayback.setMasterVolume(settings.outputVolume);
livePlayback.setOutputDevice(settings.outputDevice);
}
if (onApply != null) onApply.run(); if (onApply != null) onApply.run();
} }
@@ -1,11 +1,11 @@
package eu.lixko.ts3j.client.ui; package eu.lixko.ts3j.client.ui;
import eu.lixko.ts3j.client.config.Setting;
import javax.swing.JSplitPane; import javax.swing.JSplitPane;
import java.awt.event.ComponentAdapter; import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent; import java.awt.event.ComponentEvent;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleSupplier;
/** /**
* Keeps a split pane's divider at the share of its span the user gave it: restores the saved * Keeps a split pane's divider at the share of its span the user gave it: restores the saved
@@ -15,8 +15,7 @@ import java.util.function.DoubleSupplier;
final class SplitRatio { final class SplitRatio {
private final JSplitPane split; private final JSplitPane split;
private final DoubleSupplier saved; private final Setting<Double> saved;
private final DoubleConsumer save;
private final BooleanSupplier tracking; private final BooleanSupplier tracking;
/** The span at the last divider move; another span means a layout moved it, not the user. */ /** The span at the last divider move; another span means a layout moved it, not the user. */
private int lastSpan; private int lastSpan;
@@ -26,23 +25,22 @@ final class SplitRatio {
* @param tracking whether the divider is the user's to place right now; while it is not * @param tracking whether the divider is the user's to place right now; while it is not
* (a side collapsed, say), moves are neither saved nor corrected * (a side collapsed, say), moves are neither saved nor corrected
*/ */
static void keep(JSplitPane split, DoubleSupplier saved, DoubleConsumer save, BooleanSupplier tracking) { static void keep(JSplitPane split, Setting<Double> saved, BooleanSupplier tracking) {
new SplitRatio(split, saved, save, tracking); new SplitRatio(split, saved, tracking);
} }
private SplitRatio(JSplitPane split, DoubleSupplier saved, DoubleConsumer save, BooleanSupplier tracking) { private SplitRatio(JSplitPane split, Setting<Double> saved, BooleanSupplier tracking) {
this.split = split; this.split = split;
this.saved = saved; this.saved = saved;
this.save = save;
this.tracking = tracking; this.tracking = tracking;
split.setResizeWeight(saved.getAsDouble()); split.setResizeWeight(saved.get());
split.addComponentListener(new ComponentAdapter() { split.addComponentListener(new ComponentAdapter() {
@Override @Override
public void componentResized(ComponentEvent e) { public void componentResized(ComponentEvent e) {
if (restored || span() <= 0) return; if (restored || span() <= 0) return;
restored = true; restored = true;
lastSpan = span(); lastSpan = span();
split.setDividerLocation(saved.getAsDouble()); split.setDividerLocation(saved.get());
} }
}); });
split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, e -> moved()); split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, e -> moved());
@@ -57,7 +55,7 @@ final class SplitRatio {
} }
double ratio = split.getDividerLocation() / (double) span; double ratio = split.getDividerLocation() / (double) span;
if (ratio <= 0.05 || ratio >= 0.98) return; if (ratio <= 0.05 || ratio >= 0.98) return;
save.accept(ratio); saved.set(ratio);
// Space the pane gains or loses is shared out in the same proportion. // Space the pane gains or loses is shared out in the same proportion.
split.setResizeWeight(ratio); split.setResizeWeight(ratio);
} }
@@ -74,7 +74,7 @@ final class VoiceActivationSection {
group.add(pttRadio); group.add(pttRadio);
group.add(contRadio); group.add(contRadio);
group.add(vadRadio); group.add(vadRadio);
switch (settings.inputMode) { switch (settings.inputMode.get()) {
case PUSH_TO_TALK: case PUSH_TO_TALK:
pttRadio.setSelected(true); pttRadio.setSelected(true);
break; break;
@@ -89,25 +89,25 @@ final class VoiceActivationSection {
pttKeyButton.setToolTipText("Push-to-talk is a global hotkey; this opens its binding"); pttKeyButton.setToolTipText("Push-to-talk is a global hotkey; this opens its binding");
pttKeyButton.addActionListener(e -> editPushToTalkHotkey()); pttKeyButton.addActionListener(e -> editPushToTalkHotkey());
vadOverPttCheck = new JCheckBox("Add Voice Activity Detection", settings.vadOverPtt); vadOverPttCheck = new JCheckBox("Add Voice Activity Detection", settings.vadOverPtt.get());
vadOverPttCheck.addActionListener(e -> vadOverPttCheck.addActionListener(e ->
micTest.configure(m -> m.setVadOverPtt(vadOverPttCheck.isSelected()))); micTest.configure(m -> m.setVadOverPtt(vadOverPttCheck.isSelected())));
vadModeCombo = new JComboBox<>(new String[]{"Automatic", "Volume Gate", "Hybrid"}); vadModeCombo = new JComboBox<>(new String[]{"Automatic", "Volume Gate", "Hybrid"});
vadModeCombo.setSelectedIndex(vadModeIndex(settings.vadMode)); vadModeCombo.setSelectedIndex(vadModeIndex(settings.vadMode.get()));
vadModeCombo.addActionListener(e -> micTest.configure(m -> m.setVadMode(currentVadMode()))); vadModeCombo.addActionListener(e -> micTest.configure(m -> m.setVadMode(currentVadMode())));
vadModeCombo.setToolTipText("<html><b>Automatic</b>: intelligent speech detection.<br>" vadModeCombo.setToolTipText("<html><b>Automatic</b>: intelligent speech detection.<br>"
+ "<b>Volume Gate</b>: transmit when loud enough.<br>" + "<b>Volume Gate</b>: transmit when loud enough.<br>"
+ "<b>Hybrid</b>: loud enough <i>and</i> detected as speech.</html>"); + "<b>Hybrid</b>: loud enough <i>and</i> detected as speech.</html>");
thresholdSlider = new JSlider((int) InputLevel.MIN_DB, (int) InputLevel.MAX_DB, thresholdSlider = new JSlider((int) InputLevel.MIN_DB, (int) InputLevel.MAX_DB,
(int) Math.round(settings.vadThresholdDb)); (int) Math.round(settings.vadThresholdDb.get()));
thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb) + " dB"); thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb.get()) + " dB");
speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold * 100)); speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold.get() * 100));
speechLabel = new JLabel(Math.round(settings.speechThreshold * 100) + "%"); speechLabel = new JLabel(Math.round(settings.speechThreshold.get() * 100) + "%");
meter = new LevelMeter(); meter = new LevelMeter();
meter.setThreshold(settings.vadThresholdDb); meter.setThreshold(settings.vadThresholdDb.get());
testControls = buildTestControls(); testControls = buildTestControls();
thresholdSlider.addChangeListener(e -> { thresholdSlider.addChangeListener(e -> {
@@ -180,13 +180,13 @@ final class VoiceActivationSection {
/** Copies the form into {@code target}, without touching anything else. */ /** Copies the form into {@code target}, without touching anything else. */
void writeInto(Settings target) { void writeInto(Settings target) {
target.inputMode = pttRadio.isSelected() ? Settings.InputMode.PUSH_TO_TALK target.inputMode.set(pttRadio.isSelected() ? Settings.InputMode.PUSH_TO_TALK
: contRadio.isSelected() ? Settings.InputMode.CONTINUOUS : contRadio.isSelected() ? Settings.InputMode.CONTINUOUS
: Settings.InputMode.VOICE_ACTIVATION; : Settings.InputMode.VOICE_ACTIVATION);
target.vadMode = currentVadMode(); target.vadMode.set(currentVadMode());
target.vadThresholdDb = thresholdSlider.getValue(); target.vadThresholdDb.set((double) thresholdSlider.getValue());
target.speechThreshold = speechSlider.getValue() / 100.0; target.speechThreshold.set(speechSlider.getValue() / 100.0);
target.vadOverPtt = vadOverPttCheck.isSelected(); target.vadOverPtt.set(vadOverPttCheck.isSelected());
} }
/** Applies a change to the microphone test, if it is running. */ /** Applies a change to the microphone test, if it is running. */
@@ -30,7 +30,8 @@ final class WindowGeometry {
} }
static void restore(JFrame frame, Settings settings, Dimension defaultSize) { static void restore(JFrame frame, Settings settings, Dimension defaultSize) {
Rectangle saved = new Rectangle(settings.windowX, settings.windowY, settings.windowWidth, settings.windowHeight); Rectangle saved = new Rectangle(settings.windowX.get(), settings.windowY.get(),
settings.windowWidth.get(), settings.windowHeight.get());
if (saved.width > 0 && saved.height > 0 && onScreen(saved)) { if (saved.width > 0 && saved.height > 0 && onScreen(saved)) {
Dimension min = frame.getMinimumSize(); Dimension min = frame.getMinimumSize();
saved.width = Math.max(saved.width, min.width); saved.width = Math.max(saved.width, min.width);
@@ -40,7 +41,7 @@ final class WindowGeometry {
frame.setSize(UIScale.scale(defaultSize)); frame.setSize(UIScale.scale(defaultSize));
frame.setLocationRelativeTo(null); frame.setLocationRelativeTo(null);
} }
if (settings.windowMaximized) frame.setExtendedState(Frame.MAXIMIZED_BOTH); if (settings.windowMaximized.get()) frame.setExtendedState(Frame.MAXIMIZED_BOTH);
track(frame, settings); track(frame, settings);
} }
@@ -48,13 +49,13 @@ final class WindowGeometry {
Timer settle = new Timer(SETTLE_MS, e -> { Timer settle = new Timer(SETTLE_MS, e -> {
int state = frame.getExtendedState(); int state = frame.getExtendedState();
if ((state & Frame.ICONIFIED) != 0 || !frame.isShowing()) return; if ((state & Frame.ICONIFIED) != 0 || !frame.isShowing()) return;
settings.windowMaximized = (state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH; settings.windowMaximized.set((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH);
if (state != Frame.NORMAL) return; if (state != Frame.NORMAL) return;
Rectangle r = frame.getBounds(); Rectangle r = frame.getBounds();
settings.windowX = r.x; settings.windowX.set(r.x);
settings.windowY = r.y; settings.windowY.set(r.y);
settings.windowWidth = r.width; settings.windowWidth.set(r.width);
settings.windowHeight = r.height; settings.windowHeight.set(r.height);
}); });
settle.setRepeats(false); settle.setRepeats(false);
frame.addComponentListener(new ComponentAdapter() { frame.addComponentListener(new ComponentAdapter() {