Mulberry/src/config.rs
astar76 4fef60ba23 Rewrite Mulberry in Rust (egui + libmpv)
Port of the Python/PyQt6 app: same library database, playlists, hero panel,
lyrics, tag editor, MusicBrainz/cover tools, CD ripping, MPRIS and tray.

New: right-click 'Set <tag> to "value"' writes the clicked cell's tag into every
selected file (with undo). The seek bar now runs off a monotonic position clock
so it can't jump back and forth.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 14:46:05 -05:00

371 lines
13 KiB
Rust

//! Paths, settings and small shared helpers.
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::{LazyLock, RwLock};
pub const APP_NAME: &str = "Mulberry";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const USER_AGENT: &str = concat!("Mulberry/", env!("CARGO_PKG_VERSION"), " ( https://archlinux.tail7c4f5e.ts.net/git/astar76/Mulberry )");
fn xdg(var: &str, default: &str) -> PathBuf {
match std::env::var_os(var) {
Some(v) if !v.is_empty() => PathBuf::from(v),
_ => dirs::home_dir().unwrap_or_default().join(default),
}
}
pub struct Paths {
pub config: PathBuf,
pub data: PathBuf,
pub cache: PathBuf,
pub covers: PathBuf,
pub thumbs: PathBuf,
pub db: PathBuf,
}
pub static PATHS: LazyLock<Paths> = LazyLock::new(|| {
let config = xdg("XDG_CONFIG_HOME", ".config").join("mulberry");
let data = xdg("XDG_DATA_HOME", ".local/share").join("mulberry");
let cache = xdg("XDG_CACHE_HOME", ".cache").join("mulberry");
let p = Paths {
covers: data.join("covers"),
thumbs: cache.join("thumbs"),
db: data.join("library.db"),
config,
data,
cache,
};
for d in [&p.config, &p.data, &p.cache, &p.covers, &p.thumbs] {
let _ = std::fs::create_dir_all(d);
}
p
});
pub const AUDIO_EXTS: &[&str] = &[
"mp3", "mp2", "mp1", "flac", "ogg", "oga", "opus", "spx", "m4a", "m4b", "mp4", "aac", "alac", "wav", "wave", "aif",
"aiff", "aifc", "wma", "asf", "ape", "wv", "mpc", "mp+", "tta", "ofr", "ofs", "tak", "dsf", "dff", "mka", "webm",
"ac3", "eac3", "dts", "amr", "au", "snd", "caf", "w64", "rf64", "mod", "xm", "it", "s3m", "mtm", "umx", "669",
"med", "okt", "far", "stm", "ult", "psm", "mptm", "spc", "vgm", "vgz", "gym", "nsf", "sid", "mid", "midi", "kar",
"3gp", "m4r", "aa", "aax", "voc", "mlp", "thd", "truehd",
];
pub const PLAYLIST_EXTS: &[&str] = &["m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"];
pub fn ext_of(path: &str) -> String {
std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default()
}
pub fn is_audio_file(path: &str) -> bool {
AUDIO_EXTS.contains(&ext_of(path).as_str())
}
pub fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"))
}
// ------------------------------------------------------------------ settings
fn defaults() -> BTreeMap<&'static str, Value> {
let m: Vec<(&str, Value)> = vec![
("library/folders", json!([])),
("library/scan_on_start", json!(true)),
("library/grouping", json!("albumartist_album")),
("playback/device", json!("")),
("playback/volume", json!(70)),
("playback/replaygain", json!("off")),
("playback/rg_preamp", json!(0.0)),
("playback/gapless", json!(true)),
("playback/crossfade", json!(0)),
("playback/eq_enabled", json!(false)),
("playback/eq_bands", json!(vec![0.0f64; 10])),
("playback/eq_preamp", json!(0.0)),
("playback/repeat", json!("off")),
("playback/shuffle", json!(false)),
("playback/resume", json!(true)),
("appearance/color_source", json!("kde")),
("appearance/mode", json!("kde")),
("appearance/custom_color", json!("#9a7fd1")),
("appearance/hero", json!("full")),
("appearance/playlist_art_bg", json!(true)),
("appearance/visualizer", json!(true)),
("appearance/analyzer", json!(true)),
("appearance/font", json!("")),
("appearance/notifications", json!(true)),
("appearance/tray", json!(true)),
("appearance/floating_shape", json!(true)),
("appearance/max_fps", json!(30)),
("lastfm/enabled", json!(false)),
("lastfm/api_key", json!("")),
("lastfm/use_own_key", json!(false)),
("lastfm/api_secret", json!("")),
("lastfm/session", json!("")),
("lastfm/user", json!("")),
("listenbrainz/enabled", json!(false)),
("listenbrainz/token", json!("")),
("online/auto_lyrics", json!(true)),
("online/auto_covers", json!(true)),
("online/save_covers_to_folder", json!(false)),
("online/acoustid_key", json!("")),
("lyrics/source", json!("auto")),
("lyrics/plain", json!(false)),
("ui/sidebar_tab", json!(0)),
("ui/sidebar", json!(true)),
("ui/sidebar_w", json!(300.0)),
("ui/win_w", json!(0.0)),
("ui/win_h", json!(0.0)),
("export/relative_paths", json!(false)),
("cd/device", json!("")),
("cd/rip_format", json!("flac")),
("cd/rip_quality", json!(5)),
("cd/rip_dir", json!(home().join("Music").to_string_lossy())),
("cd/rip_pattern", json!("{albumartist}/{album}/{track:02d} - {title}")),
];
m.into_iter().collect()
}
/// Settings stored as flat `section/key` JSON. On first run the values of the old
/// Python app (`mulberry.conf`, a QSettings INI file) are imported.
pub struct Settings {
values: RwLock<BTreeMap<String, Value>>,
defaults: BTreeMap<&'static str, Value>,
path: PathBuf,
}
pub static SETTINGS: LazyLock<Settings> = LazyLock::new(Settings::load);
pub fn settings() -> &'static Settings {
&SETTINGS
}
impl Settings {
fn load() -> Settings {
let path = PATHS.config.join("settings.json");
let defaults = defaults();
let mut values: BTreeMap<String, Value> = BTreeMap::new();
match std::fs::read_to_string(&path) {
Ok(txt) => {
if let Ok(Value::Object(o)) = serde_json::from_str::<Value>(&txt) {
values = o.into_iter().collect();
}
}
Err(_) => {
values = import_qsettings(&defaults);
}
}
let s = Settings { values: RwLock::new(values), defaults, path };
s.save();
s
}
fn save(&self) {
let v = self.values.read().unwrap();
if let Ok(txt) = serde_json::to_string_pretty(&*v) {
let tmp = self.path.with_extension("json.tmp");
if std::fs::write(&tmp, txt).is_ok() {
let _ = std::fs::rename(&tmp, &self.path);
}
}
}
fn raw(&self, key: &str) -> Value {
if let Some(v) = self.values.read().unwrap().get(key) {
return v.clone();
}
self.defaults.get(key).cloned().unwrap_or(Value::Null)
}
pub fn set(&self, key: &str, value: impl Into<Value>) {
self.values.write().unwrap().insert(key.to_string(), value.into());
self.save();
}
pub fn get_bool(&self, key: &str) -> bool {
match self.raw(key) {
Value::Bool(b) => b,
Value::String(s) => matches!(s.as_str(), "1" | "true" | "yes"),
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
_ => false,
}
}
pub fn get_i64(&self, key: &str) -> i64 {
match self.raw(key) {
Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)).unwrap_or(0),
Value::String(s) => s.parse().unwrap_or(0),
Value::Bool(b) => b as i64,
_ => 0,
}
}
pub fn get_f64(&self, key: &str) -> f64 {
match self.raw(key) {
Value::Number(n) => n.as_f64().unwrap_or(0.0),
Value::String(s) => s.parse().unwrap_or(0.0),
_ => 0.0,
}
}
pub fn get_str(&self, key: &str) -> String {
match self.raw(key) {
Value::String(s) => s,
Value::Null => String::new(),
v => v.to_string(),
}
}
pub fn get_list(&self, key: &str) -> Vec<String> {
match self.raw(key) {
Value::Array(a) => a.into_iter().filter_map(|v| v.as_str().map(String::from)).collect(),
Value::String(s) if !s.is_empty() => vec![s],
_ => vec![],
}
}
pub fn get_f64_list(&self, key: &str) -> Vec<f64> {
match self.raw(key) {
Value::Array(a) => a.into_iter().map(|v| v.as_f64().unwrap_or(0.0)).collect(),
_ => vec![],
}
}
}
// ------------------------------------------------------------------ legacy import
fn import_qsettings(defaults: &BTreeMap<&'static str, Value>) -> BTreeMap<String, Value> {
let mut out = BTreeMap::new();
let Ok(txt) = std::fs::read_to_string(PATHS.config.join("mulberry.conf")) else {
return out;
};
let mut section = String::from("General");
for line in txt.lines() {
let line = line.trim_end();
if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = s.to_string();
continue;
}
let Some((k, v)) = line.split_once('=') else { continue };
let key = if section == "General" { k.to_string() } else { format!("{section}/{k}") };
let Some(def) = defaults.get(key.as_str()) else { continue };
let val = match def {
Value::Bool(_) => json!(matches!(v, "true" | "1")),
Value::Number(n) if n.is_f64() => json!(v.parse::<f64>().unwrap_or(0.0)),
Value::Number(_) => json!(v.parse::<i64>().unwrap_or(0)),
Value::Array(_) if key == "library/folders" => json!(decode_string_list(v)),
Value::Array(_) => json!(v.split(',').filter_map(|x| x.trim().parse::<f64>().ok()).collect::<Vec<_>>()),
_ => json!(v.trim_matches('"')),
};
out.insert(key, val);
}
out
}
/// Decode a QSettings `@Variant(...)` QStringList (UTF-16BE strings) or a plain comma list.
fn decode_string_list(v: &str) -> Vec<String> {
if !v.starts_with("@Variant(") {
return v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
}
let inner = &v["@Variant(".len()..v.len().saturating_sub(1)];
let b = inner.as_bytes();
let mut raw: Vec<u8> = Vec::new();
let mut i = 0;
while i < b.len() {
if b[i] == b'\\' && i + 1 < b.len() {
i += 1;
match b[i] {
b'0' => {
raw.push(0);
i += 1;
}
b'x' => {
let mut n = 0u32;
let mut cnt = 0;
i += 1;
while i < b.len() && cnt < 2 && (b[i] as char).is_ascii_hexdigit() {
n = n * 16 + (b[i] as char).to_digit(16).unwrap();
i += 1;
cnt += 1;
}
raw.push(n as u8);
}
b'n' => {
raw.push(b'\n');
i += 1;
}
b't' => {
raw.push(b'\t');
i += 1;
}
b'\\' => {
raw.push(b'\\');
i += 1;
}
c => {
raw.push(c);
i += 1;
}
}
} else {
raw.push(b[i]);
i += 1;
}
}
let mut out = vec![];
let mut p = 0;
parse_variant(&raw, &mut p, &mut out);
out
}
fn be32(raw: &[u8], p: usize) -> Option<usize> {
raw.get(p..p + 4).map(|b| u32::from_be_bytes(b.try_into().unwrap()) as usize)
}
/// Collect the strings of a serialized QVariant (QString, QStringList or QVariantList of those).
fn parse_variant(raw: &[u8], p: &mut usize, out: &mut Vec<String>) {
let Some(ty) = be32(raw, *p) else { return };
*p += 5; // type id + isNull byte
match ty {
10 => {
let Some(len) = be32(raw, *p) else { return };
*p += 4;
if len != 0xFFFF_FFFF && *p + len <= raw.len() {
let units: Vec<u16> = raw[*p..*p + len].chunks(2).map(|c| u16::from_be_bytes([c[0], *c.get(1).unwrap_or(&0)])).collect();
out.push(String::from_utf16_lossy(&units));
*p += len;
}
}
11 => {
let Some(count) = be32(raw, *p) else { return };
*p += 4;
for _ in 0..count {
let Some(len) = be32(raw, *p) else { return };
*p += 4;
if len == 0xFFFF_FFFF || *p + len > raw.len() {
return;
}
let units: Vec<u16> = raw[*p..*p + len].chunks(2).map(|c| u16::from_be_bytes([c[0], *c.get(1).unwrap_or(&0)])).collect();
out.push(String::from_utf16_lossy(&units));
*p += len;
}
}
9 => {
let Some(count) = be32(raw, *p) else { return };
*p += 4;
for _ in 0..count {
parse_variant(raw, p, out);
}
}
_ => {}
}
}
pub fn fmt_time(sec: f64) -> String {
fmt_time_h(sec, false)
}
pub fn fmt_time_h(sec: f64, force_hours: bool) -> String {
if !(sec >= 0.0) {
return "--:--".into();
}
let s = sec as i64;
let (h, rem) = (s / 3600, s % 3600);
let (m, s) = (rem / 60, rem % 60);
if h > 0 || force_hours {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m}:{s:02}")
}
}