diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt index 75fa46a..58dc230 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/IconTheme.kt @@ -43,7 +43,7 @@ class IconTheme(private val context: Context, private val settings: Settings) { } fun select(pack: IconPack) { - settings.iconPack = pack.id() + settings.iconPack.set(pack.id()) settings.save() reload() } @@ -100,7 +100,7 @@ class IconTheme(private val context: Context, private val settings: Settings) { private fun reload() { 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) cache.evictAll() _packs.value = packs diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt index bb04ef4..e211314 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/IdentityManager.kt @@ -61,7 +61,7 @@ class IdentityManager( } private fun snapshot(): List = 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) } @@ -93,9 +93,9 @@ class IdentityManager( /** Makes [entry], or else the first identity, the default while there is none. */ 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 - settings.defaultIdentityId = fallback.id + settings.defaultIdentityId.set(fallback.id) settings.save() } @@ -124,10 +124,10 @@ class IdentityManager( /** The nickname of the identity a connect with [id] uses; empty when it has none. */ 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) { - settings.defaultIdentityId = id + settings.defaultIdentityId.set(id) settings.save() refresh() } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt index 026e0d3..cb4785f 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/LevelMonitor.kt @@ -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. */ - private fun testMode() = - if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode + private fun testMode(): Settings.InputMode { + val mode = settings.inputMode.get() + return if (mode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else mode + } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt index d75235c..ec4e733 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ServerController.kt @@ -467,7 +467,7 @@ class ServerController internal constructor( away = session.isAway, selfClientId = if (session.isConnected) session.selfClientId() 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, self = session.selfState(), whisper = session.whisper()?.label, @@ -489,8 +489,8 @@ class ServerController internal constructor( delay(TREE_FRAME_MS) treePending.set(false) if (structureChanged.getAndSet(false)) roots = session.model().buildTree() - _tree.value = ServerTree.of(roots, session.model(), session.contacts().store(), app.settings.colorContacts, - app.settings.countryFlags, app.settings.clientRowColors) + _tree.value = ServerTree.of(roots, session.model(), session.contacts().store(), + app.settings.colorContacts.get(), app.settings.countryFlags.get(), app.settings.clientRowColors) val serverName = if (session.isConnected) session.model().serverName.orEmpty() else "" val channelName = session.currentChannel()?.name.orEmpty() _chats.update { @@ -508,7 +508,7 @@ class ServerController internal constructor( override fun onSystemMessage(text: String) = system(text) 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) append(key(scope, peerClientId), peerName, html) if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt index 716f116..a16edda 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/SessionController.kt @@ -15,6 +15,7 @@ import eu.lixko.ts3j.client.config.BanReasonPresets import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmarks 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.WhisperList import eu.lixko.ts3j.client.config.WhisperLists @@ -185,19 +186,21 @@ class SessionController(private val context: Context) { _contacts.value = contactCopies() _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. */ - fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname } - val lastAddress: String get() = settings.lastAddress + fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname.get() } + val lastAddress: String get() = settings.lastAddress.get() // ---- connection ---- /** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */ fun connect(address: String, nickname: String, password: String = "", identityId: String = "") { val (host, port) = parseAddress(address) - settings.lastAddress = address - if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname + settings.lastAddress.set(address) + if (identities.nicknameOf(identityId).isBlank()) settings.nickname.set(nickname) settings.save() start(host, port, nickname, password, identityId, "", "") } @@ -532,9 +535,8 @@ class SessionController(private val context: Context) { val soundPack: SoundPack? get() = sounds.pack() fun setCountryFlags(shown: Boolean) { - settings.countryFlags = shown + settings.countryFlags.set(shown) settings.save() - servers.value.forEach { it.scheduleTree(structure = false) } } /** 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) { - settings.descriptionPictures = shown + settings.descriptionPictures.set(shown) settings.save() } @@ -598,21 +600,17 @@ class SessionController(private val context: Context) { /** Switches between push to talk and voice activation; returns the new mode. */ fun toggleInputMode(): Settings.InputMode { - settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) - Settings.InputMode.VOICE_ACTIVATION else 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) 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() { settings.save() - soundPlayer.setOutputDevice(settings.outputDevice) try { 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.refresh() 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. */ fun setRoute(route: AudioRoute) { routePrefs.save(route) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt index 14101dc..8759610 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/WebPictures.kt @@ -39,7 +39,7 @@ class WebPictures(cacheDir: File, private val settings: Settings) { fun retryFailed() = downloads.retryFailed() /** 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 { decoded.get(url)?.let { return State.Shown(it) } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt index 6163510..16de6cf 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/NetworkSettingsScreen.kt @@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import eu.lixko.ts3j.client.android.SessionController +import eu.lixko.ts3j.client.config.Setting import eu.lixko.ts3j.client.config.Settings import kotlin.math.abs import kotlin.math.roundToInt @@ -23,56 +24,56 @@ private const val MAX_BITRATE_KBITS = 160f @Composable fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { val settings = vm.settings - fun change(edit: Settings.() -> Unit) { - settings.edit() + fun change(setting: Setting, value: T) { + setting.set(value) vm.applySettings() } - var vbr by remember { mutableStateOf(settings.vbr) } - var fec by remember { mutableStateOf(settings.fec) } - var music by remember { mutableStateOf(settings.music) } - var redundancy by remember { mutableStateOf(settings.redundancyDelay) } - var copies by remember { mutableStateOf(settings.redundancyCopies) } - var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) } + var vbr by remember { mutableStateOf(settings.vbr.get()) } + var fec by remember { mutableStateOf(settings.fec.get()) } + var music by remember { mutableStateOf(settings.music.get()) } + var redundancy by remember { mutableStateOf(settings.redundancyDelay.get()) } + var copies by remember { mutableStateOf(settings.redundancyCopies.get()) } + var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer.get()) } SubScreen("Network", onBack) { padding -> Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { Section("Encoder") - Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { - change { bitrate = it.roundToInt() * 1000 } + Level("Bitrate", settings.bitrate.get() / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { + change(settings.bitrate, it.roundToInt() * 1000) } Toggle("Variable bitrate (VBR)", vbr) { vbr = it - change { this.vbr = it } + change(settings.vbr, it) } Toggle("Forward error correction (FEC)", fec) { fec = it - change { this.fec = it } + change(settings.fec, it) } - Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { - change { complexity = it.roundToInt() } + Level("Complexity", settings.complexity.get().toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { + change(settings.complexity, it.roundToInt()) } Toggle("Music codec (stereo, higher fidelity)", music) { music = it - change { this.music = it } + change(settings.music, it) } Section("Redundancy") ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) { redundancy = it - change { redundancyDelay = it } + change(settings.redundancyDelay, it) } if (redundancy > 0) { Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" }, steps = Settings.MAX_REDUNDANCY_COPIES - 2) { copies = it.roundToInt() - change { redundancyCopies = copies } + change(settings.redundancyCopies, copies) } } Section("Receive") ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) { receiveBuffer = it - change { this.receiveBuffer = it } + change(settings.receiveBuffer, it) } } } diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt index 5e19be6..9769bcd 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SettingsScreen.kt @@ -72,13 +72,13 @@ private fun DesignScreen(vm: SessionController, onBack: () -> Unit) { SubScreen("Design", onBack) { padding -> Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { 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) { pictures = it vm.setDescriptionPictures(it) } 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) { flags = it vm.setCountryFlags(it) diff --git a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt index 7ad0e3a..333e061 100644 --- a/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt +++ b/android/app/src/main/java/eu/lixko/ts3j/client/android/ui/SoundSettingsScreen.kt @@ -35,6 +35,7 @@ import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.audio.AudioRoute import eu.lixko.ts3j.client.audio.AudioDevice import eu.lixko.ts3j.client.audio.InputLevel +import eu.lixko.ts3j.client.config.Setting import eu.lixko.ts3j.client.config.Settings import kotlin.math.roundToInt @@ -44,17 +45,17 @@ private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB") @Composable fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { val settings = vm.settings - fun change(edit: Settings.() -> Unit) { - settings.edit() + fun change(setting: Setting, value: T) { + setting.set(value) vm.applySettings() } - var inputMode by remember { mutableStateOf(settings.inputMode) } - var vadMode by remember { mutableStateOf(settings.vadMode) } - var agc by remember { mutableStateOf(settings.agc) } - var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) } - var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) } - var inputDevice by remember { mutableStateOf(settings.inputDevice) } - var outputDevice by remember { mutableStateOf(settings.outputDevice) } + var inputMode by remember { mutableStateOf(settings.inputMode.get()) } + var vadMode by remember { mutableStateOf(settings.vadMode.get()) } + var agc by remember { mutableStateOf(settings.agc.get()) } + var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning.get()) } + var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) } + var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) } + var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) } val inputs by vm.inputDevices.collectAsStateWithLifecycle() val outputs by vm.outputDevices.collectAsStateWithLifecycle() val route by vm.route.collectAsStateWithLifecycle() @@ -71,11 +72,11 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { Section("Devices") DevicePicker("Microphone", inputs, inputDevice) { inputDevice = it - change { this.inputDevice = it } + change(settings.inputDevice, it) } DevicePicker("Speaker", outputs, outputDevice) { outputDevice = it - change { this.outputDevice = it } + change(settings.outputDevice, it) } Picker( "Microphone preset", @@ -95,7 +96,7 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { for ((mode, label) in INPUT_MODES) { Choice(label, inputMode == mode) { inputMode = mode - change { this.inputMode = mode } + change(settings.inputMode, mode) } } 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) { Choice(label, vadMode == mode) { vadMode = mode - change { this.vadMode = mode } + change(settings.vadMode, mode) } } 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 }) { - change { vadThresholdDb = it.roundToInt().toDouble() } + change(settings.vadThresholdDb, it.roundToInt().toDouble()) } } if (vadMode != Settings.VadMode.VOLUME_GATE) { - Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { - change { speechThreshold = it.toDouble() } + Level("Speech likelihood", settings.speechThreshold.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { + change(settings.speechThreshold, it.toDouble()) } } } 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(), { DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) { val step = it.roundToInt() - change { - denoise = step > 0 - if (step > 0) denoiserLevel = step - 1 - } + settings.denoise.set(step > 0) + if (step > 0) settings.denoiserLevel.set(step - 1) + vm.applySettings() } Toggle("Automatic gain control", agc) { agc = it - change { this.agc = it } + change(settings.agc, it) } 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) { - change { agcBoostDb = it.roundToInt() } + change(settings.agcBoostDb, it.roundToInt()) } } Section("Playback") - Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { - change { outputVolume = it.toDouble() } + Level("Volume", settings.outputVolume.get().toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { + change(settings.outputVolume, it.toDouble()) } Section("Notification sounds") @@ -161,12 +161,12 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { pack = id } } - Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { - change { soundVolume = it.toDouble() } + Level("Volume", settings.soundVolume.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { + change(settings.soundVolume, it.toDouble()) } Toggle("Beep when talking while muted", mutedTalkWarning) { mutedTalkWarning = it - change { this.mutedTalkWarning = it } + change(settings.mutedTalkWarning, it) } } } diff --git a/ts3-client/AUDIT-STRUCTURE.md b/ts3-client/AUDIT-STRUCTURE.md index 2ac9e2d..ebab0b1 100644 --- a/ts3-client/AUDIT-STRUCTURE.md +++ b/ts3-client/AUDIT-STRUCTURE.md @@ -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 | | 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 | -| 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 | +| 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 | done: each value is a `Setting` (`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 | | 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 | diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java index f76624f..b2777f6 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/AudioBackend.java @@ -24,12 +24,12 @@ public interface AudioBackend { } 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. */ 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. */ diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java index 8841fdc..5f71f15 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/CaptureVoiceInput.java @@ -103,21 +103,21 @@ public final class CaptureVoiceInput implements VoiceInput { public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) { this.io = io; this.opus = opus; - this.deviceName = settings.inputDevice; - this.mode = settings.inputMode; - this.vadMode = settings.vadMode; - this.thresholdDb = settings.vadThresholdDb; - this.speechThreshold = settings.speechThreshold; - this.vadOverPtt = settings.vadOverPtt; - this.inputGain = settings.inputVolume; + this.deviceName = settings.inputDevice.get(); + this.mode = settings.inputMode.get(); + this.vadMode = settings.vadMode.get(); + this.thresholdDb = settings.vadThresholdDb.get(); + this.speechThreshold = settings.speechThreshold.get(); + this.vadOverPtt = settings.vadOverPtt.get(); + this.inputGain = settings.inputVolume.get(); this.params = OpusParameters.from(settings); this.codec = codecFor(params); - setRedundancy(settings.redundancyDelay, settings.redundancyCopies); - processor.setNoiseSuppression(settings.denoise); - processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel)); - processor.setTransientSuppression(settings.typingAttenuation); - processor.setGainControl(settings.agc); - processor.setGainBoost(settings.agcBoostDb); + setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get()); + processor.setNoiseSuppression(settings.denoise.get()); + processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel.get())); + processor.setTransientSuppression(settings.typingAttenuation.get()); + processor.setGainControl(settings.agc.get()); + processor.setGainBoost(settings.agcBoostDb.get()); } // ---- live configuration (safe to call from the UI thread) ---- diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java index b4264f4..9b7fa7b 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/OpusParameters.java @@ -9,7 +9,8 @@ import eu.lixko.ts3j.client.config.Settings; public final class OpusParameters { 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. */ diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java index 5d19606..8785fbc 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/audio/VoiceInput.java @@ -92,19 +92,19 @@ public interface VoiceInput extends Microphone { /** Takes on the voice settings, as they stand now, while capturing. */ default void apply(Settings settings) { - setInputDevice(settings.inputDevice); - setMode(settings.inputMode); - setVadMode(settings.vadMode); - setThresholdDb(settings.vadThresholdDb); - setSpeechThreshold(settings.speechThreshold); - setVadOverPtt(settings.vadOverPtt); - setInputGain(settings.inputVolume); - setNoiseSuppression(settings.denoise); - setDenoiserLevel(settings.denoiserLevel); - setTypingAttenuation(settings.typingAttenuation); - setAgc(settings.agc); - setAgcBoost(settings.agcBoostDb); + setInputDevice(settings.inputDevice.get()); + setMode(settings.inputMode.get()); + setVadMode(settings.vadMode.get()); + setThresholdDb(settings.vadThresholdDb.get()); + setSpeechThreshold(settings.speechThreshold.get()); + setVadOverPtt(settings.vadOverPtt.get()); + setInputGain(settings.inputVolume.get()); + setNoiseSuppression(settings.denoise.get()); + setDenoiserLevel(settings.denoiserLevel.get()); + setTypingAttenuation(settings.typingAttenuation.get()); + setAgc(settings.agc.get()); + setAgcBoost(settings.agcBoostDb.get()); setOpusParameters(OpusParameters.from(settings)); - setRedundancy(settings.redundancyDelay, settings.redundancyCopies); + setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get()); } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java index a281d2d..c00df10 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/IdentityStore.java @@ -117,10 +117,10 @@ public final class IdentityStore { IdentityEntry e = byId(preferredId); if (e != null) return e; - e = byId(settings.defaultIdentityId); + e = byId(settings.defaultIdentityId.get()); if (e == null) { e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0); - settings.defaultIdentityId = e.getId(); + settings.defaultIdentityId.set(e.getId()); settings.save(); } return e; @@ -197,8 +197,8 @@ public final class IdentityStore { //noinspection ResultOfMethodCallIgnored entry.getFile().delete(); - if (entry.getId().equals(settings.defaultIdentityId)) { - settings.defaultIdentityId = entries.isEmpty() ? "" : entries.get(0).getId(); + if (entry.getId().equals(settings.defaultIdentityId.get())) { + settings.defaultIdentityId.set(entries.isEmpty() ? "" : entries.get(0).getId()); settings.save(); } if (bookmarks != null) { diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Setting.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Setting.java new file mode 100644 index 0000000..4183366 --- /dev/null +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Setting.java @@ -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 { + + private final String key; + private final Function parse; + private final Function format; + private final UnaryOperator constrain; + private final List> 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 parse, Function format, UnaryOperator 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 listener : listeners) listener.accept(constrained); + } + + public void addListener(Consumer listener) { + listeners.add(listener); + } + + public void removeListener(Consumer 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)); + } +} diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java index e401495..dbf3476 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/config/Settings.java @@ -1,5 +1,6 @@ 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.sound.NotificationSettings; @@ -7,15 +8,18 @@ import java.io.File; import java.io.FileInputStream; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; 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 * directory (~/.ts3jclient/settings.properties). * *

Holds connection defaults, audio device selection and voice-activation - * parameters. Loaded once at startup and saved whenever the user changes - * something in the options dialog. + * parameters. Loaded once at startup; whoever changes a {@link Setting} saves. */ public final class Settings { @@ -70,143 +74,147 @@ public final class Settings { } private final Properties props = new Properties(); + private final List> all = new ArrayList<>(); // ---- connection ---- - public String lastAddress = "localhost"; - public String nickname = System.getProperty("user.name", "TS3j User"); - public String serverPassword = ""; + public final Setting lastAddress = text("lastAddress", "localhost"); + public final Setting nickname = text("nickname", System.getProperty("user.name", "TS3j User")); + public final Setting serverPassword = text("serverPassword", ""); /** Legacy single-identity file; only used to migrate into the identity store. */ - public String identityFile = AppDirs.file("identity.ini").getAbsolutePath(); + public final Setting identityFile = text("identityFile", AppDirs.file("identity.ini").getAbsolutePath()); /** Id of the identity used when a server doesn't select one of its own. */ - public String defaultIdentityId = ""; + public final Setting defaultIdentityId = text("defaultIdentityId", ""); // ---- reported client version ---- /** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */ - public boolean customVersion = false; + public final Setting customVersion = flag("customVersion", false); /** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */ - public String clientVersion = ClientVersion.DEFAULT.version(); + public final Setting clientVersion = text("clientVersion", ClientVersion.DEFAULT.version()); /** Operating system other clients see, e.g. "Windows". */ - public String clientPlatform = ClientVersion.DEFAULT.platform(); + public final Setting clientPlatform = text("clientPlatform", ClientVersion.DEFAULT.platform()); /** TeamSpeak's signature over the version and platform; servers may verify it. */ - public String clientVersionSign = ClientVersion.DEFAULT.sign(); + public final Setting clientVersionSign = text("clientVersionSign", ClientVersion.DEFAULT.sign()); // ---- audio devices (mixer names; empty = system default) ---- - public String inputDevice = ""; - public String outputDevice = ""; + public final Setting inputDevice = text("inputDevice", ""); + public final Setting outputDevice = text("outputDevice", ""); // ---- voice ---- - public InputMode inputMode = InputMode.VOICE_ACTIVATION; + public final Setting inputMode = choice("inputMode", InputMode.VOICE_ACTIVATION); /** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */ - public VadMode vadMode = VadMode.HYBRID; + public final Setting 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. */ - public double vadThresholdDb = -40.0; + public final Setting vadThresholdDb = decimal("vadLevelDb", -40.0); /** * Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this * {@code vad_likelihood} and also defaults it to 0.5. */ - public double speechThreshold = 0.5; + public final Setting speechThreshold = decimal("speechThreshold", 0.5); /** Keep voice activation running while in push-to-talk mode. */ - public boolean vadOverPtt = false; + public final Setting vadOverPtt = flag("vadOverPtt", false); /** Opus target bitrate in bits/sec. */ - public int bitrate = 48000; + public final Setting bitrate = number("bitrate", 48000); /** Opus complexity 0..10. */ - public int complexity = 10; + public final Setting complexity = number("complexity", 10); /** Opus variable bitrate. */ - public boolean vbr = true; + public final Setting vbr = flag("vbr", true); /** Opus in-band forward error correction. */ - public boolean fec = true; + public final Setting fec = flag("fec", true); /** Expected packet loss percent (drives FEC). */ - public int packetLoss = 5; + public final Setting packetLoss = number("packetLoss", 5); /** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */ - public boolean music = false; + public final Setting music = flag("music", false); /** * 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 * about {@code redundancyDelay * redundancyCopies} of latency. */ - public int redundancyDelay = 0; + public final Setting redundancyDelay = number("redundancyDelay", 0); /** 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}; /** How many times every voice packet is sent again. */ - public int redundancyCopies = 1; + public final Setting redundancyCopies = number("redundancyCopies", 1); public static final int MAX_REDUNDANCY_COPIES = 4; /** * 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. */ - public int receiveBuffer = 0; + public final Setting receiveBuffer = number("receiveBuffer", 0); /** 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}; /** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */ - public double outputVolume = 1.0; + public final Setting outputVolume = decimal("outputVolume", 1.0); /** * Global multiplier on top of {@link #outputVolume} and {@link #soundVolume}, * 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. */ - public double masterVolume = 1.0; + public final Setting masterVolume = decimal("masterVolume", 1.0); /** Microphone input gain multiplier applied before VAD/encode. */ - public double inputVolume = 1.0; + public final Setting inputVolume = decimal("inputVolume", 1.0); /** Remove steady background noise from the microphone (WebRTC noise suppression). */ - public boolean denoise = true; + public final Setting denoise = flag("denoise", true); /** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */ - public int denoiserLevel = 1; + public final Setting denoiserLevel = number("denoiserLevel", 1); /** Attenuate keyboard clicks while typing. */ - public boolean typingAttenuation = true; + public final Setting typingAttenuation = flag("typingAttenuation", true); /** Automatic gain control: normalise microphone loudness to a target level. */ - public boolean agc = true; + public final Setting agc = flag("agc", true); 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. */ - public int agcBoostDb = 0; + public final Setting agcBoostDb = number("agcBoostDb", 0, 0, MAX_AGC_BOOST_DB); /** Beep when speech is picked up while the microphone is muted. */ - public boolean mutedTalkWarning = true; + public final Setting mutedTalkWarning = flag("mutedTalkWarning", true); // ---- notification sounds ---- /** Directory name of the active sound pack; empty picks the first one found. */ - public String soundPack = "default"; + public final Setting soundPack = text("soundPack", "default"); /** Notification sound volume, 0..1. */ - public double soundVolume = 1.0; + public final Setting soundVolume = decimal("soundVolume", 1.0); /** Extra folder to look for sound packs in, on top of the well-known locations. */ - public String soundPackDir = ""; + public final Setting soundPackDir = text("soundPackDir", ""); /** Whether pokes and private messages show a desktop notification while the window is in the background. */ - public boolean desktopNotifications = true; + public final Setting desktopNotifications = flag("desktopNotifications", true); // ---- icons ---- /** File name of the active icon pack; empty uses the built-in icons. */ - public String iconPack = "default_colored_2014.zip"; + public final Setting iconPack = text("iconPack", "default_colored_2014.zip"); /** * Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags; * their details show it beside their name either way. */ - public boolean countryFlags = false; + public final Setting countryFlags = flag("countryFlags", false); /** Background colours of client rows in the channel tree. */ public final ClientRowColors clientRowColors = new ClientRowColors(); /** Extra folder to look for icon packs in, on top of the well-known locations. */ - public String iconPackDir = ""; + public final Setting iconPackDir = text("iconPackDir", ""); /** Look-and-feel variant; see {@link Appearance}. */ - public Appearance appearance = Appearance.LIGHT; + public final Setting appearance = choice("appearance", Appearance.LIGHT); /** Interface scale factor, 1.0 being 100 %; 0 follows the desktop. Read at startup. */ - public double uiScale = 0; + public final Setting uiScale = decimal("uiScale", 0); // ---- window chrome ---- /** Whether the status bar at the bottom of the window is shown. */ - public boolean showStatusBar = true; + public final Setting showStatusBar = flag("showStatusBar", true); /** Whether the Master Volume slider is shown on the toolbar. */ - public boolean showMasterVolumeSlider = true; + public final Setting showMasterVolumeSlider = flag("showMasterVolumeSlider", true); /** Share of the tree/info column the tree takes, i.e. where their divider sits. */ - public double infoSplitRatio = 0.68; + public final Setting infoSplitRatio = decimal("infoSplitRatio", 0.68); /** Share of the window's width the tree/info column takes, beside the chat. */ - public double chatSplitRatio = 0.45; + public final Setting chatSplitRatio = decimal("chatSplitRatio", 0.45); /** The main window's bounds when not maximised; a width of 0 until it has been placed. */ - public int windowX, windowY, windowWidth, windowHeight; - public boolean windowMaximized; + public final Setting windowX = number("windowX", 0); + public final Setting windowY = number("windowY", 0); + public final Setting windowWidth = number("windowWidth", 0); + public final Setting windowHeight = number("windowHeight", 0); + public final Setting windowMaximized = flag("windowMaximized", false); /** Whether the ban list shows the bans we created ourselves in bold. */ - public boolean banHighlightOwn = true; + public final Setting banHighlightOwn = flag("banHighlightOwn", true); /** The ban list columns the user shows, comma-separated column names; empty for the default set. */ - public String banListColumns = ""; + public final Setting banListColumns = text("banListColumns", ""); /** What the Server Log window shows and how. */ 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. */ public final ContactDefaults contactDefaults = new ContactDefaults(); /** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */ - public boolean colorContacts = true; + public final Setting colorContacts = flag("colorContacts", true); /** Whose whispers are played. */ - public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED; + public final Setting whisperPolicy = choice("whisperPolicy", WhisperPolicy.ALLOW_UNLESS_DENIED); /** Keep chat logs, and show their history when a chat opens. */ - public boolean chatLogs = true; + public final Setting chatLogs = flag("chatLogs", true); /** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */ - public String chatLogDir = ""; + public final Setting chatLogDir = text("chatLogDir", ""); /** The folder recordings were last saved to; empty for {@code ~/Recordings}. */ - public String recordingDir = ""; + public final Setting recordingDir = text("recordingDir", ""); /** Whether descriptions show their pictures, fetched from the web, or only links to them. */ - public boolean descriptionPictures = true; + public final Setting descriptionPictures = flag("descriptionPictures", true); /** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100 %. */ - public double chatZoom = 1.0; + public final Setting chatZoom = decimal("chatZoom", 1.0); /** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100 %. */ - public double infoZoom = 1.0; + public final Setting infoZoom = decimal("infoZoom", 1.0); public static Settings load() { Settings s = new Settings(); @@ -242,7 +250,12 @@ public final class Settings { try (FileInputStream in = new FileInputStream(file())) { 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) { // Corrupt/unreadable settings -> fall back to defaults. @@ -253,210 +266,81 @@ public final class Settings { public void save() { try { 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")); } catch (Exception ignored) { } } public File identityFile() { - return new File(identityFile); + return new File(identityFile.get()); } public Path recordingFolder() { - return recordingDir.isBlank() + return recordingDir.get().isBlank() ? Paths.get(System.getProperty("user.home", "."), "Recordings") - : Paths.get(recordingDir); + : Paths.get(recordingDir.get()); } /** {@link #outputVolume} scaled by the Master Volume slider. */ public double effectiveOutputVolume() { - return outputVolume * masterVolume; + return outputVolume.get() * masterVolume.get(); } /** {@link #soundVolume} scaled by the Master Volume slider. */ public double effectiveSoundVolume() { - return soundVolume * masterVolume; + return soundVolume.get() * masterVolume.get(); } - private void applyFromProps() { - lastAddress = props.getProperty("lastAddress", lastAddress); - nickname = props.getProperty("nickname", nickname); - serverPassword = props.getProperty("serverPassword", serverPassword); - identityFile = props.getProperty("identityFile", identityFile); - 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 Setting add(String key, T initial, Function parse, Function format, + UnaryOperator constrain) { + Setting setting = new Setting<>(key, initial, parse, format, constrain); + all.add(setting); + return setting; } - private void writeToProps() { - props.setProperty("lastAddress", lastAddress); - 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 Setting text(String key, String initial) { + return add(key, initial, Function.identity(), Function.identity(), UnaryOperator.identity()); } - private static > E parseEnum(Class type, String v, E def) { - if (v == null) return def; - try { - return Enum.valueOf(type, v.trim()); - } catch (IllegalArgumentException e) { - return def; - } + private Setting flag(String key, boolean initial) { + return add(key, initial, Boolean::parseBoolean, String::valueOf, UnaryOperator.identity()); + } + + private Setting number(String key, int initial) { + return add(key, initial, Integer::parseInt, String::valueOf, UnaryOperator.identity()); + } + + private Setting 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 decimal(String key, double initial) { + return add(key, initial, Double::parseDouble, String::valueOf, UnaryOperator.identity()); + } + + private > Setting 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 - * dBFS ({@code 20*log10(rms)}), to {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, so - * upgrading doesn't silently change how sensitive the gate is. + * dBFS ({@code 20*log10(rms)}), to {@link InputLevel}'s scale, so upgrading doesn't silently + * change how sensitive the gate is. */ - private static double migrateThreshold(String legacy, double def) { - double dbfs = parseD(legacy, Double.NaN); - if (Double.isNaN(dbfs)) { - 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; + private void migrateThreshold() { + String legacy = (String) props.remove("vadThresholdDb"); + if (legacy == null || props.containsKey(vadThresholdDb.key())) return; try { - return Double.parseDouble(v); - } catch (NumberFormatException e) { - return def; + double converted = InputLevel.powerToDb(Math.pow(10.0, Double.parseDouble(legacy) / 10.0)); + props.setProperty(vadThresholdDb.key(), Double.toString(Math.min(InputLevel.MAX_DB, converted))); + } 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); - } } diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChatLog.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChatLog.java index 6105881..20f71a4 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChatLog.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ChatLog.java @@ -30,13 +30,13 @@ final class ChatLog { */ void open(String serverUniqueId) { store = null; - if (!settings.chatLogs) return; + if (!settings.chatLogs.get()) return; try { if (serverUniqueId == null) { ui.onStatus("Chat logs unavailable: the server's unique id is not known"); 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: // ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId); ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), serverUniqueId); diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientContacts.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientContacts.java index dc73d58..12cb0ad 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientContacts.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/ClientContacts.java @@ -46,7 +46,7 @@ public final class ClientContacts { * client's contact entry. A client that has already left is judged by the policy alone. */ boolean isWhisperAllowed(int clientId) { - Settings.WhisperPolicy policy = settings.whisperPolicy; + Settings.WhisperPolicy policy = settings.whisperPolicy.get(); if (policy == Settings.WhisperPolicy.NOBODY) return false; ClientEntry c = model.getClient(clientId); Contact contact = c == null ? null : store.find(c.uniqueId); diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OwnClient.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OwnClient.java index a1bd681..24020fa 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OwnClient.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/OwnClient.java @@ -130,7 +130,7 @@ public final class OwnClient { VoiceOutput out = audio.createOutput(settings); out.setMasterVolume(settings.effectiveOutputVolume()); - out.setReceiveBuffer(settings.receiveBuffer); + out.setReceiveBuffer(settings.receiveBuffer.get()); out.setTalkListener((clientId, talking) -> { ClientEntry c = model.getClient(clientId); 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. */ private void onTalkingWhileMuted() { - if (!settings.mutedTalkWarning) return; + if (!settings.mutedTalkWarning.get()) return; long now = System.nanoTime(); if (now - lastMutedTalkNanos < MUTED_TALK_COOLDOWN_NANOS) return; lastMutedTalkNanos = now; diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java index bc0c446..1d00da8 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/net/TeamspeakConnection.java @@ -359,7 +359,7 @@ public final class TeamspeakConnection implements TS3Listener { * hand, and the bare message does not point anywhere. */ private String versionHint(Exception e) { - if (!settings.customVersion) return ""; + if (!settings.customVersion.get()) return ""; String message = RequestException.rootMessage(e); return message != null && message.contains("client is modified") ? " — 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. */ private void applyClientVersion(LocalTeamspeakClientSocket client) { - if (!settings.customVersion) return; - setIfPresent(client, "client.version_string", settings.clientVersion); - setIfPresent(client, "client.version_platform", settings.clientPlatform); - setIfPresent(client, "client.version_sign", settings.clientVersionSign); + if (!settings.customVersion.get()) return; + setIfPresent(client, "client.version_string", settings.clientVersion.get()); + setIfPresent(client, "client.version_platform", settings.clientPlatform.get()); + setIfPresent(client, "client.version_sign", settings.clientVersionSign.get()); } 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) { ClientEntry self = own.entry(); 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 ---- diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java index 59257c9..3bba641 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/session/ServerSession.java @@ -301,7 +301,7 @@ public final class ServerSession { private String nicknameFor(String serverNickname, IdentityEntry identity) { if (serverNickname != null && !serverNickname.isBlank()) return serverNickname.trim(); if (!identity.getNickname().isBlank()) return identity.getNickname(); - return settings.nickname; + return settings.nickname.get(); } /** diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java index 70a077a..1656c94 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/sound/SoundNotifier.java @@ -49,8 +49,8 @@ public final class SoundNotifier { /** Re-scans the installed packs and selects the configured one. */ public void reload() { - available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir); - pack = SoundPacks.select(available, settings.soundPack); + available = SoundPacks.findAll(new File(AppDirs.profile(), "sound"), settings.soundPackDir.get()); + pack = SoundPacks.select(available, settings.soundPack.get()); } public List availablePacks() { @@ -64,7 +64,7 @@ public final class SoundNotifier { /** Switches packs and remembers the choice in the settings. */ public void setPack(SoundPack pack) { this.pack = pack; - settings.soundPack = pack == null ? "" : pack.id(); + settings.soundPack.set(pack == null ? "" : pack.id()); } /** diff --git a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java index 5953abb..f87d6bb 100644 --- a/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java +++ b/ts3-client/core/src/main/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporter.java @@ -177,9 +177,9 @@ public final class TeamSpeakImporter { imported.put(identity.uuid(), entry); if (!identity.isDefault()) continue; // No default of our own yet: TeamSpeak's default identity and nickname become ours. - if (identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = entry.getId(); - if (!identity.nickname().isBlank()) settings.nickname = identity.nickname(); + if (identities.byId(settings.defaultIdentityId.get()) == null) { + settings.defaultIdentityId.set(entry.getId()); + if (!identity.nickname().isBlank()) settings.nickname.set(identity.nickname()); settingsChanged = true; } } diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java index 525b9e4..96922e6 100644 --- a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/config/SettingsTest.java @@ -8,6 +8,8 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.file.Files; 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.assertFalse; @@ -30,33 +32,33 @@ class SettingsTest { @Test void whatIsSavedLoadsBack() { Settings saved = new Settings(); - saved.nickname = "Žofia"; - saved.inputMode = Settings.InputMode.PUSH_TO_TALK; - saved.vadMode = Settings.VadMode.AUTOMATIC; - saved.vadThresholdDb = -33.5; - saved.appearance = Settings.Appearance.DARK; - saved.whisperPolicy = Settings.WhisperPolicy.NOBODY; - saved.chatLogs = false; - saved.chatLogDir = "/somewhere/else"; + saved.nickname.set("Žofia"); + saved.inputMode.set(Settings.InputMode.PUSH_TO_TALK); + saved.vadMode.set(Settings.VadMode.AUTOMATIC); + saved.vadThresholdDb.set(-33.5); + saved.appearance.set(Settings.Appearance.DARK); + saved.whisperPolicy.set(Settings.WhisperPolicy.NOBODY); + saved.chatLogs.set(false); + saved.chatLogDir.set("/somewhere/else"); saved.save(); Settings loaded = Settings.load(); - assertEquals("Žofia", loaded.nickname); - assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode); - assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode); - assertEquals(-33.5, loaded.vadThresholdDb); - assertEquals(Settings.Appearance.DARK, loaded.appearance); - assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy); - assertFalse(loaded.chatLogs); - assertEquals("/somewhere/else", loaded.chatLogDir); + assertEquals("Žofia", loaded.nickname.get()); + assertEquals(Settings.InputMode.PUSH_TO_TALK, loaded.inputMode.get()); + assertEquals(Settings.VadMode.AUTOMATIC, loaded.vadMode.get()); + assertEquals(-33.5, loaded.vadThresholdDb.get()); + assertEquals(Settings.Appearance.DARK, loaded.appearance.get()); + assertEquals(Settings.WhisperPolicy.NOBODY, loaded.whisperPolicy.get()); + assertFalse(loaded.chatLogs.get()); + assertEquals("/somewhere/else", loaded.chatLogDir.get()); } @Test void unknownValuesFallBackToDefaults() throws Exception { Files.writeString(dir.resolve("settings.properties"), "inputMode=TELEPATHY\nvadMode=\n"); Settings loaded = Settings.load(); - assertEquals(new Settings().inputMode, loaded.inputMode); - assertEquals(new Settings().vadMode, loaded.vadMode); + assertEquals(new Settings().inputMode.get(), loaded.inputMode.get()); + assertEquals(new Settings().vadMode.get(), loaded.vadMode.get()); } @Test @@ -64,11 +66,31 @@ class SettingsTest { Files.writeString(dir.resolve("settings.properties"), "vadThresholdDb=-40.0\n"); Settings loaded = Settings.load(); 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(); String saved = Files.readString(dir.resolve("settings.properties")); 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 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()); } } diff --git a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java index c6df78f..d23319b 100644 --- a/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java +++ b/ts3-client/core/src/test/java/eu/lixko/ts3j/client/teamspeak/TeamSpeakImporterTest.java @@ -38,7 +38,7 @@ class TeamSpeakImporterTest { @Test void importsBookmarksWithTheIdentitiesTheyUse() throws Exception { Settings settings = new Settings(); - settings.nickname = "Fallback"; + settings.nickname.set("Fallback"); IdentityStore identities = IdentityStore.load(settings); Bookmarks bookmarks = new Bookmarks(); bookmarks.add(new Bookmark("TeamSpeak Public", "VOICE.teamspeak.com", 9987, "me", "")); @@ -51,7 +51,7 @@ class TeamSpeakImporterTest { IdentityEntry imported = identities.all().get(0); assertEquals("Default", imported.getName()); - assertEquals(imported.getId(), settings.defaultIdentityId); + assertEquals(imported.getId(), settings.defaultIdentityId.get()); assertTrue(imported.getFile().isFile()); List all = bookmarks.all(); @@ -70,7 +70,7 @@ class TeamSpeakImporterTest { assertEquals("", byId.nickname, "takes the identity's nickname as it connects"); assertEquals("SyncTester", imported.getNickname()); assertEquals("", byId.identityId, "connects with whatever the default identity is"); - assertEquals("SyncTester", settings.nickname); + assertEquals("SyncTester", settings.nickname.get()); // Running it again changes nothing. result = importer.importBookmarks(SyncItemsTest.fixture()); @@ -129,7 +129,7 @@ class TeamSpeakImporterTest { assertEquals(1, first.identities()); assertEquals(1, second.identitiesKnown()); assertEquals(before + first.identitiesAdded(), identities.all().size()); - assertNotNull(identities.byId(settings.defaultIdentityId)); + assertNotNull(identities.byId(settings.defaultIdentityId.get())); } @Test diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java index ec2faa5..4d33822 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/Main.java @@ -32,11 +32,11 @@ public final class Main { if (link != null && InstanceChannel.send(link)) return; final Settings settings = Settings.load(); - DisplayScale.configure(settings.uiScale); + DisplayScale.configure(settings.uiScale.get()); WindowClass.apply(); SwingUtilities.invokeLater(() -> { - LookAndFeelManager.install(settings.appearance); + LookAndFeelManager.install(settings.appearance.get()); IconTheme.get().reload(settings); DesktopEntry.install(); MainFrame frame = new MainFrame(settings); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java index 2b39a93..c805a09 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ApplicationPanel.java @@ -16,7 +16,7 @@ final class ApplicationPanel extends FormPanel { this.settings = settings; 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); int row = 0; @@ -29,7 +29,7 @@ final class ApplicationPanel extends FormPanel { /** Copies the page into the settings; the caller saves them. */ void apply() { - settings.mutedTalkWarning = mutedWarning.isSelected(); + settings.mutedTalkWarning.set(mutedWarning.isSelected()); clientVersion.apply(); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java index 7b295e2..aacbc22 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/BanListDialog.java @@ -195,9 +195,9 @@ final class BanListDialog extends AbstractServerListDialog { onlyOwn.addActionListener(e -> applyFilter()); highlightOwn.setToolTipText("Mark bans created by you as bold"); highlightOwn.setOpaque(false); - highlightOwn.setSelected(settings.banHighlightOwn); + highlightOwn.setSelected(settings.banHighlightOwn.get()); highlightOwn.addActionListener(e -> { - settings.banHighlightOwn = highlightOwn.isSelected(); + settings.banHighlightOwn.set(highlightOwn.isSelected()); settings.save(); table.repaint(); }); @@ -241,7 +241,7 @@ final class BanListDialog extends AbstractServerListDialog { private Set savedColumns() { Set columns = EnumSet.noneOf(Column.class); - for (String name : settings.banListColumns.split(",")) { + for (String name : settings.banListColumns.get().split(",")) { try { if (!name.isBlank()) columns.add(Column.valueOf(name.trim())); } catch (IllegalArgumentException ignored) { @@ -255,7 +255,7 @@ final class BanListDialog extends AbstractServerListDialog { } 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(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java index 1cf9046..c629c75 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/CapturePanel.java @@ -38,11 +38,11 @@ final class CapturePanel extends FormPanel { this.activation = new VoiceActivationSection(settings, audio, liveMic, hotkeys, hotkeysPanel, audioSnapshot); GridBagConstraints c = gbc(); - inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice); + inputCombo = AudioDevices.combo(audio.io().inputDevices(), settings.inputDevice.get()); limitWidth(inputCombo, FIELD_WIDTH); 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() + "%"); inputGain.addChangeListener(e -> { gainLabel.setText(inputGain.getValue() + "%"); @@ -51,14 +51,14 @@ final class CapturePanel extends FormPanel { // Off, then TS3's four denoiser_level steps. 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.setPaintTicks(true); denoise.setSnapToTicks(true); JLabel denoiseLabel = new JLabel(DENOISE_STEPS[denoise.getValue()]); - typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation); - agcCheck = new JCheckBox("Automatic gain control", settings.agc); - agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb); + typingCheck = new JCheckBox("Typing attenuation", settings.typingAttenuation.get()); + agcCheck = new JCheckBox("Automatic gain control", settings.agc.get()); + agcBoost = new JSlider(0, Settings.MAX_AGC_BOOST_DB, settings.agcBoostDb.get()); agcBoost.setMajorTickSpacing(5); agcBoost.setPaintTicks(true); limitWidth(agcBoost, SLIDER_WIDTH); @@ -98,13 +98,13 @@ final class CapturePanel extends FormPanel { /** Copies the page into {@code target}, without touching anything else. */ void writeInto(Settings target) { - target.inputDevice = AudioDevices.selectedId(inputCombo); - target.inputVolume = inputGain.getValue() / 100.0; - target.denoise = denoise.getValue() > 0; - if (target.denoise) target.denoiserLevel = denoise.getValue() - 1; - target.typingAttenuation = typingCheck.isSelected(); - target.agc = agcCheck.isSelected(); - target.agcBoostDb = agcBoost.getValue(); + target.inputDevice.set(AudioDevices.selectedId(inputCombo)); + target.inputVolume.set(inputGain.getValue() / 100.0); + target.denoise.set(denoise.getValue() > 0); + if (target.denoise.get()) target.denoiserLevel.set(denoise.getValue() - 1); + target.typingAttenuation.set(typingCheck.isSelected()); + target.agc.set(agcCheck.isSelected()); + target.agcBoostDb.set(agcBoost.getValue()); activation.writeInto(target); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java index 125f29a..fb605d7 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ChatLogsPanel.java @@ -30,11 +30,11 @@ final class ChatLogsPanel extends FormPanel { this.settings = settings; 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.addActionListener(e -> updateEnabled()); - folder.setText(settings.chatLogDir); + folder.setText(settings.chatLogDir.get()); folder.putClientProperty("JTextField.placeholderText", "The TeamSpeak 3 client's folder"); folder.setToolTipText("Leave empty to share the TeamSpeak 3 client's logs:
" + AppDirs.chatLogs() + ""); @@ -47,7 +47,7 @@ final class ChatLogsPanel extends FormPanel { JLabel nextConnect = new JLabel("Takes effect on the next connect."); nextConnect.setEnabled(false); - pictures.setSelected(settings.descriptionPictures); + pictures.setSelected(settings.descriptionPictures.get()); pictures.setToolTipText("Off: only links to them, nothing fetched"); int row = 0; @@ -81,8 +81,8 @@ final class ChatLogsPanel extends FormPanel { /** Copies the page into the settings; the caller saves them. */ void apply() { - settings.chatLogs = enabled.isSelected(); - settings.chatLogDir = folder.getText().trim(); - settings.descriptionPictures = pictures.isSelected(); + settings.chatLogs.set(enabled.isSelected()); + settings.chatLogDir.set(folder.getText().trim()); + settings.descriptionPictures.set(pictures.isSelected()); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java index d84f74f..a5a1f37 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ClientVersionPanel.java @@ -57,10 +57,10 @@ final class ClientVersionPanel extends JPanel { /** Copies the edited version into the settings; the caller saves them. */ void apply() { - settings.customVersion = enabled.isSelected(); - settings.clientVersion = versionField.getText().trim(); - settings.clientPlatform = String.valueOf(platformCombo.getEditor().getItem()).trim(); - settings.clientVersionSign = signField.getText().trim(); + settings.customVersion.set(enabled.isSelected()); + settings.clientVersion.set(versionField.getText().trim()); + settings.clientPlatform.set(String.valueOf(platformCombo.getEditor().getItem()).trim()); + settings.clientVersionSign.set(signField.getText().trim()); } private JComponent buildForm() { @@ -117,11 +117,12 @@ final class ClientVersionPanel extends JPanel { } private void load() { - enabled.setSelected(settings.customVersion); + enabled.setSelected(settings.customVersion.get()); ClientVersion preset = ClientVersion.match( - settings.clientVersion, settings.clientPlatform, settings.clientVersionSign); + settings.clientVersion.get(), settings.clientPlatform.get(), settings.clientVersionSign.get()); 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); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java index a25a93a..599cbc1 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ConnectDialog.java @@ -34,7 +34,7 @@ public final class ConnectDialog extends JDialog { public ConnectDialog(Frame owner, Settings settings, IdentityStore identities) { super(owner, "Connect to Server", true); - String addr = settings.lastAddress; + String addr = settings.lastAddress.get(); int port = 9987; int colon = addr.lastIndexOf(':'); if (colon > 0) { @@ -47,9 +47,9 @@ public final class ConnectDialog extends JDialog { addressField = new JTextField(addr, 18); portField = new JTextField(Integer.toString(port), 6); - nickField = new JTextField(settings.nickname, 18); - passwordField = new JPasswordField(settings.serverPassword, 18); - identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId); + nickField = new JTextField(settings.nickname.get(), 18); + passwordField = new JPasswordField(settings.serverPassword.get(), 18); + identityChooser = new IdentityChooser(identities, false, settings.defaultIdentityId.get()); JPanel form = new JPanel(new GridBagLayout()); form.setBorder(new ScaledEmptyBorder(12, 12, 8, 12)); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java index ea88ca6..e1f10c3 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ContactsPanel.java @@ -30,10 +30,10 @@ final class ContactsPanel extends FormPanel { this.settings = settings; 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"); - whisperPolicy.setSelectedItem(settings.whisperPolicy); + whisperPolicy.setSelectedItem(settings.whisperPolicy.get()); whisperPolicy.setRenderer(new DefaultListCellRenderer() { @Override 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. */ void apply() { - settings.colorContacts = colorContacts.isSelected(); - settings.whisperPolicy = (Settings.WhisperPolicy) whisperPolicy.getSelectedItem(); + settings.colorContacts.set(colorContacts.isSelected()); + settings.whisperPolicy.set((Settings.WhisperPolicy) whisperPolicy.getSelectedItem()); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java index bea7f26..d126113 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DescriptionPictures.java @@ -92,7 +92,7 @@ final class DescriptionPictures { * and asks for those not on their way yet. */ String state(List urls) { - if (!settings.descriptionPictures) return ""; + if (!settings.descriptionPictures.get()) return ""; StringBuilder state = new StringBuilder(urls.size()); for (String url : urls) { 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) { - if (!settings.descriptionPictures) return link("ICONVIEWER", url, anchor, href); + if (!settings.descriptionPictures.get()) return link("ICONVIEWER", url, anchor, href); File file = downloads.get(url); if (file == null) { return downloads.failed(url) ? link("BROKEN_IMAGE", url, anchor, href) : icon("LOADING_IMAGE"); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java index 677d80a..4e9c9de 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesignPanel.java @@ -70,10 +70,10 @@ final class DesignPanel extends JPanel { DesignPanel(Settings settings) { super(new BorderLayout(0, UIScale.scale(8))); this.settings = settings; - this.originalPackId = settings.iconPack; - this.originalPackDir = settings.iconPackDir; - this.originalAppearance = settings.appearance; - this.packDirField = new JTextField(settings.iconPackDir, 18); + this.originalPackId = settings.iconPack.get(); + this.originalPackDir = settings.iconPackDir.get(); + this.originalAppearance = settings.appearance.get(); + this.packDirField = new JTextField(settings.iconPackDir.get(), 18); this.anyColor = new RowColorCombo(settings.clientRowColors.any); this.talkingColor = new RowColorCombo(settings.clientRowColors.talking); 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. */ void apply() { - settings.appearance = selectedAppearance(); - if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale = scale; - settings.iconPackDir = packDirField.getText().trim(); + settings.appearance.set(selectedAppearance()); + if (scaleCombo.getSelectedItem() instanceof Double scale) settings.uiScale.set(scale); + settings.iconPackDir.set(packDirField.getText().trim()); Object selected = packCombo.getSelectedItem(); - settings.iconPack = selected instanceof IconPack pack ? pack.id() : ""; - settings.countryFlags = countryFlags.isSelected(); + settings.iconPack.set(selected instanceof IconPack pack ? pack.id() : ""); + settings.countryFlags.set(countryFlags.isSelected()); settings.clientRowColors.any = anyColor.value(); settings.clientRowColors.talking = talkingColor.value(); settings.clientRowColors.mutedAway = mutedAwayColor.value(); - originalPackId = settings.iconPack; - originalPackDir = settings.iconPackDir; - originalAppearance = settings.appearance; + originalPackId = settings.iconPack.get(); + originalPackDir = settings.iconPackDir.get(); + originalAppearance = settings.appearance.get(); } /** Puts back the appearance and pack last applied, for a cancelled edit. */ void revert() { - settings.iconPack = originalPackId; - settings.iconPackDir = originalPackDir; + settings.iconPack.set(originalPackId); + settings.iconPackDir.set(originalPackDir); IconTheme.get().reload(settings); - if (settings.appearance != originalAppearance) { - settings.appearance = originalAppearance; + if (settings.appearance.get() != originalAppearance) { + settings.appearance.set(originalAppearance); LookAndFeelManager.switchTo(originalAppearance); } } @@ -134,7 +134,7 @@ final class DesignPanel extends JPanel { }); appearanceCombo.setToolTipText("Light or dark window colours"); - appearanceCombo.setSelectedItem(settings.appearance); + appearanceCombo.setSelectedItem(settings.appearance.get()); appearanceCombo.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, @@ -153,7 +153,7 @@ final class DesignPanel extends JPanel { dirRow.add(browse, BorderLayout.EAST); packDirField.setToolTipText("Extra folder to look for icon packs in"); packInfo.setEnabled(false); - countryFlags.setSelected(settings.countryFlags); + countryFlags.setSelected(settings.countryFlags.get()); int row = 0; FormPanel.addSection(p, c, row++, "Appearance"); @@ -178,10 +178,10 @@ final class DesignPanel extends JPanel { private void buildScaleCombo() { for (double scale : SCALES) scaleCombo.addItem(scale); - if (settings.uiScale > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale)) { - scaleCombo.addItem(settings.uiScale); + if (settings.uiScale.get() > 0 && Arrays.stream(SCALES).noneMatch(s -> s == settings.uiScale.get())) { + 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.setRenderer(new DefaultListCellRenderer() { @Override @@ -248,8 +248,8 @@ final class DesignPanel extends JPanel { private void onAppearanceSelected() { Settings.Appearance chosen = selectedAppearance(); - if (chosen == settings.appearance) return; - settings.appearance = chosen; + if (chosen == settings.appearance.get()) return; + settings.appearance.set(chosen); LookAndFeelManager.switchTo(chosen); } @@ -276,7 +276,7 @@ final class DesignPanel extends JPanel { if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); - settings.iconPackDir = packDirField.getText(); + settings.iconPackDir.set(packDirField.getText()); reloadPacks(); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java index e6fd52c..856eaac 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DesktopNotifier.java @@ -118,7 +118,7 @@ final class DesktopNotifier { private boolean wanted() { // 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; } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java index c6d8e4d..aa14474 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/DropIndicatorTree.java @@ -338,7 +338,7 @@ final class DropIndicatorTree extends JTree { model.serverGroupsOf(cl.serverGroupIds), model.channelGroup(cl.channelGroupId))); addIcon(icons, cl.talkRequest ? "TALK_POWER_REQUEST" : null); // 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); return icons; } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java index 1418cdb..b76bd0b 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IconTheme.java @@ -75,8 +75,8 @@ public final class IconTheme { /** Re-scans the pack folders and activates the one the settings name. */ public void reload(Settings settings) { - packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir); - IconPack pack = IconPacks.select(packs, settings.iconPack); + packs = IconPacks.findAll(new File(AppDirs.profile(), "gfx"), settings.iconPackDir.get()); + 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. lookupOrder = IconPacks.lookupOrder(pack, packs, null); setPack(pack); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java index 7dd7e32..1284a6a 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/IdentitiesDialog.java @@ -173,7 +173,7 @@ public final class IdentitiesDialog extends JDialog { } 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() { @@ -233,8 +233,8 @@ public final class IdentitiesDialog extends JDialog { runWithProgress("Generating identity…", (cancelled, status) -> { IdentityEntry created = identities.generate(name.trim(), level); - if (settings.defaultIdentityId == null || identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = created.getId(); + if (settings.defaultIdentityId.get() == null || identities.byId(settings.defaultIdentityId.get()) == null) { + settings.defaultIdentityId.set(created.getId()); settings.save(); } return created; @@ -249,8 +249,8 @@ public final class IdentitiesDialog extends JDialog { File file = chooser.getSelectedFile(); try { IdentityEntry imported = identities.importFile(file, null); - if (identities.byId(settings.defaultIdentityId) == null) { - settings.defaultIdentityId = imported.getId(); + if (identities.byId(settings.defaultIdentityId.get()) == null) { + settings.defaultIdentityId.set(imported.getId()); settings.save(); } reload(); @@ -315,7 +315,7 @@ public final class IdentitiesDialog extends JDialog { private void setSelectedDefault() { IdentityEntry e = list.getSelectedValue(); if (e == null) return; - settings.defaultIdentityId = e.getId(); + settings.defaultIdentityId.set(e.getId()); settings.save(); reload(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java index 97b6249..066f11c 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainCommands.java @@ -260,16 +260,16 @@ final class MainCommands { /** Asks for a new nickname, used on every server. */ 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); } /** Uses this nickname on every server; a blank one is ignored. */ void changeNickname(String nickname) { if (nickname == null || nickname.isBlank()) return; - settings.nickname = nickname.trim(); + settings.nickname.set(nickname.trim()); settings.save(); - sessions.setNickname(settings.nickname); + sessions.setNickname(settings.nickname.get()); } void joinChannel(List targets, String path) { @@ -378,15 +378,6 @@ final class MainCommands { // ---- 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 ---- void showGiantPtt() { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java index d125b38..102ce48 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainFrame.java @@ -10,6 +10,7 @@ import eu.lixko.ts3j.client.config.Bookmark; import eu.lixko.ts3j.client.config.Bookmarks; import eu.lixko.ts3j.client.session.ServerLink; 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.myts.ChatAttachments; import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin; @@ -102,12 +103,12 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { public MainFrame(Settings settings) { super("TeamSpook TS3j"); this.settings = settings; - this.chatZoom = new TextZoom(settings.chatZoom, z -> { - settings.chatZoom = z; + this.chatZoom = new TextZoom(settings.chatZoom.get(), z -> { + settings.chatZoom.set(z); settings.save(); }); - this.infoZoom = new TextZoom(settings.infoZoom, z -> { - settings.infoZoom = z; + this.infoZoom = new TextZoom(settings.infoZoom.get(), z -> { + settings.infoZoom.set(z); settings.save(); }); this.identities = IdentityStore.load(settings); @@ -117,6 +118,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { this.soundPlayer = audio.createSoundPlayer(settings); this.sounds.setPlayer(soundPlayer); this.notifier = new DesktopNotifier(this, settings); + Setting.onAnyChange(this::applyOutputSettingsToAllTabs, + settings.outputDevice, settings.outputVolume, settings.masterVolume, settings.receiveBuffer); pictures.addSource("tsattach:", attachments::fetchPicture); // Any of the client's windows coming to the front counts, a dialog included. 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, () -> { if (selected != null) selected.session().cancelReconnect(); }); - statusBar.setVisible(settings.showStatusBar); + statusBar.setVisible(settings.showStatusBar.get()); + settings.showStatusBar.addListener(this::showStatusBar); add(statusBar, BorderLayout.SOUTH); statusBar.setCodec(audio.description()); @@ -311,7 +315,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { menuBar.rebuildBookmarks(); } - void showStatusBar(boolean visible) { + private void showStatusBar(boolean visible) { statusBar.setVisible(visible); revalidate(); repaint(); @@ -413,9 +417,8 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { } 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(); - applyOutputSettingsToAllTabs(); 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, String channel, String channelPassword, boolean replaceCurrent, boolean mytsFeatures) { - settings.lastAddress = address + ":" + port; - if (!nickname.isBlank()) settings.nickname = nickname; - settings.serverPassword = password; + settings.lastAddress.set(address + ":" + port); + if (!nickname.isBlank()) settings.nickname.set(nickname); + settings.serverPassword.set(password); settings.save(); ServerTab tab = (replaceCurrent && selected != null) ? selected : tabForNewConnection(); @@ -626,10 +629,7 @@ public final class MainFrame extends JFrame implements ServerTabPane.Listener { sounds, hotkeys, new MyTeamSpeakPanel(myTeamSpeak, new TeamSpeakImporter(identities, bookmarks, settings, contacts), this::bookmarksChanged, this::myTeamSpeakChanged), - () -> { - applyOutputSettingsToAllTabs(); - contactsChanged(); - }); + this::contactsChanged); 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. */ - void applyOutputSettingsToAllTabs() { - soundPlayer.setOutputDevice(settings.outputDevice); + private void applyOutputSettingsToAllTabs() { + soundPlayer.setOutputDevice(settings.outputDevice.get()); for (ServerTab tab : tabs) { VoiceOutput playback = tab.session().playback(); if (playback == null) continue; playback.setMasterVolume(settings.effectiveOutputVolume()); - playback.setOutputDevice(settings.outputDevice); - playback.setReceiveBuffer(settings.receiveBuffer); + playback.setOutputDevice(settings.outputDevice.get()); + playback.setReceiveBuffer(settings.receiveBuffer.get()); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java index 2fc639b..3b03e8e 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MainToolbar.java @@ -16,8 +16,6 @@ import javax.swing.JPopupMenu; import javax.swing.JSlider; import javax.swing.JToggleButton; import javax.swing.JToolBar; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; @@ -96,7 +94,7 @@ final class MainToolbar extends JToolBar { add(settingsButton); add(Box.createHorizontalGlue()); masterVolumePanel = buildMasterVolumeControl(); - masterVolumePanel.setVisible(settings.showMasterVolumeSlider); + masterVolumePanel.setVisible(settings.showMasterVolumeSlider.get()); add(masterVolumePanel); hostButton = new HostButtonView(pictures); add(hostButton); @@ -136,14 +134,13 @@ final class MainToolbar extends JToolBar { icon.setToolTipText("Master volume (voice + notifications)"); 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.setToolTipText("Master volume (voice + notifications) — scroll to adjust"); slider.setAlignmentY(Component.CENTER_ALIGNMENT); slider.setPreferredSize(new Dimension(UIScale.scale(135), slider.getPreferredSize().height)); slider.addChangeListener(e -> { - settings.masterVolume = slider.getValue() / 100.0; - commands.applyOutputSettings(); + settings.masterVolume.set(slider.getValue() / 100.0); // Only touch the disk once the drag (or a wheel step) has settled. if (!slider.getValueIsAdjusting()) settings.save(); }); @@ -162,41 +159,27 @@ final class MainToolbar extends JToolBar { private JPopupMenu buildContextMenu() { 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 -> { - settings.showStatusBar = statusBarItem.isSelected(); + settings.showStatusBar.set(statusBarItem.isSelected()); 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 -> { - settings.showMasterVolumeSlider = volumeItem.isSelected(); + settings.showMasterVolumeSlider.set(volumeItem.isSelected()); settings.save(); - masterVolumePanel.setVisible(settings.showMasterVolumeSlider); + }); + settings.showMasterVolumeSlider.addListener(shown -> { + volumeItem.setSelected(shown); + masterVolumePanel.setVisible(shown); revalidate(); repaint(); }); menu.add(statusBarItem); 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; } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java index 4eab36c..2560857 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/MicrophoneTest.java @@ -60,7 +60,7 @@ final class MicrophoneTest { input.setLevelListener(db -> SwingUtilities.invokeLater(() -> onLevel.accept(db))); input.setTalkListener(talking -> SwingUtilities.invokeLater(() -> onTransmitting.accept(talking))); input.setMonitorListener(this::enqueueForLoopback); - this.outputDevice = settings.outputDevice; + this.outputDevice = settings.outputDevice.get(); try { input.start(); } catch (RuntimeException e) { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java index 27c5c43..174e8a6 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NetworkPanel.java @@ -34,7 +34,7 @@ final class NetworkPanel extends FormPanel { this.liveMic = liveMic; 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); JLabel bitrateLabel = new JLabel(kbits + " kbit/s"); bitrateSlider.addChangeListener(e -> { @@ -42,28 +42,28 @@ final class NetworkPanel extends FormPanel { pushEncoder.run(); }); - vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr); - fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec); + vbrCheck = new JCheckBox("Variable bitrate (VBR)", settings.vbr.get()); + fecCheck = new JCheckBox("Forward error correction (FEC)", settings.fec.get()); vbrCheck.addActionListener(e -> pushEncoder.run()); fecCheck.addActionListener(e -> pushEncoder.run()); - complexitySlider = new JSlider(0, 10, settings.complexity); - JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity)); + complexitySlider = new JSlider(0, 10, settings.complexity.get()); + JLabel complexityLabel = new JLabel(String.valueOf(settings.complexity.get())); complexitySlider.addChangeListener(e -> { complexityLabel.setText(String.valueOf(complexitySlider.getValue())); 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("Transmits OPUS_MUSIC: stereo when the capture " + "device has two channels, and without the voice pre-processing " + "(noise removal, typing attenuation, AGC).
" + "Voice mode (OPUS_VOICE) is mono, as in the official client."); 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())); - 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.setMajorTickSpacing(1); copiesSlider.setPaintTicks(true); @@ -84,7 +84,7 @@ final class NetworkPanel extends FormPanel { pushRedundancy(); }); - receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer); + receiveBufferSlider = choiceSlider(Settings.RECEIVE_BUFFERS, settings.receiveBuffer.get()); JLabel receiveBufferLabel = new JLabel(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. */ void writeInto(Settings target) { - target.bitrate = bitrateSlider.getValue() * 1000; - target.vbr = vbrCheck.isSelected(); - target.fec = fecCheck.isSelected(); - target.complexity = complexitySlider.getValue(); - target.music = musicCheck.isSelected(); - target.redundancyDelay = selectedDelay(); - target.redundancyCopies = copiesSlider.getValue(); - target.receiveBuffer = selectedReceiveBuffer(); + target.bitrate.set(bitrateSlider.getValue() * 1000); + target.vbr.set(vbrCheck.isSelected()); + target.fec.set(fecCheck.isSelected()); + target.complexity.set(complexitySlider.getValue()); + target.music.set(musicCheck.isSelected()); + target.redundancyDelay.set(selectedDelay()); + target.redundancyCopies.set(copiesSlider.getValue()); + target.receiveBuffer.set(selectedReceiveBuffer()); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java index 4193b1d..210b1de 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/NotificationsPanel.java @@ -88,10 +88,10 @@ final class NotificationsPanel extends JPanel { this.settings = settings; this.sounds = sounds; this.working = settings.notifications.copy(); - this.originalPackId = settings.soundPack; - this.originalPackDir = settings.soundPackDir; - this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume * 100)); - this.packDirField = new JTextField(settings.soundPackDir, 18); + this.originalPackId = settings.soundPack.get(); + this.originalPackDir = settings.soundPackDir.get(); + this.volume = new JSlider(0, 100, (int) Math.round(settings.soundVolume.get() * 100)); + this.packDirField = new JTextField(settings.soundPackDir.get(), 18); buildRows(); this.table = buildTable(); @@ -107,21 +107,21 @@ final class NotificationsPanel extends JPanel { /** Copies the edited state into the settings; the caller saves them. */ void apply() { settings.notifications.copyFrom(working); - settings.soundVolume = volume.getValue() / 100.0; + settings.soundVolume.set(volume.getValue() / 100.0); String directory = packDirField.getText().trim(); - boolean rescan = !directory.equals(settings.soundPackDir); - settings.soundPackDir = directory; - settings.desktopNotifications = desktopNotifications.isSelected(); + boolean rescan = !directory.equals(settings.soundPackDir.get()); + settings.soundPackDir.set(directory); + settings.desktopNotifications.set(desktopNotifications.isSelected()); sounds.setPack((SoundPack) packCombo.getSelectedItem()); if (rescan) sounds.reload(); - originalPackId = settings.soundPack; - originalPackDir = settings.soundPackDir; + originalPackId = settings.soundPack.get(); + originalPackDir = settings.soundPackDir.get(); } /** Puts back the pack (and folder) last applied, for a cancelled edit. */ void revert() { - settings.soundPackDir = originalPackDir; - settings.soundPack = originalPackId; + settings.soundPackDir.set(originalPackDir); + settings.soundPack.set(originalPackId); sounds.reload(); } @@ -162,7 +162,7 @@ final class NotificationsPanel extends JPanel { packDirField.setToolTipText("Extra folder to look for sound packs in"); addRow(p, c, row++, new JLabel("Extra pack folder:"), dirRow); - desktopNotifications.setSelected(settings.desktopNotifications); + desktopNotifications.setSelected(settings.desktopNotifications.get()); c.gridx = 0; c.gridy = row; c.gridwidth = 2; @@ -283,7 +283,7 @@ final class NotificationsPanel extends JPanel { if (!current.isEmpty()) chooser.setCurrentDirectory(new File(current)); if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return; packDirField.setText(chooser.getSelectedFile().getAbsolutePath()); - settings.soundPackDir = packDirField.getText(); + settings.soundPackDir.set(packDirField.getText()); reloadPacks(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java index ac332b4..4f76a82 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/PlaybackPanel.java @@ -29,15 +29,17 @@ final class PlaybackPanel extends FormPanel { Consumer onOutputDeviceChanged) { GridBagConstraints c = gbc(); - outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice); + outputCombo = AudioDevices.combo(io.outputDevices(), settings.outputDevice.get()); limitWidth(outputCombo, FIELD_WIDTH); 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() + "%"); outputVol.addChangeListener(e -> { 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"); @@ -56,7 +58,7 @@ final class PlaybackPanel extends FormPanel { /** Copies the form into {@code target}, without touching anything else. */ void writeInto(Settings target) { - target.outputDevice = AudioDevices.selectedId(outputCombo); - target.outputVolume = outputVol.getValue() / 100.0; + target.outputDevice.set(AudioDevices.selectedId(outputCombo)); + target.outputVolume.set(outputVol.getValue() / 100.0); } } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java index e790326..6a39a44 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/RecordingActions.java @@ -35,7 +35,7 @@ final class RecordingActions { if (chooser.showSaveDialog(owner) != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); 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(); session.startRecording(mode(multitrack), file.toPath()); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java index f389a93..e08985a 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTab.java @@ -154,12 +154,11 @@ final class ServerTab { leftColumn = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treePanel, infoPanel); leftColumn.setContinuousLayout(true); normalDividerSize = leftColumn.getDividerSize(); - SplitRatio.keep(leftColumn, () -> settings.infoSplitRatio, r -> settings.infoSplitRatio = r, - infoPanel::isVisible); + SplitRatio.keep(leftColumn, settings.infoSplitRatio, infoPanel::isVisible); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftColumn, chatPanel); split.setContinuousLayout(true); - SplitRatio.keep(split, () -> settings.chatSplitRatio, r -> settings.chatSplitRatio = r, () -> true); + SplitRatio.keep(split, settings.chatSplitRatio, () -> true); this.component = split; } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java index adacabf..ec20fd0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTabConnectionEvents.java @@ -59,7 +59,7 @@ final class ServerTabConnectionEvents implements ServerSession.Listener { @Override 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(); SwingUtilities.invokeLater(() -> { switch (scope) { diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java index e2e676d..67751ed 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/ServerTreeCellRenderer.java @@ -84,7 +84,7 @@ final class ServerTreeCellRenderer extends DefaultTreeCellRenderer { /** Friends and blocked clients stand out by colour, as in TeamSpeak, unless turned off. */ 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) { case FRIEND: return Theme.friend(); diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java index 3eae68d..ff137b0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SettingsDialog.java @@ -37,7 +37,6 @@ public final class SettingsDialog extends JDialog { private static int lastPage; private final Settings settings; - private final VoiceOutput livePlayback; private final Runnable onApply; private final ApplicationPanel applicationPanel; @@ -56,7 +55,6 @@ public final class SettingsDialog extends JDialog { Runnable onApply) { super(owner, "Options", true); this.settings = settings; - this.livePlayback = livePlayback; this.onApply = onApply; applicationPanel = new ApplicationPanel(settings); @@ -184,10 +182,10 @@ public final class SettingsDialog extends JDialog { */ private Settings audioSnapshot() { Settings snapshot = new Settings(); - snapshot.packetLoss = settings.packetLoss; + snapshot.packetLoss.set(settings.packetLoss.get()); writeAudioSettings(snapshot); - if (snapshot.inputMode == Settings.InputMode.PUSH_TO_TALK) { - snapshot.inputMode = Settings.InputMode.VOICE_ACTIVATION; + if (snapshot.inputMode.get() == Settings.InputMode.PUSH_TO_TALK) { + snapshot.inputMode.set(Settings.InputMode.VOICE_ACTIVATION); } return snapshot; } @@ -203,10 +201,6 @@ public final class SettingsDialog extends JDialog { settings.save(); capturePanel.applyLive(m -> m.apply(settings)); - if (livePlayback != null) { - livePlayback.setMasterVolume(settings.outputVolume); - livePlayback.setOutputDevice(settings.outputDevice); - } if (onApply != null) onApply.run(); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SplitRatio.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SplitRatio.java index 3fd6b4c..f3f8bf0 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SplitRatio.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/SplitRatio.java @@ -1,11 +1,11 @@ package eu.lixko.ts3j.client.ui; +import eu.lixko.ts3j.client.config.Setting; + import javax.swing.JSplitPane; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; 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 @@ -15,8 +15,7 @@ import java.util.function.DoubleSupplier; final class SplitRatio { private final JSplitPane split; - private final DoubleSupplier saved; - private final DoubleConsumer save; + private final Setting saved; private final BooleanSupplier tracking; /** The span at the last divider move; another span means a layout moved it, not the user. */ 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 * (a side collapsed, say), moves are neither saved nor corrected */ - static void keep(JSplitPane split, DoubleSupplier saved, DoubleConsumer save, BooleanSupplier tracking) { - new SplitRatio(split, saved, save, tracking); + static void keep(JSplitPane split, Setting saved, BooleanSupplier tracking) { + new SplitRatio(split, saved, tracking); } - private SplitRatio(JSplitPane split, DoubleSupplier saved, DoubleConsumer save, BooleanSupplier tracking) { + private SplitRatio(JSplitPane split, Setting saved, BooleanSupplier tracking) { this.split = split; this.saved = saved; - this.save = save; this.tracking = tracking; - split.setResizeWeight(saved.getAsDouble()); + split.setResizeWeight(saved.get()); split.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { if (restored || span() <= 0) return; restored = true; lastSpan = span(); - split.setDividerLocation(saved.getAsDouble()); + split.setDividerLocation(saved.get()); } }); split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, e -> moved()); @@ -57,7 +55,7 @@ final class SplitRatio { } double ratio = split.getDividerLocation() / (double) span; 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. split.setResizeWeight(ratio); } diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java index e5d09fc..d6bfe88 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/VoiceActivationSection.java @@ -74,7 +74,7 @@ final class VoiceActivationSection { group.add(pttRadio); group.add(contRadio); group.add(vadRadio); - switch (settings.inputMode) { + switch (settings.inputMode.get()) { case PUSH_TO_TALK: pttRadio.setSelected(true); break; @@ -89,25 +89,25 @@ final class VoiceActivationSection { pttKeyButton.setToolTipText("Push-to-talk is a global hotkey; this opens its binding"); 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 -> micTest.configure(m -> m.setVadOverPtt(vadOverPttCheck.isSelected()))); 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.setToolTipText("Automatic: intelligent speech detection.
" + "Volume Gate: transmit when loud enough.
" + "Hybrid: loud enough and detected as speech."); thresholdSlider = new JSlider((int) InputLevel.MIN_DB, (int) InputLevel.MAX_DB, - (int) Math.round(settings.vadThresholdDb)); - thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb) + " dB"); - speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold * 100)); - speechLabel = new JLabel(Math.round(settings.speechThreshold * 100) + "%"); + (int) Math.round(settings.vadThresholdDb.get())); + thresholdLabel = new JLabel(Math.round(settings.vadThresholdDb.get()) + " dB"); + speechSlider = new JSlider(0, 100, (int) Math.round(settings.speechThreshold.get() * 100)); + speechLabel = new JLabel(Math.round(settings.speechThreshold.get() * 100) + "%"); meter = new LevelMeter(); - meter.setThreshold(settings.vadThresholdDb); + meter.setThreshold(settings.vadThresholdDb.get()); testControls = buildTestControls(); thresholdSlider.addChangeListener(e -> { @@ -180,13 +180,13 @@ final class VoiceActivationSection { /** Copies the form into {@code target}, without touching anything else. */ 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 - : Settings.InputMode.VOICE_ACTIVATION; - target.vadMode = currentVadMode(); - target.vadThresholdDb = thresholdSlider.getValue(); - target.speechThreshold = speechSlider.getValue() / 100.0; - target.vadOverPtt = vadOverPttCheck.isSelected(); + : Settings.InputMode.VOICE_ACTIVATION); + target.vadMode.set(currentVadMode()); + target.vadThresholdDb.set((double) thresholdSlider.getValue()); + target.speechThreshold.set(speechSlider.getValue() / 100.0); + target.vadOverPtt.set(vadOverPttCheck.isSelected()); } /** Applies a change to the microphone test, if it is running. */ diff --git a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowGeometry.java b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowGeometry.java index df7f373..ebfa40f 100644 --- a/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowGeometry.java +++ b/ts3-client/swing/src/main/java/eu/lixko/ts3j/client/ui/WindowGeometry.java @@ -30,7 +30,8 @@ final class WindowGeometry { } 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)) { Dimension min = frame.getMinimumSize(); saved.width = Math.max(saved.width, min.width); @@ -40,7 +41,7 @@ final class WindowGeometry { frame.setSize(UIScale.scale(defaultSize)); frame.setLocationRelativeTo(null); } - if (settings.windowMaximized) frame.setExtendedState(Frame.MAXIMIZED_BOTH); + if (settings.windowMaximized.get()) frame.setExtendedState(Frame.MAXIMIZED_BOTH); track(frame, settings); } @@ -48,13 +49,13 @@ final class WindowGeometry { Timer settle = new Timer(SETTLE_MS, e -> { int state = frame.getExtendedState(); 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; Rectangle r = frame.getBounds(); - settings.windowX = r.x; - settings.windowY = r.y; - settings.windowWidth = r.width; - settings.windowHeight = r.height; + settings.windowX.set(r.x); + settings.windowY.set(r.y); + settings.windowWidth.set(r.width); + settings.windowHeight.set(r.height); }); settle.setRepeats(false); frame.addComponentListener(new ComponentAdapter() {