yandex-music-rs/src/config.rs
2026-11-27 13:17:37 +03:00

272 lines
7.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::api::models::Track;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThemeMode {
System,
Dark,
Light,
}
impl ThemeMode {
/// Resolve `ThemeMode::System` to concrete dark/light boolean via Windows Registry `AppsUseLightTheme`
/// (exact match to Chromium's `prefers-color-scheme: light` in Electron 5.129.0).
pub fn is_dark_resolved(self) -> bool {
match self {
ThemeMode::Dark => true,
ThemeMode::Light => false,
ThemeMode::System => !detect_system_light_theme(),
}
}
}
#[cfg(windows)]
pub fn detect_system_light_theme() -> bool {
// Query HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize\AppsUseLightTheme
// via advapi32 RegGetValueW (zero extra crate dependencies!)
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
const HKEY_CURRENT_USER: isize = -2147483647; // 0x80000001
const RRF_RT_REG_DWORD: u32 = 0x00000010;
#[link(name = "advapi32")]
extern "system" {
fn RegGetValueW(
hkey: isize,
lp_sub_key: *const u16,
lp_value: *const u16,
dw_flags: u32,
pdw_type: *mut u32,
pv_data: *mut std::ffi::c_void,
pcb_data: *mut u32,
) -> i32;
}
let subkey: Vec<u16> = OsStr::new("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize")
.encode_wide()
.chain(Some(0))
.collect();
let valname: Vec<u16> = OsStr::new("AppsUseLightTheme")
.encode_wide()
.chain(Some(0))
.collect();
let mut data: u32 = 0;
let mut size: u32 = std::mem::size_of::<u32>() as u32;
let status = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
subkey.as_ptr(),
valname.as_ptr(),
RRF_RT_REG_DWORD,
std::ptr::null_mut(),
&mut data as *mut u32 as *mut std::ffi::c_void,
&mut size,
)
};
status == 0 && data == 1
}
#[cfg(not(windows))]
pub fn detect_system_light_theme() -> bool {
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Language {
Ru,
En,
}
impl Default for Language {
fn default() -> Self {
Language::Ru
}
}
impl Language {
pub fn api_code(self) -> &'static str {
match self {
Language::Ru => "ru",
Language::En => "en",
}
}
pub fn is_ru(self) -> bool {
matches!(self, Language::Ru)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AudioQuality {
Lossless, // FLAC / FLAC-MP4
High, // 320 kbps MP3 / AAC
Standard, // 192 kbps MP3
}
impl AudioQuality {
pub fn label(&self) -> &'static str {
self.label_for(Language::Ru)
}
pub fn label_for(&self, lang: Language) -> &'static str {
match (self, lang) {
(AudioQuality::Lossless, Language::Ru) => "Превосходное (Lossless FLAC)",
(AudioQuality::High, Language::Ru) => "Высокое (320 кбит/с)",
(AudioQuality::Standard, Language::Ru) => "Оптимальное (192 кбит/с)",
(AudioQuality::Lossless, Language::En) => "Superb (Lossless FLAC)",
(AudioQuality::High, Language::En) => "High (320 kbps)",
(AudioQuality::Standard, Language::En) => "Optimal (192 kbps)",
}
}
pub fn api_quality(&self) -> &'static str {
match self {
AudioQuality::Lossless => "lossless",
AudioQuality::High => "nq",
AudioQuality::Standard => "lq",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PinnedItem {
pub id: String,
pub kind: String, // "likes" | "playlist" | "album" | "artist" | "wave"
pub title: String,
pub subtitle: String,
pub cover_uri: Option<String>,
pub owner_uid: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
pub oauth_token: Option<String>,
pub theme: ThemeMode,
#[serde(default)]
pub language: Language,
pub audio_quality: AudioQuality,
pub volume: f32,
pub muted: bool,
pub sidebar_collapsed: bool,
pub eq_enabled: bool,
pub eq_bands_db: [f32; 10], // 32, 64, 125, 250, 500, 1k, 2k, 4k, 8k, 16k Hz
pub normalize_loudness: bool,
pub crossfade_secs: f32,
#[serde(default)]
pub ai_content_reduction: bool,
#[serde(default)]
pub child_mode: bool,
#[serde(default = "default_true")]
pub close_to_tray: bool,
pub max_cover_cache: usize,
pub show_perf_hud: bool,
pub search_history: Vec<String>,
pub pinned_items: Vec<PinnedItem>,
pub vibe_mood: Option<String>,
pub vibe_activity: Option<String>,
pub vibe_character: Option<String>,
pub vibe_language: Option<String>,
/// Persisted playback session restored cleanly across restarts
#[serde(default)]
pub last_queue: Vec<Track>,
#[serde(default)]
pub last_queue_index: usize,
#[serde(default)]
pub last_position_ms: u64,
#[serde(default)]
pub last_context_name: String,
#[serde(default)]
pub last_is_vibe: bool,
#[serde(default)]
pub shuffle: bool,
#[serde(default)]
pub repeat_mode: String, // "off" | "all" | "one"
/// Track IDs downloaded to local offline cache directory
#[serde(default)]
pub downloaded_tracks: Vec<Track>,
}
fn default_true() -> bool {
true
}
impl Default for AppConfig {
fn default() -> Self {
Self {
oauth_token: None,
theme: ThemeMode::Dark,
language: Language::Ru,
audio_quality: AudioQuality::Lossless,
volume: 0.78,
muted: false,
sidebar_collapsed: false,
eq_enabled: false,
eq_bands_db: [0.0; 10],
normalize_loudness: true,
crossfade_secs: 0.0,
ai_content_reduction: false,
child_mode: false,
close_to_tray: true,
max_cover_cache: 256,
show_perf_hud: false,
search_history: Vec::new(),
pinned_items: vec![PinnedItem {
id: "likes".into(),
kind: "likes".into(),
title: "Мне нравится".into(),
subtitle: "Плейлист".into(),
cover_uri: None,
owner_uid: None,
}],
vibe_mood: None,
vibe_activity: None,
vibe_character: None,
vibe_language: None,
last_queue: Vec::new(),
last_queue_index: 0,
last_position_ms: 0,
last_context_name: String::new(),
last_is_vibe: false,
shuffle: false,
repeat_mode: "off".into(),
downloaded_tracks: Vec::new(),
}
}
}
impl AppConfig {
pub fn offline_cache_dir() -> PathBuf {
let base = dirs::cache_dir()
.or_else(dirs::config_dir)
.unwrap_or_else(|| PathBuf::from("."));
base.join("YandexMusicRust").join("offline_audio")
}
pub fn config_path() -> PathBuf {
let base = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
base.join("YandexMusicRust").join("config.json")
}
pub fn load() -> Self {
let path = Self::config_path();
if let Ok(data) = std::fs::read_to_string(&path) {
if let Ok(mut cfg) = serde_json::from_str::<AppConfig>(&data) {
cfg.max_cover_cache = cfg.max_cover_cache.clamp(128, 1024);
return cfg;
}
}
Self::default()
}
pub fn save(&self) {
let path = Self::config_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(json) = serde_json::to_string_pretty(self) {
let _ = std::fs::write(path, json);
}
}
}