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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 22:53:37 +00:00
co-authored by Claude Opus 5.5
parent bbe741d5cf
commit 203082d040
55 changed files with 581 additions and 615 deletions
@@ -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. */
@@ -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) ----
@@ -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. */
@@ -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());
}
}
@@ -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) {
@@ -0,0 +1,78 @@
package eu.lixko.ts3j.client.config;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/**
* One value of {@link Settings}: its key in the settings file, how it is written there, and who
* to tell when it changes. Listeners run on the thread that sets the value.
*/
public final class Setting<T> {
private final String key;
private final Function<String, T> parse;
private final Function<T, String> format;
private final UnaryOperator<T> constrain;
private final List<Consumer<? super T>> listeners = new CopyOnWriteArrayList<>();
private volatile T value;
/**
* @param parse reads the file's text; throws {@link IllegalArgumentException} for text it
* can't read, which keeps the default
* @param constrain brings a value into range, both when read and when set
*/
Setting(String key, T initial, Function<String, T> parse, Function<T, String> format, UnaryOperator<T> constrain) {
this.key = key;
this.parse = parse;
this.format = format;
this.constrain = constrain;
this.value = initial;
}
public String key() {
return key;
}
public T get() {
return value;
}
public void set(T newValue) {
T constrained = constrain.apply(Objects.requireNonNull(newValue));
if (constrained.equals(value)) return;
value = constrained;
for (Consumer<? super T> listener : listeners) listener.accept(constrained);
}
public void addListener(Consumer<? super T> listener) {
listeners.add(listener);
}
public void removeListener(Consumer<? super T> listener) {
listeners.remove(listener);
}
/** Runs {@code action} whenever any of {@code settings} changes. */
public static void onAnyChange(Runnable action, Setting<?>... settings) {
for (Setting<?> setting : settings) setting.addListener(v -> action.run());
}
void load(Properties props) {
String text = props.getProperty(key);
if (text == null) return;
try {
value = constrain.apply(parse.apply(text));
} catch (IllegalArgumentException unreadable) {
// keeps the default
}
}
void store(Properties props) {
props.setProperty(key, format.apply(value));
}
}
@@ -1,5 +1,6 @@
package eu.lixko.ts3j.client.config;
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).
*
* <p>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<Setting<?>> all = new ArrayList<>();
// ---- connection ----
public String lastAddress = "localhost";
public String nickname = System.getProperty("user.name", "TS3j User");
public String serverPassword = "";
public final Setting<String> lastAddress = text("lastAddress", "localhost");
public final Setting<String> nickname = text("nickname", System.getProperty("user.name", "TS3j User"));
public final Setting<String> 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<String> 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<String> defaultIdentityId = text("defaultIdentityId", "");
// ---- reported client version ----
/** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */
public boolean customVersion = false;
public final Setting<Boolean> customVersion = flag("customVersion", false);
/** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */
public String clientVersion = ClientVersion.DEFAULT.version();
public final Setting<String> clientVersion = text("clientVersion", ClientVersion.DEFAULT.version());
/** Operating system other clients see, e.g. "Windows". */
public String clientPlatform = ClientVersion.DEFAULT.platform();
public final Setting<String> clientPlatform = text("clientPlatform", ClientVersion.DEFAULT.platform());
/** TeamSpeak's signature over the version and platform; servers may verify it. */
public String clientVersionSign = ClientVersion.DEFAULT.sign();
public final Setting<String> clientVersionSign = text("clientVersionSign", ClientVersion.DEFAULT.sign());
// ---- audio devices (mixer names; empty = system default) ----
public String inputDevice = "";
public String outputDevice = "";
public final Setting<String> inputDevice = text("inputDevice", "");
public final Setting<String> outputDevice = text("outputDevice", "");
// ---- voice ----
public InputMode inputMode = InputMode.VOICE_ACTIVATION;
public final Setting<InputMode> inputMode = choice("inputMode", InputMode.VOICE_ACTIVATION);
/** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */
public VadMode vadMode = VadMode.HYBRID;
public final Setting<VadMode> vadMode = choice("vadMode", VadMode.HYBRID);
/**
* Volume-gate threshold on {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, the same one
* Volume-gate threshold on {@link InputLevel}'s scale, the same one
* the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40.
*/
public double vadThresholdDb = -40.0;
public final Setting<Double> vadThresholdDb = decimal("vadLevelDb", -40.0);
/**
* Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this
* {@code vad_likelihood} and also defaults it to 0.5.
*/
public double speechThreshold = 0.5;
public final Setting<Double> speechThreshold = decimal("speechThreshold", 0.5);
/** Keep voice activation running while in push-to-talk mode. */
public boolean vadOverPtt = false;
public final Setting<Boolean> vadOverPtt = flag("vadOverPtt", false);
/** Opus target bitrate in bits/sec. */
public int bitrate = 48000;
public final Setting<Integer> bitrate = number("bitrate", 48000);
/** Opus complexity 0..10. */
public int complexity = 10;
public final Setting<Integer> complexity = number("complexity", 10);
/** Opus variable bitrate. */
public boolean vbr = true;
public final Setting<Boolean> vbr = flag("vbr", true);
/** Opus in-band forward error correction. */
public boolean fec = true;
public final Setting<Boolean> fec = flag("fec", true);
/** Expected packet loss percent (drives FEC). */
public int packetLoss = 5;
public final Setting<Integer> packetLoss = number("packetLoss", 5);
/** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */
public boolean music = false;
public final Setting<Boolean> music = flag("music", false);
/**
* Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off.
* 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<Integer> 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<Integer> 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<Integer> 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<Double> 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<Double> masterVolume = decimal("masterVolume", 1.0);
/** Microphone input gain multiplier applied before VAD/encode. */
public double inputVolume = 1.0;
public final Setting<Double> inputVolume = decimal("inputVolume", 1.0);
/** Remove steady background noise from the microphone (WebRTC noise suppression). */
public boolean denoise = true;
public final Setting<Boolean> denoise = flag("denoise", true);
/** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */
public int denoiserLevel = 1;
public final Setting<Integer> denoiserLevel = number("denoiserLevel", 1);
/** Attenuate keyboard clicks while typing. */
public boolean typingAttenuation = true;
public final Setting<Boolean> typingAttenuation = flag("typingAttenuation", true);
/** Automatic gain control: normalise microphone loudness to a target level. */
public boolean agc = true;
public final Setting<Boolean> 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<Integer> 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<Boolean> 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<String> soundPack = text("soundPack", "default");
/** Notification sound volume, 0..1. */
public double soundVolume = 1.0;
public final Setting<Double> soundVolume = decimal("soundVolume", 1.0);
/** Extra folder to look for sound packs in, on top of the well-known locations. */
public String soundPackDir = "";
public final Setting<String> soundPackDir = text("soundPackDir", "");
/** Whether pokes and private messages show a desktop notification while the window is in the background. */
public boolean desktopNotifications = true;
public final Setting<Boolean> 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<String> 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<Boolean> 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<String> iconPackDir = text("iconPackDir", "");
/** Look-and-feel variant; see {@link Appearance}. */
public Appearance appearance = Appearance.LIGHT;
public final Setting<Appearance> appearance = choice("appearance", Appearance.LIGHT);
/** Interface scale factor, 1.0 being 100&nbsp;%; 0 follows the desktop. Read at startup. */
public double uiScale = 0;
public final Setting<Double> 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<Boolean> showStatusBar = flag("showStatusBar", true);
/** Whether the Master Volume slider is shown on the toolbar. */
public boolean showMasterVolumeSlider = true;
public final Setting<Boolean> showMasterVolumeSlider = flag("showMasterVolumeSlider", true);
/** Share of the tree/info column the tree takes, i.e. where their divider sits. */
public double infoSplitRatio = 0.68;
public final Setting<Double> infoSplitRatio = decimal("infoSplitRatio", 0.68);
/** Share of the window's width the tree/info column takes, beside the chat. */
public double chatSplitRatio = 0.45;
public final Setting<Double> chatSplitRatio = decimal("chatSplitRatio", 0.45);
/** The main window's bounds when not maximised; a width of 0 until it has been placed. */
public int windowX, windowY, windowWidth, windowHeight;
public boolean windowMaximized;
public final Setting<Integer> windowX = number("windowX", 0);
public final Setting<Integer> windowY = number("windowY", 0);
public final Setting<Integer> windowWidth = number("windowWidth", 0);
public final Setting<Integer> windowHeight = number("windowHeight", 0);
public final Setting<Boolean> windowMaximized = flag("windowMaximized", false);
/** Whether the ban list shows the bans we created ourselves in bold. */
public boolean banHighlightOwn = true;
public final Setting<Boolean> banHighlightOwn = flag("banHighlightOwn", true);
/** The ban list columns the user shows, comma-separated column names; empty for the default set. */
public String banListColumns = "";
public final Setting<String> 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<Boolean> colorContacts = flag("colorContacts", true);
/** Whose whispers are played. */
public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED;
public final Setting<WhisperPolicy> whisperPolicy = choice("whisperPolicy", WhisperPolicy.ALLOW_UNLESS_DENIED);
/** Keep chat logs, and show their history when a chat opens. */
public boolean chatLogs = true;
public final Setting<Boolean> chatLogs = flag("chatLogs", true);
/** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */
public String chatLogDir = "";
public final Setting<String> chatLogDir = text("chatLogDir", "");
/** The folder recordings were last saved to; empty for {@code ~/Recordings}. */
public String recordingDir = "";
public final Setting<String> recordingDir = text("recordingDir", "");
/** Whether descriptions show their pictures, fetched from the web, or only links to them. */
public boolean descriptionPictures = true;
public final Setting<Boolean> descriptionPictures = flag("descriptionPictures", true);
/** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100&nbsp;%. */
public double chatZoom = 1.0;
public final Setting<Double> chatZoom = decimal("chatZoom", 1.0);
/** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100&nbsp;%. */
public double infoZoom = 1.0;
public final Setting<Double> 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 <T> Setting<T> add(String key, T initial, Function<String, T> parse, Function<T, String> format,
UnaryOperator<T> constrain) {
Setting<T> 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<String> text(String key, String initial) {
return add(key, initial, Function.identity(), Function.identity(), UnaryOperator.identity());
}
private static <E extends Enum<E>> E parseEnum(Class<E> type, String v, E def) {
if (v == null) return def;
try {
return Enum.valueOf(type, v.trim());
} catch (IllegalArgumentException e) {
return def;
}
private Setting<Boolean> flag(String key, boolean initial) {
return add(key, initial, Boolean::parseBoolean, String::valueOf, UnaryOperator.identity());
}
private Setting<Integer> number(String key, int initial) {
return add(key, initial, Integer::parseInt, String::valueOf, UnaryOperator.identity());
}
private Setting<Integer> number(String key, int initial, int min, int max) {
return add(key, initial, Integer::parseInt, String::valueOf, v -> Math.max(min, Math.min(max, v)));
}
private Setting<Double> decimal(String key, double initial) {
return add(key, initial, Double::parseDouble, String::valueOf, UnaryOperator.identity());
}
private <E extends Enum<E>> Setting<E> choice(String key, E initial) {
return add(key, initial, v -> Enum.valueOf(initial.getDeclaringClass(), v.trim()), Enum::name,
UnaryOperator.identity());
}
/**
* Converts a threshold saved under the old {@code vadThresholdDb} key, which was in
* 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);
}
}
@@ -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);
@@ -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);
@@ -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;
@@ -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 ----
@@ -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();
}
/**
@@ -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<SoundPack> 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());
}
/**
@@ -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;
}
}
@@ -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<Boolean> heard = new ArrayList<>();
settings.showStatusBar.addListener(heard::add);
settings.showStatusBar.set(true);
settings.showStatusBar.set(false);
settings.showStatusBar.set(false);
assertEquals(List.of(false), heard);
}
@Test
void outOfRangeValuesAreClamped() throws Exception {
Files.writeString(dir.resolve("settings.properties"), "agcBoostDb=99\n");
Settings loaded = Settings.load();
assertEquals(Settings.MAX_AGC_BOOST_DB, loaded.agcBoostDb.get());
loaded.agcBoostDb.set(-5);
assertEquals(0, loaded.agcBoostDb.get());
}
}
@@ -38,7 +38,7 @@ class TeamSpeakImporterTest {
@Test
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<Bookmark> 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