Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

fix(security): restrict aria2c to http/ftp, verify TLS by default, verify every managed binary

tonhowtff267b5b3f9cf
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index 14e0ce47..83855e66 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -14,6 +14,7 @@
"clipboard-manager:allow-write-text",
"updater:default",
"process:allow-restart",
+ "core:window:allow-start-dragging",
"core:window:allow-set-badge-count",
"core:window:allow-set-progress-bar",
"core:window:allow-set-overlay-icon",
diff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rs
index b44c7ffb..8df3237b 100644
--- a/src-tauri/omniget-core/src/core/dependencies.rs
+++ b/src-tauri/omniget-core/src/core/dependencies.rs
@@ -11,6 +11,100 @@ fn managed_bin_dir() -> Option<PathBuf> {
Some(crate::core::paths::app_data_dir()?.join("bin"))
}
+/// Verificação de integridade dos binários gerenciados.
+///
+/// Regra: **fail-closed**. Se a origem publica um hash e ele não confere, ou
+/// se o hash esperado não pôde ser obtido de uma origem que sabidamente o
+/// publica, o binário é descartado.
+pub mod integrity {
+ use anyhow::anyhow;
+
+ pub fn sha256_hex(bytes: &[u8]) -> String {
+ use sha2::{Digest, Sha256};
+ let mut hasher = Sha256::new();
+ hasher.update(bytes);
+ hasher
+ .finalize()
+ .iter()
+ .map(|b| format!("{:02x}", b))
+ .collect()
+ }
+
+ fn is_sha256(candidate: &str) -> bool {
+ candidate.len() == 64 && candidate.bytes().all(|b| b.is_ascii_hexdigit())
+ }
+
+ /// Lê um arquivo estilo `sha256sum`: `<64-hex><espaços>[*]<nome>`.
+ /// Linha em branco ou malformada é pulada — não interrompe a busca.
+ pub fn parse_sha256sums(text: &str, asset: &str) -> Option<String> {
+ for line in text.lines() {
+ let mut parts = line.split_whitespace();
+ let (Some(hash), Some(name)) = (parts.next(), parts.next()) else {
+ continue;
+ };
+ let name = name.trim_start_matches('*');
+ if name == asset && is_sha256(hash) {
+ return Some(hash.to_lowercase());
+ }
+ }
+ None
+ }
+
+ /// Arquivo `.sha256sum` de asset único (o Deno publica um por asset).
+ pub fn parse_single_sha256(text: &str) -> Option<String> {
+ let first = text.split_whitespace().next()?;
+ is_sha256(first).then(|| first.to_lowercase())
+ }
+
+ /// `digest` da API de releases do GitHub, no formato `sha256:<hex>`.
+ pub fn parse_github_digest(digest: &str) -> Option<String> {
+ let hex = digest.trim().strip_prefix("sha256:")?;
+ is_sha256(hex).then(|| hex.to_lowercase())
+ }
+
+ pub fn verify_sha256(bytes: &[u8], expected: &str, label: &str) -> anyhow::Result<()> {
+ let actual = sha256_hex(bytes);
+ if actual == expected.to_lowercase() {
+ tracing::info!("[integrity] {} verificado (sha256 confere)", label);
+ return Ok(());
+ }
+ Err(anyhow!(
+ "{}: hash nao confere — esperado {}, obtido {}. Download descartado.",
+ label,
+ expected,
+ actual
+ ))
+ }
+
+ /// Busca o hash esperado num arquivo de sums remoto. `Err` quando a origem
+ /// publica sums mas não conseguimos obtê-los — o chamador deve abortar.
+ pub async fn expected_from_sums_url(
+ client: &reqwest::Client,
+ sums_url: &str,
+ asset: &str,
+ ) -> anyhow::Result<String> {
+ let response = client
+ .get(sums_url)
+ .send()
+ .await
+ .map_err(|e| anyhow!("nao foi possivel buscar {}: {}", sums_url, e))?;
+ if !response.status().is_success() {
+ return Err(anyhow!(
+ "nao foi possivel buscar {}: HTTP {}",
+ sums_url,
+ response.status()
+ ));
+ }
+ let text = response
+ .text()
+ .await
+ .map_err(|e| anyhow!("corpo ilegivel de {}: {}", sums_url, e))?;
+ parse_sha256sums(&text, asset)
+ .or_else(|| parse_single_sha256(&text))
+ .ok_or_else(|| anyhow!("{} nao esta listado em {}", asset, sums_url))
+ }
+}
+
pub fn bin_name(tool: &str) -> String {
if cfg!(target_os = "windows") {
format!("{}.exe", tool)
@@ -806,3 +900,49 @@ async fn download_aria2c() -> anyhow::Result<PathBuf> {
Ok(aria2c_target)
}
+
+#[cfg(test)]
+mod integrity_tests {
+ use super::integrity::*;
+
+ const VAZIO: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+ #[test]
+ fn sha256_de_vetor_conhecido() {
+ assert_eq!(sha256_hex(b""), VAZIO);
+ }
+
+ #[test]
+ fn verify_sha256_recusa_binario_adulterado() {
+ assert!(verify_sha256(b"", VAZIO, "t").is_ok());
+ assert!(verify_sha256(b"", &VAZIO.to_uppercase(), "t").is_ok());
+ let erro = verify_sha256(b"binario trocado", VAZIO, "yt-dlp").unwrap_err();
+ assert!(erro.to_string().contains("yt-dlp"));
+ }
+
+ #[test]
+ fn linha_em_branco_nao_interrompe_a_busca_no_sums() {
+ // Regressao: a versao anterior usava `?` dentro do laco, entao a
+ // primeira linha vazia ou de um token so abortava a funcao inteira e o
+ // asset seguinte nunca era encontrado -> instalacao sem verificacao.
+ let sums = format!("\n\ncomentario\n{} yt-dlp.exe\n\n{} yt-dlp_macos\n", VAZIO, "1".repeat(64));
+ assert_eq!(parse_sha256sums(&sums, "yt-dlp.exe").as_deref(), Some(VAZIO));
+ assert_eq!(parse_sha256sums(&sums, "yt-dlp_macos").as_deref(), Some("1".repeat(64).as_str()));
+ assert_eq!(parse_sha256sums(&sums, "ausente"), None);
+ }
+
+ #[test]
+ fn sums_aceita_marcador_binario_e_recusa_hash_invalido() {
+ let bin = format!("{} *ffmpeg.zip\n", VAZIO);
+ assert_eq!(parse_sha256sums(&bin, "ffmpeg.zip").as_deref(), Some(VAZIO));
+ assert_eq!(parse_sha256sums("abc yt-dlp.exe\n", "yt-dlp.exe"), None);
+ assert_eq!(parse_sha256sums(&format!("{} yt-dlp.exe\n", "z".repeat(64)), "yt-dlp.exe"), None);
+ }
+
+ #[test]
+ fn digest_da_api_do_github() {
+ assert_eq!(parse_github_digest(&format!("sha256:{}", VAZIO)).as_deref(), Some(VAZIO));
+ assert_eq!(parse_github_digest(VAZIO), None);
+ assert_eq!(parse_github_digest("sha512:abc"), None);
+ }
+}
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index 5d6404e1..8b1b8648 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -28,6 +28,7 @@ type EmbedMetadataFn = Box<dyn Fn() -> bool + Send + Sync>;
type EmbedThumbnailFn = Box<dyn Fn() -> bool + Send + Sync>;
type SpeedLimitFn = Box<dyn Fn() -> Option<String> + Send + Sync>;
type LiveFromStartFn = Box<dyn Fn() -> bool + Send + Sync>;
+type InsecureTlsFn = Box<dyn Fn() -> bool + Send + Sync>;
type ConcurrentFragmentsFn = Box<dyn Fn() -> u32 + Send + Sync>;
type UserAgentFn = Box<dyn Fn() -> Option<String> + Send + Sync>;
type SponsorBlockModeFn = Box<dyn Fn() -> String + Send + Sync>;
@@ -52,11 +53,77 @@ static EMBED_METADATA_FN: OnceLock<EmbedMetadataFn> = OnceLock::new();
static EMBED_THUMBNAIL_FN: OnceLock<EmbedThumbnailFn> = OnceLock::new();
static SPEED_LIMIT_FN: OnceLock<SpeedLimitFn> = OnceLock::new();
static LIVE_FROM_START_FN: OnceLock<LiveFromStartFn> = OnceLock::new();
+static INSECURE_TLS_FN: OnceLock<InsecureTlsFn> = OnceLock::new();
static CONCURRENT_FRAGMENTS_FN: OnceLock<ConcurrentFragmentsFn> = OnceLock::new();
static USER_AGENT_FN: OnceLock<UserAgentFn> = OnceLock::new();
static SPONSORBLOCK_MODE_FN: OnceLock<SponsorBlockModeFn> = OnceLock::new();
static SPONSORBLOCK_CATEGORIES_FN: OnceLock<SponsorBlockCategoriesFn> = OnceLock::new();
+/// Protocolos que podem ser delegados ao aria2c. Manifesto fragmentado
+/// (`m3u8*`, `dash_frag_urls`) fica de fora por causa da CVE-2026-50574 — o
+/// yt-dlp removeu esse suporte na 2026.06.09 e recomenda `-N` no lugar.
+pub(crate) const ARIA2C_ALLOWED_PROTOCOLS: &str = "http,ftp";
+
+/// Piso de versão do yt-dlp. 2026.06.09 é a release que corrigiu
+/// CVE-2026-50019 (vazamento de cookie no downloader curl), CVE-2026-50023
+/// (escrita de `.desktop`/`.url`/`.webloc`) e CVE-2026-50574 (execução
+/// arbitrária via manifesto com aria2c).
+pub const MIN_YTDLP_VERSION: (u32, u32, u32) = (2026, 6, 9);
+
+/// yt-dlp versiona como `YYYY.MM.DD` com sufixo opcional (`.N`, `-nightly…`).
+/// Devolve `None` para qualquer coisa que não case com esse formato.
+pub fn parse_ytdlp_version(raw: &str) -> Option<(u32, u32, u32)> {
+ let head = raw.split_whitespace().next()?;
+ let core = head.split(['-', '+']).next()?;
+ let mut parts = core.split('.');
+ let year: u32 = parts.next()?.parse().ok()?;
+ let month: u32 = parts.next()?.parse().ok()?;
+ let day: u32 = parts.next()?.parse().ok()?;
+ if !(1..=12).contains(&month) || !(1..=31).contains(&day) || year < 2000 {
+ return None;
+ }
+ Some((year, month, day))
+}
+
+/// `None` quando a versão não pôde ser lida — nesse caso o chamador não deve
+/// afirmar que está desatualizada.
+pub fn ytdlp_version_is_supported(raw: &str) -> Option<bool> {
+ parse_ytdlp_version(raw).map(|v| v >= MIN_YTDLP_VERSION)
+}
+
+/// Argumentos que delegam o download ao aria2c **apenas** para os protocolos
+/// de `ARIA2C_ALLOWED_PROTOCOLS`. Manifesto fragmentado continua no downloader
+/// nativo (CVE-2026-50574).
+///
+/// O proxy é validado antes de entrar na string de `--downloader-args`: um
+/// espaço ali viraria argumento extra do aria2c.
+pub(crate) fn aria2c_downloader_args(
+ aria2c_path: &str,
+ connections: u32,
+ proxy: Option<&str>,
+) -> Vec<String> {
+ let conns = connections.max(1);
+ let proxy_arg = match proxy.map(str::trim).filter(|p| !p.is_empty()) {
+ Some(p) if !p.contains(char::is_whitespace) => format!(" --all-proxy={}", p),
+ Some(_) => {
+ tracing::warn!("[aria2c] proxy com espaço ignorado no --downloader-args");
+ String::new()
+ }
+ None => String::new(),
+ };
+ vec![
+ "--downloader".to_string(),
+ format!("{}:{}", ARIA2C_ALLOWED_PROTOCOLS, aria2c_path),
+ "--downloader-args".to_string(),
+ format!(
+ "aria2c:-x {conns} -k 1M -j {conns} --min-split-size=1M \
+ --file-allocation=none --optimize-concurrent-downloads=true \
+ --auto-file-renaming=false --summary-interval=1 \
+ --console-log-level=notice{proxy_arg}"
+ ),
+ ]
+}
+
pub fn set_ext_cookie_path_fn(f: impl Fn() -> PathBuf + Send + Sync + 'static) {
let _ = EXT_COOKIE_PATH_FN.set(Box::new(f));
}
@@ -258,6 +325,20 @@ fn speed_limit_value() -> Option<String> {
SPEED_LIMIT_FN.get().and_then(|f| f())
}
+pub fn set_insecure_tls_fn(f: impl Fn() -> bool + Send + Sync + 'static) {
+ let _ = INSECURE_TLS_FN.set(Box::new(f));
+}
+
+/// Verificar certificado é o default. `Vec` vazio quando ligado, para o
+/// chamador poder simplesmente estender a lista de argumentos.
+pub fn insecure_tls_args() -> Vec<String> {
+ if INSECURE_TLS_FN.get().map(|f| f()).unwrap_or(false) {
+ vec!["--no-check-certificates".to_string()]
+ } else {
+ Vec::new()
+ }
+}
+
pub fn set_live_from_start_fn(f: impl Fn() -> bool + Send + Sync + 'static) {
let _ = LIVE_FROM_START_FN.set(Box::new(f));
}
@@ -906,30 +987,8 @@ fn ytdlp_release_base(channel: YtdlpChannel) -> &'static str {
}
}
-/// Finds the expected sha256 (lowercased hex) for `asset` in a yt-dlp
-/// `SHA2-256SUMS` file. Lines are `"<64-hex> <filename>"`.
-fn parse_sha256sums(text: &str, asset: &str) -> Option<String> {
- for line in text.lines() {
- let mut parts = line.split_whitespace();
- let hash = parts.next()?;
- let name = parts.next()?;
- if name == asset && hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) {
- return Some(hash.to_lowercase());
- }
- }
- None
-}
+use crate::core::dependencies::integrity;
-fn sha256_hex(bytes: &[u8]) -> String {
- use sha2::{Digest, Sha256};
- let mut hasher = Sha256::new();
- hasher.update(bytes);
- hasher
- .finalize()
- .iter()
- .map(|b| format!("{:02x}", b))
- .collect()
-}
async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
let target =
@@ -963,29 +1022,13 @@ async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
// Verify against the release's published checksums. Fail closed on a
// mismatch; fail open only when the sums file itself can't be fetched, so
// a transient GitHub hiccup doesn't block downloads entirely.
- match client.get(&sums_url).send().await {
- Ok(r) if r.status().is_success() => {
- let sums = r.text().await.unwrap_or_default();
- match parse_sha256sums(&sums, asset) {
- Some(expected) => {
- let actual = sha256_hex(&bytes);
- if actual != expected {
- return Err(anyhow!(
- "yt-dlp checksum mismatch (expected {}, got {}) — refusing to install",
- expected,
- actual
- ));
- }
- tracing::info!("[ytdlp] sha256 verified ({:?} channel)", channel);
- }
- None => tracing::warn!(
- "[ytdlp] {} not listed in SHA2-256SUMS — skipping verification",
- asset
- ),
- }
- }
- _ => tracing::warn!("[ytdlp] could not fetch SHA2-256SUMS — skipping verification"),
- }
+ // Fail-closed. O yt-dlp publica `SHA2-256SUMS` em toda release; não
+ // conseguir buscá-lo é indistinguível de alguém suprimindo a verificação,
+ // então o binário é descartado em vez de instalado sem conferência.
+ let expected = integrity::expected_from_sums_url(&client, &sums_url, asset)
+ .await
+ .map_err(|e| anyhow!("yt-dlp: verificacao de integridade impossivel — {}", e))?;
+ integrity::verify_sha256(&bytes, &expected, &format!("yt-dlp ({:?})", channel))?;
let temp = target.with_file_name(format!(
"{}.new",
@@ -1294,7 +1337,6 @@ pub async fn get_video_info(
"--dump-single-json".to_string(),
"--no-warnings".to_string(),
"--no-playlist".to_string(),
- "--no-check-certificates".to_string(),
"--encoding".to_string(),
"utf-8".to_string(),
"--socket-timeout".to_string(),
@@ -2159,6 +2201,13 @@ pub async fn download_video(
base_args.push(loc.clone());
}
+ // `-N` e `--concurrent-fragments` são a mesma opção do yt-dlp. Empurrar as
+ // duas fazia a segunda vencer no argparse e anular o freio de 429 abaixo.
+ let requested_fragments = if concurrent_fragments == 0 {
+ concurrent_fragments_value()
+ } else {
+ concurrent_fragments
+ };
let effective_fragments = if is_youtube_url(url) {
let rate_limit_count = rate_limit_429_count();
let max_frags = if rate_limit_count >= 2 {
@@ -2168,12 +2217,12 @@ pub async fn download_video(
} else {
8
};
- concurrent_fragments.min(max_frags)
+ requested_fragments.min(max_frags)
} else {
- concurrent_fragments
+ requested_fragments
};
base_args.push("-N".to_string());
- base_args.push(effective_fragments.to_string());
+ base_args.push(effective_fragments.max(1).to_string());
if is_youtube_url(url) {
base_args.push("--extractor-args".to_string());
@@ -2201,8 +2250,8 @@ pub async fn download_video(
let effective_ua = ext_user_agent_for_url(url)
.or_else(user_agent_setting)
.unwrap_or_else(|| CHROME_UA.to_string());
+ base_args.extend(insecure_tls_args());
base_args.extend([
- "--no-check-certificate".to_string(),
"--no-warnings".to_string(),
"--no-mtime".to_string(),
"--user-agent".to_string(),
@@ -2273,12 +2322,6 @@ pub async fn download_video(
base_args.push(rate);
}
- let frag_count = concurrent_fragments_value();
- if frag_count > 1 {
- base_args.push("--concurrent-fragments".to_string());
- base_args.push(frag_count.to_string());
- }
-
if live_from_start_enabled() {
base_args.push("--live-from-start".to_string());
base_args.push("--no-part".to_string());
@@ -2392,14 +2435,15 @@ pub async fn download_video(
} else {
effective_fragments.clamp(8, 16)
};
- args.push("--downloader".to_string());
- args.push(a2_path.to_string_lossy().to_string());
- args.push("--downloader-args".to_string());
- let aria2c_proxy = match crate::core::http_client::proxy_url() {
- Some(url) => format!(" --all-proxy={}", url),
- None => String::new(),
- };
- args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=1 --console-log-level=notice{}", conns, conns, aria2c_proxy));
+ // CVE-2026-50574: entregar manifesto (m3u8/dash) ao aria2c
+ // permite escrita arbitrária de arquivo. O yt-dlp 2026.06.09
+ // removeu o suporte; aqui o downloader externo fica restrito a
+ // http/ftp e fragmento vai pelo nativo com `-N`.
+ args.extend(aria2c_downloader_args(
+ &a2_path.to_string_lossy(),
+ conns,
+ crate::core::http_client::proxy_url().as_deref(),
+ ));
}
}
@@ -3560,22 +3604,22 @@ mod tests {
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\
1111111111111111111111111111111111111111111111111111111111111111 yt-dlp_macos\n";
assert_eq!(
- parse_sha256sums(sums, "yt-dlp.exe").as_deref(),
+ integrity::parse_sha256sums(sums, "yt-dlp.exe").as_deref(),
Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
);
assert_eq!(
- parse_sha256sums(sums, "yt-dlp_macos").as_deref(),
+ integrity::parse_sha256sums(sums, "yt-dlp_macos").as_deref(),
Some("1111111111111111111111111111111111111111111111111111111111111111")
);
- assert_eq!(parse_sha256sums(sums, "yt-dlp_missing"), None);
- assert_eq!(parse_sha256sums("garbage line", "yt-dlp"), None);
+ assert_eq!(integrity::parse_sha256sums(sums, "yt-dlp_missing"), None);
+ assert_eq!(integrity::parse_sha256sums("garbage line", "yt-dlp"), None);
}
#[test]
fn sha256_hex_known_vector() {
// SHA-256 of the empty input.
assert_eq!(
- sha256_hex(b""),
+ integrity::sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
@@ -3930,4 +3974,55 @@ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\
assert!(formats[0].has_video);
assert!(!formats[0].has_audio);
}
+
+ // --- Regressao de seguranca: CVE-2026-50574 (aria2c + manifesto) ---
+
+ #[test]
+ fn aria2c_nunca_recebe_manifesto_fragmentado() {
+ let args = aria2c_downloader_args("/opt/bin/aria2c", 8, None);
+ let downloader = &args[1];
+ assert!(downloader.starts_with("http,ftp:"), "{downloader}");
+ for proto in ["m3u8", "m3u8_native", "m3u8_frag_urls", "dash_frag_urls"] {
+ assert!(!downloader.contains(proto), "protocolo {proto} nao pode ir ao aria2c");
+ }
+ assert_eq!(downloader, "http,ftp:/opt/bin/aria2c");
+ // A chave de --downloader-args e o NOME do downloader, nao o protocolo.
+ assert!(args[3].starts_with("aria2c:"), "{}", args[3]);
+ }
+
+ #[test]
+ fn aria2c_downloader_args_rejeita_proxy_com_espaco() {
+ let limpo = aria2c_downloader_args("/bin/aria2c", 2, Some("http://127.0.0.1:8080"));
+ assert!(limpo[3].ends_with("--all-proxy=http://127.0.0.1:8080"), "{}", limpo[3]);
+ let sujo = aria2c_downloader_args("/bin/aria2c", 2, Some("http://h:1 --seed-ratio=0"));
+ assert!(!sujo[3].contains("--all-proxy"), "{}", sujo[3]);
+ assert!(!sujo[3].contains("--seed-ratio"));
+ }
+
+ #[test]
+ fn aria2c_nunca_zera_conexoes() {
+ let args = aria2c_downloader_args("/bin/aria2c", 0, None);
+ assert!(args[3].contains("-x 1") && args[3].contains("-j 1"), "{}", args[3]);
+ }
+
+ // --- Piso de versao do yt-dlp ---
+
+ #[test]
+ fn parse_ytdlp_version_le_os_formatos_reais() {
+ assert_eq!(parse_ytdlp_version("2026.06.09"), Some((2026, 6, 9)));
+ assert_eq!(parse_ytdlp_version("2025.12.31.232815"), Some((2025, 12, 31)));
+ assert_eq!(parse_ytdlp_version("2026.06.10.232815-nightly"), Some((2026, 6, 10)));
+ for lixo in ["", "unknown", "1.2", "2026.13.01", "2026.06.99"] {
+ assert_eq!(parse_ytdlp_version(lixo), None, "aceitou {lixo:?}");
+ }
+ }
+
+ #[test]
+ fn piso_de_versao_cobre_as_cves_de_2026_06_09() {
+ assert_eq!(ytdlp_version_is_supported("2026.06.09"), Some(true));
+ assert_eq!(ytdlp_version_is_supported("2026.07.04"), Some(true));
+ assert_eq!(ytdlp_version_is_supported("2026.06.08"), Some(false));
+ // Versao ilegivel nao pode ser reportada como desatualizada.
+ assert_eq!(ytdlp_version_is_supported("sei la"), None);
+ }
}
diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rs
index e9656863..7d071569 100644
--- a/src-tauri/omniget-core/src/models/settings.rs
+++ b/src-tauri/omniget-core/src/models/settings.rs
@@ -1,603 +1,657 @@
-use serde::{Deserialize, Serialize};
-use std::path::PathBuf;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct AppSettings {
- pub schema_version: u32,
- pub appearance: AppearanceSettings,
- pub download: DownloadSettings,
- pub advanced: AdvancedSettings,
- #[serde(default)]
- pub telegram: TelegramSettings,
- #[serde(default)]
- pub proxy: ProxySettings,
- #[serde(default)]
- pub onboarding_completed: bool,
- #[serde(default, alias = "start_with_windows")]
- pub start_with_system: bool,
- #[serde(default)]
- pub start_minimized: bool,
- #[serde(default)]
- pub portable_mode: bool,
- #[serde(default)]
- pub legal_acknowledged: bool,
- #[serde(default)]
- pub last_download_options: LastDownloadOptions,
- #[serde(default)]
- pub typography: TypographySettings,
- #[serde(default)]
- pub rpc: RpcSettings,
- #[serde(default)]
- pub bridge: BridgeSettings,
- #[serde(default)]
- pub league: LeagueSettings,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct LeagueSettings {
- #[serde(default = "default_league_enabled")]
- pub enabled: bool,
- #[serde(default)]
- pub auto_accept: bool,
- #[serde(default)]
- pub auto_pick: bool,
- #[serde(default)]
- pub auto_ban: bool,
- #[serde(default)]
- pub auto_lock: bool,
- #[serde(default)]
- pub auto_runes: bool,
- #[serde(default)]
- pub auto_honor: bool,
- #[serde(default)]
- pub auto_play_again: bool,
- #[serde(default)]
- pub auto_reconnect: bool,
- #[serde(default)]
- pub auto_trade: String,
- #[serde(default)]
- pub auto_message: String,
- #[serde(default)]
- pub pick_champions: Vec<i64>,
- #[serde(default)]
- pub ban_champions: Vec<i64>,
-}
-
-fn default_league_enabled() -> bool {
- true
-}
-
-impl Default for LeagueSettings {
- fn default() -> Self {
- Self {
- enabled: default_league_enabled(),
- auto_accept: false,
- auto_pick: false,
- auto_ban: false,
- auto_lock: false,
- auto_runes: false,
- auto_honor: false,
- auto_play_again: false,
- auto_reconnect: false,
- auto_trade: String::new(),
- auto_message: String::new(),
- pick_champions: Vec::new(),
- ban_champions: Vec::new(),
- }
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct RpcSettings {
- #[serde(default = "default_rpc_enabled")]
- pub enabled: bool,
- #[serde(default = "default_rpc_app_id")]
- pub app_id: String,
- #[serde(default = "default_rpc_image_key")]
- pub large_image_key: String,
-}
-
-impl Default for RpcSettings {
- fn default() -> Self {
- Self {
- enabled: default_rpc_enabled(),
- app_id: default_rpc_app_id(),
- large_image_key: default_rpc_image_key(),
- }
- }
-}
-
-fn default_rpc_enabled() -> bool {
- true
-}
-
-fn default_rpc_app_id() -> String {
- "1502867748353478656".into()
-}
-
-fn default_rpc_image_key() -> String {
- "omniget_music".into()
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-pub struct LastDownloadOptions {
- #[serde(default)]
- pub mode: Option<String>,
- #[serde(default)]
- pub quality: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct AppearanceSettings {
- pub theme: String,
- pub language: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct DownloadSettings {
- pub default_output_dir: PathBuf,
- pub always_ask_path: bool,
- pub video_quality: String,
- pub skip_existing: bool,
- pub download_attachments: bool,
- pub download_descriptions: bool,
- #[serde(default = "default_true")]
- pub embed_metadata: bool,
- #[serde(default = "default_true")]
- pub embed_thumbnail: bool,
- #[serde(default)]
- pub clipboard_detection: bool,
- #[serde(default)]
- pub auto_download_on_paste: bool,
- #[serde(default = "default_filename_template")]
- pub filename_template: String,
- #[serde(default)]
- pub organize_by_platform: bool,
- #[serde(default)]
- pub download_subtitles: bool,
- #[serde(default)]
- pub include_auto_subtitles: bool,
- #[serde(default = "default_caption_locale")]
- pub caption_locale: String,
- #[serde(default)]
- pub keep_vtt: bool,
- #[serde(default)]
- pub translate_metadata: bool,
- #[serde(default)]
- pub youtube_sponsorblock: bool,
- #[serde(default = "default_sponsorblock_mode")]
- pub sponsorblock_mode: String,
- #[serde(default = "default_sponsorblock_categories")]
- pub sponsorblock_categories: Vec<String>,
- #[serde(default)]
- pub split_by_chapters: bool,
- #[serde(default)]
- pub live_from_start: bool,
- #[serde(default)]
- pub speed_limit: String,
- #[serde(default)]
- pub hotkey_enabled: bool,
- #[serde(default = "default_hotkey_binding")]
- pub hotkey_binding: String,
- #[serde(default)]
- pub clip_hotkey_enabled: bool,
- #[serde(default = "default_clip_hotkey_binding")]
- pub clip_hotkey_binding: String,
- #[serde(default)]
- pub music_hotkey_enabled: bool,
- #[serde(default = "default_music_hotkey_binding")]
- pub music_hotkey_binding: String,
- #[serde(default = "default_music_audio_format")]
- pub music_audio_format: String,
- #[serde(default)]
- pub extra_ytdlp_flags: Vec<String>,
- #[serde(default = "default_true")]
- pub copy_to_clipboard_on_hotkey: bool,
- #[serde(default)]
- pub cookie_file: String,
- #[serde(default = "default_true")]
- pub always_use_managed_cookies: bool,
- #[serde(default)]
- pub continuous_lecture_numbers: bool,
- #[serde(default)]
- pub bilibili_danmaku_enabled: bool,
- #[serde(default = "default_bilibili_danmaku_format")]
- pub bilibili_danmaku_format: String,
- #[serde(default = "default_bilibili_container")]
- pub bilibili_container: String,
- #[serde(default)]
- pub bilibili_nfo_enabled: bool,
- #[serde(default)]
- pub bilibili_cover_sidecar: bool,
- #[serde(default = "default_bilibili_cover_format")]
- pub bilibili_cover_format: String,
- #[serde(default = "default_bilibili_naming_video")]
- pub bilibili_naming_video: String,
- #[serde(default = "default_bilibili_naming_multi_part")]
- pub bilibili_naming_multi_part: String,
- #[serde(default = "default_bilibili_naming_bangumi")]
- pub bilibili_naming_bangumi: String,
- #[serde(default = "default_bilibili_naming_cheese")]
- pub bilibili_naming_cheese: String,
- #[serde(default = "default_bilibili_naming_collection")]
- pub bilibili_naming_collection: String,
- #[serde(default)]
- pub bilibili_cdn_hosts: String,
- #[serde(default)]
- pub bilibili_cdn_prefer_alternatives: bool,
- #[serde(default = "default_bilibili_preferred_qn")]
- pub bilibili_preferred_qn: u32,
- #[serde(default = "default_bilibili_preferred_codec")]
- pub bilibili_preferred_codec: u32,
- #[serde(default = "default_bilibili_preferred_audio_qn")]
- pub bilibili_preferred_audio_qn: u32,
-}
-
-fn default_bilibili_preferred_qn() -> u32 {
- 200
-}
-
-fn default_bilibili_preferred_codec() -> u32 {
- 20
-}
-
-fn default_bilibili_preferred_audio_qn() -> u32 {
- 30300
-}
-
-fn default_bilibili_cover_format() -> String {
- "jpg".to_string()
-}
-
-fn default_bilibili_naming_video() -> String {
- "{title}".to_string()
-}
-
-fn default_bilibili_naming_multi_part() -> String {
- "{parent_title}/P{page} - {leaf_title}".to_string()
-}
-
-fn default_bilibili_naming_bangumi() -> String {
- "{series_title}/Season {season_number}/{episode_number_pad2} - {episode_title}".to_string()
-}
-
-fn default_bilibili_naming_cheese() -> String {
- "{series_title}/{section_title}/{episode_number_pad2} - {episode_title}".to_string()
-}
-
-fn default_bilibili_naming_collection() -> String {
- "{collection_title}/{title}".to_string()
-}
-
-fn default_bilibili_danmaku_format() -> String {
- "xml".to_string()
-}
-
-fn default_bilibili_container() -> String {
- "mp4".to_string()
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct AdvancedSettings {
- pub max_concurrent_segments: u32,
- pub max_retries: u32,
- #[serde(default = "default_max_concurrent_downloads")]
- pub max_concurrent_downloads: u32,
- #[serde(default = "default_concurrent_fragments")]
- pub concurrent_fragments: u32,
- #[serde(default = "default_stagger_delay_ms")]
- pub stagger_delay_ms: u64,
- #[serde(default = "default_torrent_listen_port")]
- pub torrent_listen_port: u16,
- #[serde(default = "default_torrent_auto_trackers")]
- pub torrent_auto_trackers: bool,
- #[serde(default = "default_torrent_upnp")]
- pub torrent_upnp: bool,
- #[serde(default = "default_prevent_sleep")]
- pub prevent_sleep: bool,
- #[serde(default)]
- pub cookies_from_browser: String,
- #[serde(default)]
- pub twitter_manual_cookie: String,
- #[serde(default)]
- pub user_agent: String,
-}
-
-fn default_concurrent_fragments() -> u32 {
- 8
-}
-
-fn default_sponsorblock_mode() -> String {
- "remove".to_string()
-}
-
-fn default_sponsorblock_categories() -> Vec<String> {
- vec![
- "sponsor".to_string(),
- "selfpromo".to_string(),
- "interaction".to_string(),
- ]
-}
-
-fn default_max_concurrent_downloads() -> u32 {
- 2
-}
-
-fn default_stagger_delay_ms() -> u64 {
- 150
-}
-
-fn default_torrent_auto_trackers() -> bool {
- true
-}
-
-fn default_torrent_upnp() -> bool {
- true
-}
-
-fn default_prevent_sleep() -> bool {
- true
-}
-
-fn default_torrent_listen_port() -> u16 {
- 6881
-}
-
-fn default_true() -> bool {
- true
-}
-
-pub fn default_filename_template() -> String {
- "%(title).200s [%(id)s].%(ext)s".into()
-}
-
-fn default_hotkey_binding() -> String {
- "CmdOrCtrl+Shift+D".into()
-}
-
-fn default_clip_hotkey_binding() -> String {
- "CmdOrCtrl+Shift+B".into()
-}
-
-fn default_music_hotkey_binding() -> String {
- "CmdOrCtrl+Shift+M".into()
-}
-
-fn default_music_audio_format() -> String {
- "m4a".into()
-}
-
-fn default_caption_locale() -> String {
- "en".into()
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TelegramSettings {
- pub concurrent_downloads: u32,
- pub fix_file_extensions: bool,
-}
-
-impl Default for TelegramSettings {
- fn default() -> Self {
- Self {
- concurrent_downloads: 3,
- fix_file_extensions: true,
- }
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ProxySettings {
- #[serde(default)]
- pub enabled: bool,
- #[serde(default = "default_proxy_type")]
- pub proxy_type: String,
- #[serde(default)]
- pub host: String,
- #[serde(default = "default_proxy_port")]
- pub port: u16,
- #[serde(default)]
- pub username: String,
- #[serde(default)]
- pub password: String,
-}
-
-impl Default for ProxySettings {
- fn default() -> Self {
- Self {
- enabled: false,
- proxy_type: default_proxy_type(),
- host: String::new(),
- port: default_proxy_port(),
- username: String::new(),
- password: String::new(),
- }
- }
-}
-
-fn default_proxy_type() -> String {
- "http".into()
-}
-
-fn default_proxy_port() -> u16 {
- 8080
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TypographySettings {
- #[serde(default = "default_font_display")]
- pub font_display: String,
- #[serde(default = "default_font_body")]
- pub font_body: String,
- #[serde(default = "default_font_mono")]
- pub font_mono: String,
- #[serde(default = "default_line_height_base")]
- pub line_height_base: f32,
- #[serde(default = "default_spacing_scale")]
- pub spacing_scale: f32,
- #[serde(default)]
- pub preset_name: Option<String>,
-}
-
-fn default_font_display() -> String {
- "Bricolage Grotesque Variable".into()
-}
-
-fn default_font_body() -> String {
- "Inter".into()
-}
-
-fn default_font_mono() -> String {
- "IBM Plex Mono".into()
-}
-
-fn default_line_height_base() -> f32 {
- 1.55
-}
-
-fn default_spacing_scale() -> f32 {
- 1.0
-}
-
-/// Local HTTP bridge that lets the browser extension talk to the desktop app
-/// without depending on a Chrome native-messaging manifest (which would
-/// otherwise force us to maintain an explicit allowlist of extension IDs).
-///
-/// The token is generated lazily on first launch and shown in the app
-/// Settings; the user pastes it into the extension's options page once,
-/// after which the extension authenticates each request with
-/// `Authorization: Bearer <token>`.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct BridgeSettings {
- #[serde(default = "default_bridge_enabled")]
- pub enabled: bool,
- /// Bound port on `127.0.0.1`. `0` means "pick at startup, then persist".
- #[serde(default)]
- pub port: u16,
- /// Random token used to authenticate extension requests.
- /// Empty means "regenerate on next launch".
- #[serde(default)]
- pub token: String,
-}
-
-impl Default for BridgeSettings {
- fn default() -> Self {
- Self {
- enabled: default_bridge_enabled(),
- port: 0,
- token: String::new(),
- }
- }
-}
-
-fn default_bridge_enabled() -> bool {
- true
-}
-
-impl Default for TypographySettings {
- fn default() -> Self {
- Self {
- font_display: default_font_display(),
- font_body: default_font_body(),
- font_mono: default_font_mono(),
- line_height_base: default_line_height_base(),
- spacing_scale: default_spacing_scale(),
- preset_name: Some("omniget-default".into()),
- }
- }
-}
-
-impl Default for AppSettings {
- fn default() -> Self {
- Self {
- schema_version: 1,
- appearance: AppearanceSettings {
- theme: "system".into(),
- language: "en".into(),
- },
- download: DownloadSettings {
- default_output_dir: dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")),
- always_ask_path: false,
- video_quality: "720p".into(),
- skip_existing: true,
- download_attachments: true,
- download_descriptions: true,
- embed_metadata: true,
- embed_thumbnail: true,
- clipboard_detection: false,
- auto_download_on_paste: false,
- filename_template: default_filename_template(),
- organize_by_platform: false,
- download_subtitles: false,
- include_auto_subtitles: false,
- caption_locale: default_caption_locale(),
- keep_vtt: false,
- translate_metadata: false,
- youtube_sponsorblock: false,
- sponsorblock_mode: "remove".to_string(),
- sponsorblock_categories: vec![
- "sponsor".to_string(),
- "selfpromo".to_string(),
- "interaction".to_string(),
- ],
- split_by_chapters: false,
- live_from_start: false,
- speed_limit: String::new(),
- hotkey_enabled: false,
- hotkey_binding: default_hotkey_binding(),
- clip_hotkey_enabled: false,
- clip_hotkey_binding: default_clip_hotkey_binding(),
- music_hotkey_enabled: false,
- music_hotkey_binding: default_music_hotkey_binding(),
- music_audio_format: default_music_audio_format(),
- extra_ytdlp_flags: Vec::new(),
- copy_to_clipboard_on_hotkey: true,
- cookie_file: String::new(),
- always_use_managed_cookies: true,
- continuous_lecture_numbers: false,
- bilibili_danmaku_enabled: false,
- bilibili_danmaku_format: "xml".into(),
- bilibili_container: "mp4".into(),
- bilibili_nfo_enabled: false,
- bilibili_cover_sidecar: false,
- bilibili_cover_format: "jpg".into(),
- bilibili_naming_video: default_bilibili_naming_video(),
- bilibili_naming_multi_part: default_bilibili_naming_multi_part(),
- bilibili_naming_bangumi: default_bilibili_naming_bangumi(),
- bilibili_naming_cheese: default_bilibili_naming_cheese(),
- bilibili_naming_collection: default_bilibili_naming_collection(),
- bilibili_cdn_hosts: String::new(),
- bilibili_cdn_prefer_alternatives: false,
- bilibili_preferred_qn: default_bilibili_preferred_qn(),
- bilibili_preferred_codec: default_bilibili_preferred_codec(),
- bilibili_preferred_audio_qn: default_bilibili_preferred_audio_qn(),
- },
- advanced: AdvancedSettings {
- max_concurrent_segments: 20,
- max_retries: 3,
- max_concurrent_downloads: 2,
- concurrent_fragments: 8,
- stagger_delay_ms: 150,
- torrent_listen_port: 6881,
- torrent_auto_trackers: true,
- torrent_upnp: true,
- prevent_sleep: true,
- cookies_from_browser: String::new(),
- twitter_manual_cookie: String::new(),
- user_agent: String::new(),
- },
- telegram: TelegramSettings::default(),
- proxy: ProxySettings::default(),
- onboarding_completed: false,
- start_with_system: false,
- start_minimized: false,
- portable_mode: false,
- legal_acknowledged: false,
- last_download_options: LastDownloadOptions::default(),
- typography: TypographySettings::default(),
- rpc: RpcSettings::default(),
- bridge: BridgeSettings::default(),
- league: LeagueSettings::default(),
- }
- }
-}
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AppSettings {
+ pub schema_version: u32,
+ pub appearance: AppearanceSettings,
+ pub download: DownloadSettings,
+ pub advanced: AdvancedSettings,
+ #[serde(default)]
+ pub telegram: TelegramSettings,
+ #[serde(default)]
+ pub proxy: ProxySettings,
+ #[serde(default)]
+ pub onboarding_completed: bool,
+ #[serde(default, alias = "start_with_windows")]
+ pub start_with_system: bool,
+ #[serde(default)]
+ pub start_minimized: bool,
+ #[serde(default)]
+ pub portable_mode: bool,
+ #[serde(default)]
+ pub legal_acknowledged: bool,
+ #[serde(default)]
+ pub last_download_options: LastDownloadOptions,
+ #[serde(default)]
+ pub typography: TypographySettings,
+ #[serde(default)]
+ pub rpc: RpcSettings,
+ #[serde(default)]
+ pub bridge: BridgeSettings,
+ #[serde(default)]
+ pub league: LeagueSettings,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LeagueSettings {
+ #[serde(default = "default_league_enabled")]
+ pub enabled: bool,
+ #[serde(default)]
+ pub auto_accept: bool,
+ #[serde(default)]
+ pub auto_pick: bool,
+ #[serde(default)]
+ pub auto_ban: bool,
+ #[serde(default)]
+ pub auto_lock: bool,
+ #[serde(default)]
+ pub auto_runes: bool,
+ #[serde(default)]
+ pub auto_honor: bool,
+ #[serde(default)]
+ pub auto_play_again: bool,
+ #[serde(default)]
+ pub auto_reconnect: bool,
+ #[serde(default)]
+ pub auto_trade: String,
+ #[serde(default)]
+ pub auto_message: String,
+ #[serde(default)]
+ pub pick_champions: Vec<i64>,
+ #[serde(default)]
+ pub ban_champions: Vec<i64>,
+}
+
+fn default_league_enabled() -> bool {
+ true
+}
+
+impl Default for LeagueSettings {
+ fn default() -> Self {
+ Self {
+ enabled: default_league_enabled(),
+ auto_accept: false,
+ auto_pick: false,
+ auto_ban: false,
+ auto_lock: false,
+ auto_runes: false,
+ auto_honor: false,
+ auto_play_again: false,
+ auto_reconnect: false,
+ auto_trade: String::new(),
+ auto_message: String::new(),
+ pick_champions: Vec::new(),
+ ban_champions: Vec::new(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RpcSettings {
+ #[serde(default = "default_rpc_enabled")]
+ pub enabled: bool,
+ #[serde(default = "default_rpc_app_id")]
+ pub app_id: String,
+ #[serde(default = "default_rpc_image_key")]
+ pub large_image_key: String,
+}
+
+impl Default for RpcSettings {
+ fn default() -> Self {
+ Self {
+ enabled: default_rpc_enabled(),
+ app_id: default_rpc_app_id(),
+ large_image_key: default_rpc_image_key(),
+ }
+ }
+}
+
+fn default_rpc_enabled() -> bool {
+ true
+}
+
+fn default_rpc_app_id() -> String {
+ "1502867748353478656".into()
+}
+
+fn default_rpc_image_key() -> String {
+ "omniget_music".into()
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct LastDownloadOptions {
+ #[serde(default)]
+ pub mode: Option<String>,
+ #[serde(default)]
+ pub quality: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AppearanceSettings {
+ pub theme: String,
+ pub language: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DownloadSettings {
+ pub default_output_dir: PathBuf,
+ pub always_ask_path: bool,
+ pub video_quality: String,
+ pub skip_existing: bool,
+ pub download_attachments: bool,
+ pub download_descriptions: bool,
+ #[serde(default = "default_true")]
+ pub embed_metadata: bool,
+ #[serde(default = "default_true")]
+ pub embed_thumbnail: bool,
+ #[serde(default)]
+ pub clipboard_detection: bool,
+ #[serde(default)]
+ pub auto_download_on_paste: bool,
+ #[serde(default = "default_filename_template")]
+ pub filename_template: String,
+ #[serde(default)]
+ pub organize_by_platform: bool,
+ #[serde(default)]
+ pub download_subtitles: bool,
+ #[serde(default)]
+ pub include_auto_subtitles: bool,
+ #[serde(default = "default_caption_locale")]
+ pub caption_locale: String,
+ #[serde(default)]
+ pub keep_vtt: bool,
+ #[serde(default)]
+ pub translate_metadata: bool,
+ #[serde(default)]
+ pub youtube_sponsorblock: bool,
+ #[serde(default = "default_sponsorblock_mode")]
+ pub sponsorblock_mode: String,
+ #[serde(default = "default_sponsorblock_categories")]
+ pub sponsorblock_categories: Vec<String>,
+ #[serde(default)]
+ pub split_by_chapters: bool,
+ #[serde(default)]
+ pub live_from_start: bool,
+ #[serde(default)]
+ pub speed_limit: String,
+ #[serde(default)]
+ pub hotkey_enabled: bool,
+ #[serde(default = "default_hotkey_binding")]
+ pub hotkey_binding: String,
+ #[serde(default)]
+ pub clip_hotkey_enabled: bool,
+ #[serde(default = "default_clip_hotkey_binding")]
+ pub clip_hotkey_binding: String,
+ #[serde(default)]
+ pub music_hotkey_enabled: bool,
+ #[serde(default = "default_music_hotkey_binding")]
+ pub music_hotkey_binding: String,
+ #[serde(default = "default_music_audio_format")]
+ pub music_audio_format: String,
+ #[serde(default)]
+ pub extra_ytdlp_flags: Vec<String>,
+ #[serde(default = "default_true")]
+ pub copy_to_clipboard_on_hotkey: bool,
+ #[serde(default)]
+ pub cookie_file: String,
+ #[serde(default = "default_true")]
+ pub always_use_managed_cookies: bool,
+ #[serde(default)]
+ pub continuous_lecture_numbers: bool,
+ #[serde(default)]
+ pub bilibili_danmaku_enabled: bool,
+ #[serde(default = "default_bilibili_danmaku_format")]
+ pub bilibili_danmaku_format: String,
+ #[serde(default = "default_bilibili_container")]
+ pub bilibili_container: String,
+ #[serde(default)]
+ pub bilibili_nfo_enabled: bool,
+ #[serde(default)]
+ pub bilibili_cover_sidecar: bool,
+ #[serde(default = "default_bilibili_cover_format")]
+ pub bilibili_cover_format: String,
+ #[serde(default = "default_bilibili_naming_video")]
+ pub bilibili_naming_video: String,
+ #[serde(default = "default_bilibili_naming_multi_part")]
+ pub bilibili_naming_multi_part: String,
+ #[serde(default = "default_bilibili_naming_bangumi")]
+ pub bilibili_naming_bangumi: String,
+ #[serde(default = "default_bilibili_naming_cheese")]
+ pub bilibili_naming_cheese: String,
+ #[serde(default = "default_bilibili_naming_collection")]
+ pub bilibili_naming_collection: String,
+ #[serde(default)]
+ pub bilibili_cdn_hosts: String,
+ #[serde(default)]
+ pub bilibili_cdn_prefer_alternatives: bool,
+ #[serde(default = "default_bilibili_preferred_qn")]
+ pub bilibili_preferred_qn: u32,
+ #[serde(default = "default_bilibili_preferred_codec")]
+ pub bilibili_preferred_codec: u32,
+ #[serde(default = "default_bilibili_preferred_audio_qn")]
+ pub bilibili_preferred_audio_qn: u32,
+}
+
+fn default_bilibili_preferred_qn() -> u32 {
+ 200
+}
+
+fn default_bilibili_preferred_codec() -> u32 {
+ 20
+}
+
+fn default_bilibili_preferred_audio_qn() -> u32 {
+ 30300
+}
+
+fn default_bilibili_cover_format() -> String {
+ "jpg".to_string()
+}
+
+fn default_bilibili_naming_video() -> String {
+ "{title}".to_string()
+}
+
+fn default_bilibili_naming_multi_part() -> String {
+ "{parent_title}/P{page} - {leaf_title}".to_string()
+}
+
+fn default_bilibili_naming_bangumi() -> String {
+ "{series_title}/Season {season_number}/{episode_number_pad2} - {episode_title}".to_string()
+}
+
+fn default_bilibili_naming_cheese() -> String {
+ "{series_title}/{section_title}/{episode_number_pad2} - {episode_title}".to_string()
+}
+
+fn default_bilibili_naming_collection() -> String {
+ "{collection_title}/{title}".to_string()
+}
+
+fn default_bilibili_danmaku_format() -> String {
+ "xml".to_string()
+}
+
+fn default_bilibili_container() -> String {
+ "mp4".to_string()
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AdvancedSettings {
+ pub max_concurrent_segments: u32,
+ pub max_retries: u32,
+ #[serde(default = "default_max_concurrent_downloads")]
+ pub max_concurrent_downloads: u32,
+ #[serde(default = "default_concurrent_fragments")]
+ pub concurrent_fragments: u32,
+ #[serde(default = "default_stagger_delay_ms")]
+ pub stagger_delay_ms: u64,
+ #[serde(default = "default_torrent_listen_port")]
+ pub torrent_listen_port: u16,
+ #[serde(default = "default_torrent_auto_trackers")]
+ pub torrent_auto_trackers: bool,
+ #[serde(default = "default_torrent_upnp")]
+ pub torrent_upnp: bool,
+ #[serde(default = "default_prevent_sleep")]
+ pub prevent_sleep: bool,
+ #[serde(default)]
+ pub cookies_from_browser: String,
+ #[serde(default)]
+ pub twitter_manual_cookie: String,
+ #[serde(default)]
+ pub user_agent: String,
+ /// Desliga a verificação de certificado TLS do yt-dlp. Default `false`:
+ /// só existe para rede corporativa com TLS interceptado.
+ #[serde(default)]
+ pub insecure_tls: bool,
+}
+
+fn default_concurrent_fragments() -> u32 {
+ 8
+}
+
+fn default_sponsorblock_mode() -> String {
+ "remove".to_string()
+}
+
+fn default_sponsorblock_categories() -> Vec<String> {
+ vec![
+ "sponsor".to_string(),
+ "selfpromo".to_string(),
+ "interaction".to_string(),
+ ]
+}
+
+fn default_max_concurrent_downloads() -> u32 {
+ 2
+}
+
+fn default_stagger_delay_ms() -> u64 {
+ 150
+}
+
+fn default_torrent_auto_trackers() -> bool {
+ true
+}
+
+fn default_torrent_upnp() -> bool {
+ true
+}
+
+fn default_prevent_sleep() -> bool {
+ true
+}
+
+fn default_torrent_listen_port() -> u16 {
+ 6881
+}
+
+fn default_true() -> bool {
+ true
+}
+
+pub fn default_filename_template() -> String {
+ "%(title).200s [%(id)s].%(ext)s".into()
+}
+
+fn default_hotkey_binding() -> String {
+ "CmdOrCtrl+Shift+D".into()
+}
+
+fn default_clip_hotkey_binding() -> String {
+ "CmdOrCtrl+Shift+B".into()
+}
+
+fn default_music_hotkey_binding() -> String {
+ "CmdOrCtrl+Shift+M".into()
+}
+
+fn default_music_audio_format() -> String {
+ "m4a".into()
+}
+
+fn default_caption_locale() -> String {
+ "en".into()
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TelegramSettings {
+ pub concurrent_downloads: u32,
+ pub fix_file_extensions: bool,
+}
+
+impl Default for TelegramSettings {
+ fn default() -> Self {
+ Self {
+ concurrent_downloads: 3,
+ fix_file_extensions: true,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProxySettings {
+ #[serde(default)]
+ pub enabled: bool,
+ #[serde(default = "default_proxy_type")]
+ pub proxy_type: String,
+ #[serde(default)]
+ pub host: String,
+ #[serde(default = "default_proxy_port")]
+ pub port: u16,
+ #[serde(default)]
+ pub username: String,
+ #[serde(default)]
+ pub password: String,
+}
+
+impl Default for ProxySettings {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ proxy_type: default_proxy_type(),
+ host: String::new(),
+ port: default_proxy_port(),
+ username: String::new(),
+ password: String::new(),
+ }
+ }
+}
+
+fn default_proxy_type() -> String {
+ "http".into()
+}
+
+fn default_proxy_port() -> u16 {
+ 8080
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TypographySettings {
+ #[serde(default = "default_font_display")]
+ pub font_display: String,
+ #[serde(default = "default_font_body")]
+ pub font_body: String,
+ #[serde(default = "default_font_mono")]
+ pub font_mono: String,
+ #[serde(default = "default_line_height_base")]
+ pub line_height_base: f32,
+ #[serde(default = "default_spacing_scale")]
+ pub spacing_scale: f32,
+ #[serde(default)]
+ pub preset_name: Option<String>,
+}
+
+fn default_font_display() -> String {
+ "Bricolage Grotesque Variable".into()
+}
+
+fn default_font_body() -> String {
+ "Inter".into()
+}
+
+fn default_font_mono() -> String {
+ "IBM Plex Mono".into()
+}
+
+fn default_line_height_base() -> f32 {
+ 1.55
+}
+
+fn default_spacing_scale() -> f32 {
+ 1.0
+}
+
+/// Local HTTP bridge that lets the browser extension talk to the desktop app
+/// without depending on a Chrome native-messaging manifest (which would
+/// otherwise force us to maintain an explicit allowlist of extension IDs).
+///
+/// The token is generated lazily on first launch and shown in the app
+/// Settings; the user pastes it into the extension's options page once,
+/// after which the extension authenticates each request with
+/// `Authorization: Bearer <token>`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BridgeSettings {
+ #[serde(default = "default_bridge_enabled")]
+ pub enabled: bool,
+ /// Bound port on `127.0.0.1`. `0` means "pick at startup, then persist".
+ #[serde(default)]
+ pub port: u16,
+ /// Random token used to authenticate extension requests.
+ /// Empty means "regenerate on next launch".
+ #[serde(default)]
+ pub token: String,
+}
+
+impl Default for BridgeSettings {
+ fn default() -> Self {
+ Self {
+ enabled: default_bridge_enabled(),
+ port: 0,
+ token: String::new(),
+ }
+ }
+}
+
+fn default_bridge_enabled() -> bool {
+ true
+}
+
+impl Default for TypographySettings {
+ fn default() -> Self {
+ Self {
+ font_display: default_font_display(),
+ font_body: default_font_body(),
+ font_mono: default_font_mono(),
+ line_height_base: default_line_height_base(),
+ spacing_scale: default_spacing_scale(),
+ preset_name: Some("omniget-default".into()),
+ }
+ }
+}
+
+impl Default for AppSettings {
+ fn default() -> Self {
+ Self {
+ schema_version: 1,
+ appearance: AppearanceSettings {
+ theme: "system".into(),
+ language: "en".into(),
+ },
+ download: DownloadSettings {
+ default_output_dir: dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")),
+ always_ask_path: false,
+ video_quality: "720p".into(),
+ skip_existing: true,
+ download_attachments: true,
+ download_descriptions: true,
+ embed_metadata: true,
+ embed_thumbnail: true,
+ clipboard_detection: false,
+ auto_download_on_paste: false,
+ filename_template: default_filename_template(),
+ organize_by_platform: false,
+ download_subtitles: false,
+ include_auto_subtitles: false,
+ caption_locale: default_caption_locale(),
+ keep_vtt: false,
+ translate_metadata: false,
+ youtube_sponsorblock: false,
+ sponsorblock_mode: "remove".to_string(),
+ sponsorblock_categories: vec![
+ "sponsor".to_string(),
+ "selfpromo".to_string(),
+ "interaction".to_string(),
+ ],
+ split_by_chapters: false,
+ live_from_start: false,
+ speed_limit: String::new(),
+ hotkey_enabled: false,
+ hotkey_binding: default_hotkey_binding(),
+ clip_hotkey_enabled: false,
+ clip_hotkey_binding: default_clip_hotkey_binding(),
+ music_hotkey_enabled: false,
+ music_hotkey_binding: default_music_hotkey_binding(),
+ music_audio_format: default_music_audio_format(),
+ extra_ytdlp_flags: Vec::new(),
+ copy_to_clipboard_on_hotkey: true,
+ cookie_file: String::new(),
+ always_use_managed_cookies: true,
+ continuous_lecture_numbers: false,
+ bilibili_danmaku_enabled: false,
+ bilibili_danmaku_format: "xml".into(),
+ bilibili_container: "mp4".into(),
+ bilibili_nfo_enabled: false,
+ bilibili_cover_sidecar: false,
+ bilibili_cover_format: "jpg".into(),
+ bilibili_naming_video: default_bilibili_naming_video(),
+ bilibili_naming_multi_part: default_bilibili_naming_multi_part(),
+ bilibili_naming_bangumi: default_bilibili_naming_bangumi(),
+ bilibili_naming_cheese: default_bilibili_naming_cheese(),
+ bilibili_naming_collection: default_bilibili_naming_collection(),
+ bilibili_cdn_hosts: String::new(),
+ bilibili_cdn_prefer_alternatives: false,
+ bilibili_preferred_qn: default_bilibili_preferred_qn(),
+ bilibili_preferred_codec: default_bilibili_preferred_codec(),
+ bilibili_preferred_audio_qn: default_bilibili_preferred_audio_qn(),
+ },
+ advanced: AdvancedSettings {
+ max_concurrent_segments: 20,
+ max_retries: 3,
+ max_concurrent_downloads: 2,
+ concurrent_fragments: 8,
+ stagger_delay_ms: 150,
+ torrent_listen_port: 6881,
+ torrent_auto_trackers: true,
+ torrent_upnp: true,
+ prevent_sleep: true,
+ cookies_from_browser: String::new(),
+ twitter_manual_cookie: String::new(),
+ user_agent: String::new(),
+ insecure_tls: false,
+ },
+ telegram: TelegramSettings::default(),
+ proxy: ProxySettings::default(),
+ onboarding_completed: false,
+ start_with_system: false,
+ start_minimized: false,
+ portable_mode: false,
+ legal_acknowledged: false,
+ last_download_options: LastDownloadOptions::default(),
+ typography: TypographySettings::default(),
+ rpc: RpcSettings::default(),
+ bridge: BridgeSettings::default(),
+ league: LeagueSettings::default(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod backcompat_tests {
+ use super::*;
+
+ #[test]
+ fn settings_da_v0_7_6_carregam_com_tls_verificado() {
+ // settings.json de uma instalacao 0.7.6, antes de `insecure_tls`
+ // existir. O campo ausente precisa virar `false` (certificado
+ // verificado) sem derrubar a desserializacao nem tocar em nenhuma
+ // outra preferencia de `advanced`. Essa e a categoria de bug que ja
+ // zerou as preferencias de usuarios neste projeto.
+ let json = serde_json::json!({
+ "max_concurrent_segments": 20,
+ "max_retries": 3,
+ "max_concurrent_downloads": 4,
+ "concurrent_fragments": 8,
+ "prevent_sleep": false,
+ "cookies_from_browser": "",
+ "twitter_manual_cookie": "",
+ "user_agent": "Mozilla/5.0 teste"
+ });
+ let parsed: AdvancedSettings =
+ serde_json::from_value(json).expect("settings antigo precisa desserializar");
+
+ assert!(
+ !parsed.insecure_tls,
+ "campo ausente precisa virar verificacao de certificado LIGADA"
+ );
+ assert_eq!(parsed.max_concurrent_downloads, 4);
+ assert_eq!(parsed.concurrent_fragments, 8);
+ assert!(!parsed.prevent_sleep);
+ assert_eq!(parsed.user_agent, "Mozilla/5.0 teste");
+ }
+
+ #[test]
+ fn insecure_tls_ligado_sobrevive_ao_round_trip() {
+ let json = serde_json::json!({
+ "max_concurrent_segments": 20,
+ "max_retries": 3,
+ "insecure_tls": true
+ });
+ let parsed: AdvancedSettings = serde_json::from_value(json).expect("desserializa");
+ assert!(parsed.insecure_tls);
+ let round = serde_json::to_value(&parsed).expect("serializa");
+ let back: AdvancedSettings = serde_json::from_value(round).expect("volta");
+ assert!(back.insecure_tls);
+ }
+}
diff --git a/src-tauri/src/commands/dependencies.rs b/src-tauri/src/commands/dependencies.rs
index 542ca2bd..038b3d3b 100644
--- a/src-tauri/src/commands/dependencies.rs
+++ b/src-tauri/src/commands/dependencies.rs
@@ -9,6 +9,9 @@ pub struct DependencyStatus {
pub name: String,
pub installed: bool,
pub version: Option<String>,
+ /// `true` só quando a versão foi lida **e** é anterior ao piso conhecido.
+ /// Versão ilegível não vira "desatualizado" — seria um alarme falso.
+ pub outdated: bool,
}
#[derive(Debug, Clone, Serialize)]
@@ -32,21 +35,30 @@ pub async fn check_dependencies() -> Result<Vec<DependencyStatus>, String> {
None
};
+ let ytdlp_outdated = ytdlp_version
+ .as_deref()
+ .and_then(crate::core::ytdlp::ytdlp_version_is_supported)
+ .map(|supported| !supported)
+ .unwrap_or(false);
+
Ok(vec![
DependencyStatus {
name: "yt-dlp".into(),
installed: ytdlp_version.is_some(),
version: ytdlp_version,
+ outdated: ytdlp_outdated,
},
DependencyStatus {
name: "FFmpeg".into(),
installed: ffmpeg_version.is_some(),
version: ffmpeg_version,
+ outdated: false,
},
DependencyStatus {
name: "PDFium".into(),
installed: pdfium_installed,
version: pdfium_version,
+ outdated: false,
},
])
}
diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rs
index ce14e1e7..4f4c36c2 100644
--- a/src-tauri/src/commands/search.rs
+++ b/src-tauri/src/commands/search.rs
@@ -31,16 +31,18 @@ pub async fn search_videos(
_ => format!("ytsearch{}:{}", n, query),
};
+ let mut args = vec![
+ "--flat-playlist".to_string(),
+ "--dump-json".to_string(),
+ "--no-warnings".to_string(),
+ "--socket-timeout".to_string(),
+ "15".to_string(),
+ ];
+ args.extend(omniget_core::core::ytdlp::insecure_tls_args());
+ args.push(search_query);
+
let output = crate::core::process::command(&ytdlp_path)
- .args([
- "--flat-playlist",
- "--dump-json",
- "--no-warnings",
- "--no-check-certificates",
- "--socket-timeout",
- "15",
- &search_query,
- ])
+ .args(&args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
diff --git a/src-tauri/src/commands/yt_templates.rs b/src-tauri/src/commands/yt_templates.rs
index 74ef3c8d..682013c6 100644
--- a/src-tauri/src/commands/yt_templates.rs
+++ b/src-tauri/src/commands/yt_templates.rs
@@ -25,13 +25,9 @@ fn templates_path() -> PathBuf {
}
fn load() -> YtTemplateStore {
- let path = templates_path();
- if !path.exists() {
- return YtTemplateStore::default();
- }
- fs::read_to_string(&path)
- .ok()
- .and_then(|s| serde_json::from_str(&s).ok())
+ // `load()` é seguido de `save()` nos comandos de escrita, então devolver
+ // default em cima de um arquivo corrompido apagaria os templates.
+ crate::core::state_file::load_or_quarantine(&templates_path(), "templates do yt-dlp")
.unwrap_or_default()
}
diff --git a/src-tauri/src/cookies/storage.rs b/src-tauri/src/cookies/storage.rs
index b957e6f5..b1052d54 100644
--- a/src-tauri/src/cookies/storage.rs
+++ b/src-tauri/src/cookies/storage.rs
@@ -106,12 +106,10 @@ fn safe_slug_segment(slug: &str) -> String {
}
pub fn load_registry() -> CookieRegistry {
- let path = meta_path();
- let content = match fs::read_to_string(&path) {
- Ok(c) => c,
- Err(_) => return CookieRegistry::default(),
- };
- serde_json::from_str(&content).unwrap_or_default()
+ // Registro ilegível vai para quarentena antes de virar default: sem isso o
+ // `save_registry` seguinte apagaria todas as contas de cookie do usuário.
+ crate::core::state_file::load_or_quarantine(&meta_path(), "registro de cookies")
+ .unwrap_or_default()
}
pub fn save_registry(registry: &CookieRegistry) -> anyhow::Result<()> {
diff --git a/src-tauri/src/core/channels.rs b/src-tauri/src/core/channels.rs
index fb3ec028..a07f3c42 100644
--- a/src-tauri/src/core/channels.rs
+++ b/src-tauri/src/core/channels.rs
@@ -79,15 +79,34 @@ fn row_to_channel(row: &rusqlite::Row) -> rusqlite::Result<ChannelFollow> {
let enabled: i64 = row.get(6)?;
let auto: i64 = row.get(7)?;
let interval: i64 = row.get(8)?;
+ let id: String = row.get(0)?;
+
+ // `seen_ids` ilegível não pode virar lista vazia em silêncio: o poller
+ // trataria todo vídeo já arquivado como novo e re-baixaria o canal
+ // inteiro. Sem saber o que já foi visto, o download automático fica
+ // desligado nesta leitura até o usuário reabilitar.
+ let (seen_ids, auto_download) = match serde_json::from_str::<Vec<String>>(&seen_json) {
+ Ok(seen) => (seen, auto != 0),
+ Err(e) => {
+ tracing::error!(
+ "[channels] historico de vistos do canal {} esta corrompido ({}). \
+ Download automatico desligado nesta sessao para nao re-baixar tudo.",
+ id,
+ e
+ );
+ (Vec::new(), false)
+ }
+ };
+
Ok(ChannelFollow {
- id: row.get(0)?,
+ id,
url: row.get(1)?,
title: row.get(2)?,
added_at_ms: added as u64,
last_checked_ms: last.map(|v| v as u64),
- seen_ids: serde_json::from_str(&seen_json).unwrap_or_default(),
+ seen_ids,
enabled: enabled != 0,
- auto_download: auto != 0,
+ auto_download,
interval_minutes: interval as u32,
})
}
diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs
index 1ad7e61e..25d7a922 100644
--- a/src-tauri/src/core/mod.rs
+++ b/src-tauri/src/core/mod.rs
@@ -29,5 +29,6 @@ pub mod queue;
pub mod queue_history;
pub mod recovery;
pub mod rpc;
+pub mod state_file;
pub mod trackers;
pub mod url_parser;
diff --git a/src-tauri/src/core/state_file.rs b/src-tauri/src/core/state_file.rs
new file mode 100644
index 00000000..bd47a251
--- /dev/null
+++ b/src-tauri/src/core/state_file.rs
@@ -0,0 +1,198 @@
+//! Leitura de arquivo de estado do usuário sem perda silenciosa.
+//!
+//! O padrão que este módulo substitui é
+//! `read_to_string().ok().and_then(parse).unwrap_or_default()`: quando o
+//! arquivo existe mas não desserializa, o chamador recebe "vazio", e a próxima
+//! gravação sobrescreve o original. O usuário perde tudo sem ver uma linha de
+//! log. Foi assim que o `settings.json` zerou preferências, e o mesmo formato
+//! estava replicado no registro de cookies, nos templates do YouTube e nas
+//! settings de plugin.
+//!
+//! Aqui o arquivo ilegível é **posto em quarentena** antes de qualquer default
+//! ser devolvido: ele é renomeado para `<nome>.corrupt-<epoch_ms>`, o que
+//! impede a gravação seguinte de destruí-lo e deixa uma cópia recuperável.
+
+use std::path::{Path, PathBuf};
+
+fn now_ms() -> u128 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0)
+}
+
+/// Caminho de quarentena para `path`. Público para os testes e para quem
+/// precisar apontar o usuário ao arquivo preservado.
+pub fn quarantine_path(path: &Path, stamp_ms: u128) -> PathBuf {
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("state.json");
+ path.with_file_name(format!("{}.corrupt-{}", name, stamp_ms))
+}
+
+/// Renomeia o arquivo ilegível para o caminho de quarentena. Devolve o destino
+/// quando conseguiu; `None` quando nem isso foi possível (aí o log é o que
+/// resta, e o chamador segue com o default).
+pub fn quarantine(path: &Path, label: &str) -> Option<PathBuf> {
+ let dest = quarantine_path(path, now_ms());
+ match std::fs::rename(path, &dest) {
+ Ok(()) => {
+ tracing::error!(
+ "[state] {} ilegível em {} — preservado como {}. O app seguiu com os valores padrão; \
+ o arquivo original NÃO foi sobrescrito.",
+ label,
+ path.display(),
+ dest.display()
+ );
+ Some(dest)
+ }
+ Err(e) => {
+ tracing::error!(
+ "[state] {} ilegível em {} e não foi possível preservá-lo ({}). \
+ O app seguiu com os valores padrão.",
+ label,
+ path.display(),
+ e
+ );
+ None
+ }
+ }
+}
+
+/// Lê e desserializa um arquivo de estado.
+///
+/// - arquivo ausente → `None`, sem ruído (é o caso normal na primeira execução)
+/// - arquivo ilegível ou corrompido → quarentena + log de erro + `None`
+///
+/// Nunca devolve default silenciosamente: o `None` aqui sempre significa
+/// "não havia estado utilizável", e o motivo está no log quando não for a
+/// primeira execução.
+pub fn load_or_quarantine<T: serde::de::DeserializeOwned>(path: &Path, label: &str) -> Option<T> {
+ if !path.exists() {
+ return None;
+ }
+ let content = match std::fs::read_to_string(path) {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::error!("[state] não foi possível ler {}: {}", path.display(), e);
+ return None;
+ }
+ };
+ // Arquivo vazio (queda no meio de uma gravação não atômica) conta como
+ // ausente, não como corrompido — não há o que preservar.
+ if content.trim().is_empty() {
+ tracing::warn!("[state] {} vazio em {}", label, path.display());
+ return None;
+ }
+ match serde_json::from_str::<T>(&content) {
+ Ok(value) => Some(value),
+ Err(e) => {
+ // O erro do serde nomeia o campo e a posição, nunca o conteúdo —
+ // seguro de logar mesmo para arquivo de cookie.
+ tracing::error!("[state] {} não desserializa: {}", label, e);
+ quarantine(path, label);
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde::{Deserialize, Serialize};
+
+ #[derive(Debug, Serialize, Deserialize, PartialEq)]
+ struct Estado {
+ contas: Vec<String>,
+ }
+
+ fn tmp_dir(nome: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("omniget-state-{}-{}", nome, now_ms()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn arquivo_ausente_devolve_none_sem_quarentena() {
+ let dir = tmp_dir("ausente");
+ let path = dir.join("estado.json");
+ let lido: Option<Estado> = load_or_quarantine(&path, "estado");
+ assert!(lido.is_none());
+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn arquivo_valido_e_lido() {
+ let dir = tmp_dir("valido");
+ let path = dir.join("estado.json");
+ std::fs::write(&path, r#"{"contas":["a","b"]}"#).unwrap();
+ let lido: Option<Estado> = load_or_quarantine(&path, "estado");
+ assert_eq!(
+ lido,
+ Some(Estado {
+ contas: vec!["a".into(), "b".into()]
+ })
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn arquivo_corrompido_vai_para_quarentena_e_o_original_some_do_lugar() {
+ // O ponto do teste: depois disso, um save() do chamador escreve num
+ // caminho limpo e NÃO destrói o conteúdo que o usuário tinha.
+ let dir = tmp_dir("corrompido");
+ let path = dir.join("estado.json");
+ std::fs::write(&path, "{ isto nao e json").unwrap();
+
+ let lido: Option<Estado> = load_or_quarantine(&path, "estado");
+ assert!(lido.is_none());
+ assert!(!path.exists(), "o arquivo corrompido precisa sair do caminho de gravação");
+
+ let preservados: Vec<_> = std::fs::read_dir(&dir)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .map(|e| e.file_name().to_string_lossy().to_string())
+ .filter(|n| n.starts_with("estado.json.corrupt-"))
+ .collect();
+ assert_eq!(preservados.len(), 1, "esperava exatamente uma quarentena, achei {preservados:?}");
+
+ let conteudo = std::fs::read_to_string(dir.join(&preservados[0])).unwrap();
+ assert_eq!(conteudo, "{ isto nao e json", "a quarentena precisa ser byte a byte");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn arquivo_vazio_nao_gera_quarentena() {
+ let dir = tmp_dir("vazio");
+ let path = dir.join("estado.json");
+ std::fs::write(&path, " \n").unwrap();
+ let lido: Option<Estado> = load_or_quarantine(&path, "estado");
+ assert!(lido.is_none());
+ assert!(path.exists(), "arquivo vazio nao tem o que preservar");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn json_valido_de_forma_errada_tambem_e_quarentena() {
+ // Regressao: `serde_json::from_str::<T>` falhando por schema (e nao por
+ // sintaxe) caia no mesmo `unwrap_or_default()` e zerava o estado.
+ let dir = tmp_dir("schema");
+ let path = dir.join("estado.json");
+ std::fs::write(&path, r#"{"contas": "nao e uma lista"}"#).unwrap();
+ let lido: Option<Estado> = load_or_quarantine(&path, "estado");
+ assert!(lido.is_none());
+ assert!(!path.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn quarentenas_repetidas_nao_se_sobrescrevem() {
+ let dir = tmp_dir("repetida");
+ let a = quarantine_path(&dir.join("estado.json"), 1);
+ let b = quarantine_path(&dir.join("estado.json"), 2);
+ assert_ne!(a, b);
+ assert!(a.to_string_lossy().ends_with("estado.json.corrupt-1"));
+ }
+}
diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rs
index 3fd74015..1ceac307 100644
--- a/src-tauri/src/hotkey.rs
+++ b/src-tauri/src/hotkey.rs
@@ -85,18 +85,37 @@ fn matches_binding(pressed: &Shortcut, binding: &str) -> bool {
.unwrap_or(false)
}
+/// Resultado de um acionamento do atalho global, sempre reportado à interface.
+///
+/// Antes, cada caminho de falha fazia `return` mudo: quem apertava o atalho com
+/// o clipboard errado via o app não fazer absolutamente nada e concluía que o
+/// atalho estava quebrado (issue #198). O evento de sucesso existia mas ninguém
+/// escutava, então nem o caminho feliz dava sinal.
+fn emit_hotkey_result(app: &tauri::AppHandle, outcome: &str, url: Option<&str>) {
+ let _ = app.emit(
+ "hotkey-download-result",
+ serde_json::json!({ "outcome": outcome, "url": url }),
+ );
+}
+
fn handle_download_clipboard(app: &tauri::AppHandle) {
let text = match app.clipboard().read_text() {
Ok(t) => t,
- Err(_) => return,
+ Err(e) => {
+ tracing::warn!("[hotkey] nao foi possivel ler o clipboard: {}", e);
+ emit_hotkey_result(app, "clipboard_error", None);
+ return;
+ }
};
let text = text.trim().to_string();
if text.is_empty() || (!text.starts_with("http://") && !text.starts_with("https://")) {
+ emit_hotkey_result(app, "not_a_url", None);
return;
}
if url::Url::parse(&text).is_err() {
+ emit_hotkey_result(app, "not_a_url", None);
return;
}
@@ -107,11 +126,16 @@ fn handle_download_clipboard(app: &tauri::AppHandle) {
}
async fn enqueue_from_clipboard(app: &tauri::AppHandle, url: String) {
- if matches!(
- crate::external_url::queue_url_with_defaults(app, url.clone(), true, None).await,
- Ok(crate::external_url::QueueUrlOutcome::Queued)
- ) {
- let _ = app.emit("hotkey-download-queued", serde_json::json!({ "url": url }));
+ use crate::external_url::QueueUrlOutcome;
+ match crate::external_url::queue_url_with_defaults(app, url.clone(), true, None).await {
+ Ok(QueueUrlOutcome::Queued) => emit_hotkey_result(app, "queued", Some(&url)),
+ Ok(QueueUrlOutcome::AlreadyQueued) => {
+ emit_hotkey_result(app, "already_queued", Some(&url))
+ }
+ Err(e) => {
+ tracing::warn!("[hotkey] enfileiramento recusado: {}", e);
+ emit_hotkey_result(app, "unsupported", Some(&url));
+ }
}
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e98714c0..bf6917c6 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -450,6 +450,11 @@ pub fn run() {
.download
.live_from_start
});
+ core::ytdlp::set_insecure_tls_fn(|| {
+ storage::config::load_settings_standalone()
+ .advanced
+ .insecure_tls
+ });
core::ytdlp::set_concurrent_fragments_fn(|| {
storage::config::load_settings_standalone()
.advanced
diff --git a/src-tauri/src/plugin_host.rs b/src-tauri/src/plugin_host.rs
index ef948c8f..bd6e640b 100644
--- a/src-tauri/src/plugin_host.rs
+++ b/src-tauri/src/plugin_host.rs
@@ -47,10 +47,14 @@ impl<R: Runtime + 'static> PluginHost for PluginHostImpl<R> {
.join(plugin_id)
.join("data")
.join("settings.json");
- std::fs::read_to_string(&settings_path)
- .ok()
- .and_then(|s| serde_json::from_str(&s).ok())
- .unwrap_or(serde_json::Value::Object(Default::default()))
+ // Mesmo par lê-default-e-reescreve do registro de cookies: sem a
+ // quarentena, um settings.json de plugin corrompido é apagado pelo
+ // primeiro `save_settings`.
+ crate::core::state_file::load_or_quarantine(
+ &settings_path,
+ &format!("settings do plugin {}", plugin_id),
+ )
+ .unwrap_or(serde_json::Value::Object(Default::default()))
}
fn save_settings(&self, plugin_id: &str, settings: serde_json::Value) -> anyhow::Result<()> {
diff --git a/src/components/settings/DependencyRow.svelte b/src/components/settings/DependencyRow.svelte
index e2d55929..0a56bdc3 100644
--- a/src/components/settings/DependencyRow.svelte
+++ b/src/components/settings/DependencyRow.svelte
@@ -14,12 +14,13 @@
name: string;
installed: boolean;
version: string | null;
+ outdated?: boolean;
busy: boolean;
onInstall: (variant: string | null) => void | Promise<void>;
onAfterCustomFile?: () => void | Promise<void>;
};
- let { name, installed, version, busy, onInstall, onAfterCustomFile }: Props =
+ let { name, installed, version, outdated = false, busy, onInstall, onAfterCustomFile }: Props =
$props();
let variants = $state<DependencyVariantInfo[]>([]);
@@ -142,7 +143,11 @@
{/if}
</td>
<td class="deps-cell-status">
- {#if installed}
+ {#if installed && outdated}
+ <span class="deps-status deps-status-outdated" title={$t("settings.dependencies.outdated_hint") as string}>
+ {$t("settings.dependencies.status_outdated")}
+ </span>
+ {:else if installed}
<span class="deps-status deps-status-ok">{$t("settings.dependencies.status_installed")}</span>
{:else}
<span class="deps-status deps-status-missing">{$t("settings.dependencies.status_missing")}</span>
@@ -243,6 +248,10 @@
background: color-mix(in srgb, var(--success, #16a34a) 18%, transparent);
color: var(--success, #16a34a);
}
+ .deps-status-outdated {
+ background: color-mix(in srgb, var(--danger) 18%, transparent);
+ color: var(--danger);
+ }
.deps-status-missing {
background: color-mix(in srgb, var(--text) 8%, transparent);
color: var(--text-dim, var(--gray));
diff --git a/src/components/settings/SettingsPlugins.svelte b/src/components/settings/SettingsPlugins.svelte
index 8025e089..6619b1f1 100644
--- a/src/components/settings/SettingsPlugins.svelte
+++ b/src/components/settings/SettingsPlugins.svelte
@@ -1,210 +1,211 @@
-<script lang="ts">
- import { onMount } from "svelte";
- import { invoke } from "@tauri-apps/api/core";
- import { t } from "$lib/i18n";
- import { getSettings, type DependencyStatus } from "./settings-helpers";
- import { showToast } from "$lib/stores/toast-store.svelte";
- import DependencyRow from "./DependencyRow.svelte";
-
- let { deps = [], installingDep = null, onInstallDep, onRefresh }: {
- deps?: DependencyStatus[];
- installingDep?: string | null;
- onInstallDep: (name: string, variant: string | null) => void;
- onRefresh?: () => void | Promise<void>;
- } = $props();
-
- let settings = $derived(getSettings());
-
- type BrowserExtStatus = {
- browser: string;
- supported: boolean;
- bundled_version: string | null;
- installable: boolean;
- install_hint: string;
- store_url: string | null;
- };
-
- let extStatuses = $state<BrowserExtStatus[]>([]);
- let busyBrowser = $state<string | null>(null);
- let installModal = $state<{ browser: string; path: string; hint: string } | null>(null);
-
- onMount(async () => {
- try {
- extStatuses = await invoke<BrowserExtStatus[]>("browser_extension_status");
- } catch (e) {
- console.warn("[ext] status failed", e);
- }
- });
-
- async function exportExtension(browser: string) {
- if (busyBrowser) return;
- busyBrowser = browser;
- try {
- const res = await invoke<{ path: string; version: string | null; browser: string }>(
- "browser_extension_export",
- { browser },
- );
- const status = extStatuses.find((s) => s.browser === browser);
- installModal = {
- browser,
- path: res.path,
- hint: status?.install_hint ?? "",
- };
- } catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
- } finally {
- busyBrowser = null;
- }
- }
-
- async function openFolder(path: string) {
- try {
- await invoke("browser_extension_open_folder", { path });
- } catch (e) {
- showToast("error", e instanceof Error ? e.message : String(e));
- }
- }
-
- function closeInstall() {
- installModal = null;
- }
-
- function browserLabel(b: string): string {
- if (b === "chrome") return "Chrome / Edge / Brave";
- if (b === "firefox") return "Firefox";
- if (b === "safari") return "Safari";
- return b;
- }
-</script>
-
-{#if settings}
- <section class="section">
- <h5 class="section-title">Extensão de navegador</h5>
- <p class="muted">A extensão envia cookies e URLs do seu navegador para o OmniGet. Auto-update direto pelo app só funciona via lojas oficiais — enquanto não publicamos, use os botões abaixo para extrair a versão atual e (re)instalar manualmente.</p>
- <div class="card">
- {#each extStatuses as ext, i (ext.browser)}
- {#if i > 0}<div class="divider"></div>{/if}
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{browserLabel(ext.browser)}</span>
- <span class="setting-path">
- {#if ext.bundled_version}
- Versão empacotada: v{ext.bundled_version}
- {:else}
- {ext.install_hint}
- {/if}
- </span>
- </div>
- {#if ext.installable}
- <button
- class="button"
- disabled={busyBrowser === ext.browser}
- onclick={() => exportExtension(ext.browser)}
- >
- {busyBrowser === ext.browser ? "Extraindo..." : "Atualizar / Instalar"}
- </button>
- {:else if ext.store_url}
- <a class="button" href={ext.store_url} target="_blank" rel="noreferrer">Abrir loja</a>
- {:else}
- <span class="muted small">Indisponível</span>
- {/if}
- </div>
- {/each}
- </div>
- </section>
-
- {#if deps.length > 0}
- <section class="section">
- <div class="settings-section-head section-title">
- <h5 class="section-title">{$t('settings.dependencies.title')}</h5>
- </div>
- <div class="deps-table-wrap">
- <table class="deps-table">
- <thead>
- <tr>
- <th scope="col">{$t('settings.dependencies.col_name')}</th>
- <th scope="col">{$t('settings.dependencies.col_version')}</th>
- <th scope="col">{$t('settings.dependencies.col_status')}</th>
- <th scope="col" class="deps-col-action">{$t('settings.dependencies.col_action')}</th>
- </tr>
- </thead>
- <tbody>
- {#each deps as dep (dep.name)}
- <DependencyRow
- name={dep.name}
- installed={dep.installed}
- version={dep.version}
- busy={installingDep === dep.name}
- onInstall={(variant) => onInstallDep(dep.name, variant)}
- onAfterCustomFile={onRefresh}
- />
- {/each}
- </tbody>
- </table>
- </div>
- </section>
- {/if}
-{/if}
-
-{#if installModal}
- <div class="overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) closeInstall(); }}>
- <div class="dialog" role="dialog" aria-modal="true">
- <header class="head">
- <h3>Instalar / Atualizar extensão — {browserLabel(installModal.browser)}</h3>
- <button class="close" onclick={closeInstall} aria-label="fechar">×</button>
- </header>
- <div class="body">
- <p>A extensão foi extraída para:</p>
- <code class="path">{installModal.path}</code>
- <button class="button" onclick={() => openFolder(installModal!.path)}>Abrir pasta</button>
- <h4>Como instalar / atualizar</h4>
- <p class="hint">{installModal.hint}</p>
- <p class="hint small">
- Se a extensão já está instalada, clique em "Recarregar" no <code>{installModal.browser === 'firefox' ? 'about:debugging' : 'chrome://extensions'}</code> apontando pra essa pasta — ou remova a antiga e adicione a nova.
- </p>
- </div>
- <footer class="foot">
- <button class="button" onclick={closeInstall}>Fechar</button>
- </footer>
- </div>
- </div>
-{/if}
-
-<style>
- .muted { color: rgba(255, 255, 255, 0.6); font-size: 12px; line-height: 1.4; margin: 0 0 8px; }
- .small { font-size: 11px; }
- .overlay {
- position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6);
- display: grid; place-items: center; z-index: 999;
- }
- .dialog {
- background: var(--bg-card, #1a1a1a);
- border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: 12px;
- width: min(560px, 90vw);
- max-height: 80vh; overflow: auto;
- display: flex; flex-direction: column;
- }
- .head {
- display: flex; justify-content: space-between; align-items: center;
- padding: 16px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.05);
- }
- .head h3 { margin: 0; font-size: 16px; }
- .close {
- background: transparent; border: 0; color: rgba(255, 255, 255, 0.6);
- font-size: 22px; line-height: 1; cursor: pointer;
- }
- .body { padding: 16px 20px; display: flex; flex-direction: column; gap: 12px; }
- .body h4 { margin: 8px 0 0; font-size: 13px; font-weight: 600; }
- .body p { margin: 0; font-size: 13px; line-height: 1.5; }
- .body .hint { color: rgba(255, 255, 255, 0.7); }
- .path {
- display: block; padding: 8px 10px; background: rgba(0, 0, 0, 0.4);
- border-radius: 6px; font-family: var(--font-mono, monospace); font-size: 11px;
- word-break: break-all;
- }
- .foot {
- padding: 12px 20px; border-top: 1px solid rgba(255, 255, 255, 0.05);
- display: flex; justify-content: flex-end;
- }
-</style>
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { invoke } from "@tauri-apps/api/core";
+ import { t } from "$lib/i18n";
+ import { getSettings, type DependencyStatus } from "./settings-helpers";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import DependencyRow from "./DependencyRow.svelte";
+
+ let { deps = [], installingDep = null, onInstallDep, onRefresh }: {
+ deps?: DependencyStatus[];
+ installingDep?: string | null;
+ onInstallDep: (name: string, variant: string | null) => void;
+ onRefresh?: () => void | Promise<void>;
+ } = $props();
+
+ let settings = $derived(getSettings());
+
+ type BrowserExtStatus = {
+ browser: string;
+ supported: boolean;
+ bundled_version: string | null;
+ installable: boolean;
+ install_hint: string;
+ store_url: string | null;
+ };
+
+ let extStatuses = $state<BrowserExtStatus[]>([]);
+ let busyBrowser = $state<string | null>(null);
+ let installModal = $state<{ browser: string; path: string; hint: string } | null>(null);
+
+ onMount(async () => {
+ try {
+ extStatuses = await invoke<BrowserExtStatus[]>("browser_extension_status");
+ } catch (e) {
+ console.warn("[ext] status failed", e);
+ }
+ });
+
+ async function exportExtension(browser: string) {
+ if (busyBrowser) return;
+ busyBrowser = browser;
+ try {
+ const res = await invoke<{ path: string; version: string | null; browser: string }>(
+ "browser_extension_export",
+ { browser },
+ );
+ const status = extStatuses.find((s) => s.browser === browser);
+ installModal = {
+ browser,
+ path: res.path,
+ hint: status?.install_hint ?? "",
+ };
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ } finally {
+ busyBrowser = null;
+ }
+ }
+
+ async function openFolder(path: string) {
+ try {
+ await invoke("browser_extension_open_folder", { path });
+ } catch (e) {
+ showToast("error", e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ function closeInstall() {
+ installModal = null;
+ }
+
+ function browserLabel(b: string): string {
+ if (b === "chrome") return "Chrome / Edge / Brave";
+ if (b === "firefox") return "Firefox";
+ if (b === "safari") return "Safari";
+ return b;
+ }
+</script>
+
+{#if settings}
+ <section class="section">
+ <h5 class="section-title">Extensão de navegador</h5>
+ <p class="muted">A extensão envia cookies e URLs do seu navegador para o OmniGet. Auto-update direto pelo app só funciona via lojas oficiais — enquanto não publicamos, use os botões abaixo para extrair a versão atual e (re)instalar manualmente.</p>
+ <div class="card">
+ {#each extStatuses as ext, i (ext.browser)}
+ {#if i > 0}<div class="divider"></div>{/if}
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{browserLabel(ext.browser)}</span>
+ <span class="setting-path">
+ {#if ext.bundled_version}
+ Versão empacotada: v{ext.bundled_version}
+ {:else}
+ {ext.install_hint}
+ {/if}
+ </span>
+ </div>
+ {#if ext.installable}
+ <button
+ class="button"
+ disabled={busyBrowser === ext.browser}
+ onclick={() => exportExtension(ext.browser)}
+ >
+ {busyBrowser === ext.browser ? "Extraindo..." : "Atualizar / Instalar"}
+ </button>
+ {:else if ext.store_url}
+ <a class="button" href={ext.store_url} target="_blank" rel="noreferrer">Abrir loja</a>
+ {:else}
+ <span class="muted small">Indisponível</span>
+ {/if}
+ </div>
+ {/each}
+ </div>
+ </section>
+
+ {#if deps.length > 0}
+ <section class="section">
+ <div class="settings-section-head section-title">
+ <h5 class="section-title">{$t('settings.dependencies.title')}</h5>
+ </div>
+ <div class="deps-table-wrap">
+ <table class="deps-table">
+ <thead>
+ <tr>
+ <th scope="col">{$t('settings.dependencies.col_name')}</th>
+ <th scope="col">{$t('settings.dependencies.col_version')}</th>
+ <th scope="col">{$t('settings.dependencies.col_status')}</th>
+ <th scope="col" class="deps-col-action">{$t('settings.dependencies.col_action')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each deps as dep (dep.name)}
+ <DependencyRow
+ name={dep.name}
+ installed={dep.installed}
+ version={dep.version}
+ outdated={dep.outdated}
+ busy={installingDep === dep.name}
+ onInstall={(variant) => onInstallDep(dep.name, variant)}
+ onAfterCustomFile={onRefresh}
+ />
+ {/each}
+ </tbody>
+ </table>
+ </div>
+ </section>
+ {/if}
+{/if}
+
+{#if installModal}
+ <div class="overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget) closeInstall(); }}>
+ <div class="dialog" role="dialog" aria-modal="true">
+ <header class="head">
+ <h3>Instalar / Atualizar extensão — {browserLabel(installModal.browser)}</h3>
+ <button class="close" onclick={closeInstall} aria-label="fechar">×</button>
+ </header>
+ <div class="body">
+ <p>A extensão foi extraída para:</p>
+ <code class="path">{installModal.path}</code>
+ <button class="button" onclick={() => openFolder(installModal!.path)}>Abrir pasta</button>
+ <h4>Como instalar / atualizar</h4>
+ <p class="hint">{installModal.hint}</p>
+ <p class="hint small">
+ Se a extensão já está instalada, clique em "Recarregar" no <code>{installModal.browser === 'firefox' ? 'about:debugging' : 'chrome://extensions'}</code> apontando pra essa pasta — ou remova a antiga e adicione a nova.
+ </p>
+ </div>
+ <footer class="foot">
+ <button class="button" onclick={closeInstall}>Fechar</button>
+ </footer>
+ </div>
+ </div>
+{/if}
+
+<style>
+ .muted { color: rgba(255, 255, 255, 0.6); font-size: 12px; line-height: 1.4; margin: 0 0 8px; }
+ .small { font-size: 11px; }
+ .overlay {
+ position: fixed; inset: 0; background: rgba(0, 0, 0, 0.6);
+ display: grid; place-items: center; z-index: 999;
+ }
+ .dialog {
+ background: var(--bg-card, #1a1a1a);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 12px;
+ width: min(560px, 90vw);
+ max-height: 80vh; overflow: auto;
+ display: flex; flex-direction: column;
+ }
+ .head {
+ display: flex; justify-content: space-between; align-items: center;
+ padding: 16px 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ }
+ .head h3 { margin: 0; font-size: 16px; }
+ .close {
+ background: transparent; border: 0; color: rgba(255, 255, 255, 0.6);
+ font-size: 22px; line-height: 1; cursor: pointer;
+ }
+ .body { padding: 16px 20px; display: flex; flex-direction: column; gap: 12px; }
+ .body h4 { margin: 8px 0 0; font-size: 13px; font-weight: 600; }
+ .body p { margin: 0; font-size: 13px; line-height: 1.5; }
+ .body .hint { color: rgba(255, 255, 255, 0.7); }
+ .path {
+ display: block; padding: 8px 10px; background: rgba(0, 0, 0, 0.4);
+ border-radius: 6px; font-family: var(--font-mono, monospace); font-size: 11px;
+ word-break: break-all;
+ }
+ .foot {
+ padding: 12px 20px; border-top: 1px solid rgba(255, 255, 255, 0.05);
+ display: flex; justify-content: flex-end;
+ }
+</style>
diff --git a/src/components/settings/downloads/ClipboardHotkeysSection.svelte b/src/components/settings/downloads/ClipboardHotkeysSection.svelte
index 5c142ea8..e97d5cc4 100644
--- a/src/components/settings/downloads/ClipboardHotkeysSection.svelte
+++ b/src/components/settings/downloads/ClipboardHotkeysSection.svelte
@@ -1,201 +1,215 @@
-<script lang="ts">
- import { t } from "$lib/i18n";
- import ContextHint from "$components/hints/ContextHint.svelte";
- import { getSettings, updateSettings, toggleBool } from "../settings-helpers";
-
- let { embedded = false }: { embedded?: boolean } = $props();
-
- let settings = $derived(getSettings());
-
- let hotkeyInput = $state("");
- let hotkeyTimer: ReturnType<typeof setTimeout> | null = null;
- let hotkeyMode = $state<"record" | "type">("record");
- let hotkeyRecording = $state(false);
- let musicHotkeyInput = $state("");
- let musicHotkeyTimer: ReturnType<typeof setTimeout> | null = null;
- let musicHotkeyMode = $state<"record" | "type">("record");
- let musicHotkeyRecording = $state(false);
-
- $effect(() => {
- if (settings) {
- hotkeyInput = settings.download.hotkey_binding;
- musicHotkeyInput = settings.download.music_hotkey_binding;
- }
- });
-
- function handleHotkeyInput(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- hotkeyInput = value;
- if (hotkeyTimer) clearTimeout(hotkeyTimer);
- hotkeyTimer = setTimeout(async () => {
- if (value.trim()) {
- await updateSettings({ download: { hotkey_binding: value } });
- }
- }, 800);
- }
-
- function mapKeyName(key: string): string | null {
- if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();
- if (key.length === 1 && /[0-9]/.test(key)) return key;
- if (/^F([1-9]|1[0-2])$/.test(key)) return key;
- const map: Record<string, string> = {
- " ": "Space", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",
- Enter: "Enter", Tab: "Tab", Escape: "Escape", Backspace: "Backspace", Delete: "Delete",
- Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", Insert: "Insert",
- };
- return map[key] ?? null;
- }
-
- function handleHotkeyKeyDown(e: KeyboardEvent) {
- e.preventDefault();
- e.stopPropagation();
- if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
- const keyName = mapKeyName(e.key);
- if (!keyName) return;
- const parts: string[] = [];
- if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
- if (e.shiftKey) parts.push("Shift");
- if (e.altKey) parts.push("Alt");
- parts.push(keyName);
- const value = parts.join("+");
- hotkeyInput = value;
- hotkeyRecording = false;
- updateSettings({ download: { hotkey_binding: value } });
- }
-
- function handleMusicHotkeyInput(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- musicHotkeyInput = value;
- if (musicHotkeyTimer) clearTimeout(musicHotkeyTimer);
- musicHotkeyTimer = setTimeout(async () => {
- if (value.trim()) {
- await updateSettings({ download: { music_hotkey_binding: value } });
- }
- }, 800);
- }
-
- function handleMusicHotkeyKeyDown(e: KeyboardEvent) {
- e.preventDefault();
- e.stopPropagation();
- if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
- const keyName = mapKeyName(e.key);
- if (!keyName) return;
- const parts: string[] = [];
- if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
- if (e.shiftKey) parts.push("Shift");
- if (e.altKey) parts.push("Alt");
- parts.push(keyName);
- const value = parts.join("+");
- musicHotkeyInput = value;
- musicHotkeyRecording = false;
- updateSettings({ download: { music_hotkey_binding: value } });
- }
-
- function changeMusicAudioFormat(e: Event) {
- const value = (e.target as HTMLSelectElement).value;
- updateSettings({ download: { music_audio_format: value } });
- }
-</script>
-
-{#if settings}
- {#if !embedded}
- <div class="settings-section-head section-title">
- <h5 class="section-title">{$t('settings.download.section_clipboard_hotkeys')}</h5>
- <p class="settings-section-hint">{$t('settings.download.section_clipboard_hotkeys_desc')}</p>
- </div>
- {/if}
-
- <div class="card">
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.clipboard_detection')} <ContextHint text={$t('hints.clipboard') as string} dismissKey="clipboard" /></span>
- <span class="setting-path">{$t('settings.download.clipboard_detection_desc')}</span>
- </div>
- <button class="toggle" class:on={settings.download.clipboard_detection} onclick={() => toggleBool("download", "clipboard_detection", settings.download.clipboard_detection)} role="switch" aria-checked={settings.download.clipboard_detection} aria-label={$t('settings.download.clipboard_detection') as string}><span class="toggle-knob"></span></button>
- </div>
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.auto_download_on_paste')}</span>
- <span class="setting-path">{$t('settings.download.auto_download_on_paste_desc')}</span>
- </div>
- <button class="toggle" class:on={settings.download.auto_download_on_paste} onclick={() => toggleBool("download", "auto_download_on_paste", settings.download.auto_download_on_paste)} role="switch" aria-checked={settings.download.auto_download_on_paste} aria-label={$t('settings.download.auto_download_on_paste') as string}><span class="toggle-knob"></span></button>
- </div>
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.hotkey_enabled')} <ContextHint text={$t('hints.hotkey') as string} dismissKey="hotkey" /></span>
- <span class="setting-path">{$t('settings.download.hotkey_enabled_desc')}</span>
- </div>
- <button class="toggle" class:on={settings.download.hotkey_enabled} onclick={() => toggleBool("download", "hotkey_enabled", settings.download.hotkey_enabled)} role="switch" aria-checked={settings.download.hotkey_enabled} aria-label={$t('settings.download.hotkey_enabled') as string}><span class="toggle-knob"></span></button>
- </div>
- {#if settings.download.hotkey_enabled}
- <div class="divider"></div>
- <div class="setting-row hotkey-row">
- <span class="setting-label">{$t('settings.download.hotkey_binding')}</span>
- <div class="hotkey-controls">
- <div class="hotkey-mode-switch">
- <button class="hotkey-mode-btn" class:active={hotkeyMode === 'record'} onclick={() => { hotkeyMode = 'record'; hotkeyRecording = false; }}>{$t('settings.download.hotkey_record')}</button>
- <button class="hotkey-mode-btn" class:active={hotkeyMode === 'type'} onclick={() => { hotkeyMode = 'type'; hotkeyRecording = false; }}>{$t('settings.download.hotkey_type')}</button>
- </div>
- {#if hotkeyMode === 'type'}
- <input type="text" class="input-hotkey" value={hotkeyInput} oninput={handleHotkeyInput} spellcheck="false" />
- {:else}
- <button class="input-hotkey hotkey-record-btn" class:recording={hotkeyRecording} onclick={() => { hotkeyRecording = true; }} onkeydown={hotkeyRecording ? handleHotkeyKeyDown : undefined} onblur={() => { hotkeyRecording = false; }}>
- {hotkeyRecording ? $t('settings.download.hotkey_press') : (hotkeyInput || $t('settings.download.hotkey_press'))}
- </button>
- {/if}
- </div>
- </div>
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.copy_to_clipboard_on_hotkey')}</span>
- <span class="setting-path">{$t('settings.download.copy_to_clipboard_on_hotkey_desc')}</span>
- </div>
- <button class="toggle" class:on={settings.download.copy_to_clipboard_on_hotkey} onclick={() => toggleBool("download", "copy_to_clipboard_on_hotkey", settings.download.copy_to_clipboard_on_hotkey)} role="switch" aria-checked={settings.download.copy_to_clipboard_on_hotkey} aria-label={$t('settings.download.copy_to_clipboard_on_hotkey') as string}><span class="toggle-knob"></span></button>
- </div>
- {/if}
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.music_hotkey_enabled')}</span>
- <span class="setting-path">{$t('settings.download.music_hotkey_enabled_desc')}</span>
- </div>
- <button class="toggle" class:on={settings.download.music_hotkey_enabled} onclick={() => toggleBool("download", "music_hotkey_enabled", settings.download.music_hotkey_enabled)} role="switch" aria-checked={settings.download.music_hotkey_enabled} aria-label={$t('settings.download.music_hotkey_enabled') as string}><span class="toggle-knob"></span></button>
- </div>
- {#if settings.download.music_hotkey_enabled}
- <div class="divider"></div>
- <div class="setting-row hotkey-row">
- <span class="setting-label">{$t('settings.download.music_hotkey_binding')}</span>
- <div class="hotkey-controls">
- <div class="hotkey-mode-switch">
- <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'record'} onclick={() => { musicHotkeyMode = 'record'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_record')}</button>
- <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'type'} onclick={() => { musicHotkeyMode = 'type'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_type')}</button>
- </div>
- {#if musicHotkeyMode === 'type'}
- <input type="text" class="input-hotkey" value={musicHotkeyInput} oninput={handleMusicHotkeyInput} spellcheck="false" />
- {:else}
- <button class="input-hotkey hotkey-record-btn" class:recording={musicHotkeyRecording} onclick={() => { musicHotkeyRecording = true; }} onkeydown={musicHotkeyRecording ? handleMusicHotkeyKeyDown : undefined} onblur={() => { musicHotkeyRecording = false; }}>
- {musicHotkeyRecording ? $t('settings.download.hotkey_press') : (musicHotkeyInput || $t('settings.download.hotkey_press'))}
- </button>
- {/if}
- </div>
- </div>
- {/if}
- <div class="divider"></div>
- <div class="setting-row">
- <div class="setting-col">
- <span class="setting-label">{$t('settings.download.music_audio_format')}</span>
- <span class="setting-path">{$t('settings.download.music_audio_format_desc')}</span>
- </div>
- <select class="select" value={settings.download.music_audio_format} onchange={changeMusicAudioFormat}>
- <option value="m4a">M4A (AAC)</option>
- <option value="mp3">MP3</option>
- <option value="flac">FLAC (lossless)</option>
- <option value="opus">Opus</option>
- <option value="wav">WAV</option>
- </select>
- </div>
- </div>
-{/if}
+<script lang="ts">
+ import { t } from "$lib/i18n";
+ import ContextHint from "$components/hints/ContextHint.svelte";
+ import { getSettings, updateSettings, toggleBool } from "../settings-helpers";
+
+ let { embedded = false }: { embedded?: boolean } = $props();
+
+ let settings = $derived(getSettings());
+
+ let hotkeyInput = $state("");
+ let hotkeyTimer: ReturnType<typeof setTimeout> | null = null;
+ let hotkeyMode = $state<"record" | "type">("record");
+ let hotkeyRecording = $state(false);
+ let musicHotkeyInput = $state("");
+ let musicHotkeyTimer: ReturnType<typeof setTimeout> | null = null;
+ let musicHotkeyMode = $state<"record" | "type">("record");
+ let musicHotkeyRecording = $state(false);
+
+ $effect(() => {
+ if (settings) {
+ hotkeyInput = settings.download.hotkey_binding;
+ musicHotkeyInput = settings.download.music_hotkey_binding;
+ }
+ });
+
+ function handleHotkeyInput(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ hotkeyInput = value;
+ if (hotkeyTimer) clearTimeout(hotkeyTimer);
+ hotkeyTimer = setTimeout(async () => {
+ if (value.trim()) {
+ await updateSettings({ download: { hotkey_binding: value } });
+ }
+ }, 800);
+ }
+
+ function mapKeyName(key: string): string | null {
+ if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();
+ if (key.length === 1 && /[0-9]/.test(key)) return key;
+ if (/^F([1-9]|1[0-2])$/.test(key)) return key;
+ const map: Record<string, string> = {
+ " ": "Space", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",
+ Enter: "Enter", Tab: "Tab", Escape: "Escape", Backspace: "Backspace", Delete: "Delete",
+ Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", Insert: "Insert",
+ };
+ return map[key] ?? null;
+ }
+
+ // O WebKit do macOS não dá foco a um `<button>` ao clicar, então o keydown
+ // nunca chegava e o gravador ficava preso em "Pressione as teclas…".
+ function startRecording(e: MouseEvent) {
+ (e.currentTarget as HTMLButtonElement | null)?.focus();
+ }
+
+ function handleHotkeyKeyDown(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.key === "Escape") {
+ hotkeyRecording = false;
+ return;
+ }
+ if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
+ const keyName = mapKeyName(e.key);
+ if (!keyName) return;
+ const parts: string[] = [];
+ if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
+ if (e.shiftKey) parts.push("Shift");
+ if (e.altKey) parts.push("Alt");
+ parts.push(keyName);
+ const value = parts.join("+");
+ hotkeyInput = value;
+ hotkeyRecording = false;
+ updateSettings({ download: { hotkey_binding: value } });
+ }
+
+ function handleMusicHotkeyInput(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ musicHotkeyInput = value;
+ if (musicHotkeyTimer) clearTimeout(musicHotkeyTimer);
+ musicHotkeyTimer = setTimeout(async () => {
+ if (value.trim()) {
+ await updateSettings({ download: { music_hotkey_binding: value } });
+ }
+ }, 800);
+ }
+
+ function handleMusicHotkeyKeyDown(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (e.key === "Escape") {
+ musicHotkeyRecording = false;
+ return;
+ }
+ if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
+ const keyName = mapKeyName(e.key);
+ if (!keyName) return;
+ const parts: string[] = [];
+ if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
+ if (e.shiftKey) parts.push("Shift");
+ if (e.altKey) parts.push("Alt");
+ parts.push(keyName);
+ const value = parts.join("+");
+ musicHotkeyInput = value;
+ musicHotkeyRecording = false;
+ updateSettings({ download: { music_hotkey_binding: value } });
+ }
+
+ function changeMusicAudioFormat(e: Event) {
+ const value = (e.target as HTMLSelectElement).value;
+ updateSettings({ download: { music_audio_format: value } });
+ }
+</script>
+
+{#if settings}
+ {#if !embedded}
+ <div class="settings-section-head section-title">
+ <h5 class="section-title">{$t('settings.download.section_clipboard_hotkeys')}</h5>
+ <p class="settings-section-hint">{$t('settings.download.section_clipboard_hotkeys_desc')}</p>
+ </div>
+ {/if}
+
+ <div class="card">
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.clipboard_detection')} <ContextHint text={$t('hints.clipboard') as string} dismissKey="clipboard" /></span>
+ <span class="setting-path">{$t('settings.download.clipboard_detection_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.clipboard_detection} onclick={() => toggleBool("download", "clipboard_detection", settings.download.clipboard_detection)} role="switch" aria-checked={settings.download.clipboard_detection} aria-label={$t('settings.download.clipboard_detection') as string}><span class="toggle-knob"></span></button>
+ </div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.auto_download_on_paste')}</span>
+ <span class="setting-path">{$t('settings.download.auto_download_on_paste_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.auto_download_on_paste} onclick={() => toggleBool("download", "auto_download_on_paste", settings.download.auto_download_on_paste)} role="switch" aria-checked={settings.download.auto_download_on_paste} aria-label={$t('settings.download.auto_download_on_paste') as string}><span class="toggle-knob"></span></button>
+ </div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.hotkey_enabled')} <ContextHint text={$t('hints.hotkey') as string} dismissKey="hotkey" /></span>
+ <span class="setting-path">{$t('settings.download.hotkey_enabled_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.hotkey_enabled} onclick={() => toggleBool("download", "hotkey_enabled", settings.download.hotkey_enabled)} role="switch" aria-checked={settings.download.hotkey_enabled} aria-label={$t('settings.download.hotkey_enabled') as string}><span class="toggle-knob"></span></button>
+ </div>
+ {#if settings.download.hotkey_enabled}
+ <div class="divider"></div>
+ <div class="setting-row hotkey-row">
+ <span class="setting-label">{$t('settings.download.hotkey_binding')}</span>
+ <div class="hotkey-controls">
+ <div class="hotkey-mode-switch">
+ <button class="hotkey-mode-btn" class:active={hotkeyMode === 'record'} onclick={() => { hotkeyMode = 'record'; hotkeyRecording = false; }}>{$t('settings.download.hotkey_record')}</button>
+ <button class="hotkey-mode-btn" class:active={hotkeyMode === 'type'} onclick={() => { hotkeyMode = 'type'; hotkeyRecording = false; }}>{$t('settings.download.hotkey_type')}</button>
+ </div>
+ {#if hotkeyMode === 'type'}
+ <input type="text" class="input-hotkey" value={hotkeyInput} oninput={handleHotkeyInput} spellcheck="false" />
+ {:else}
+ <button class="input-hotkey hotkey-record-btn" class:recording={hotkeyRecording} onclick={(e) => { hotkeyRecording = true; startRecording(e); }} onkeydown={hotkeyRecording ? handleHotkeyKeyDown : undefined} onblur={() => { hotkeyRecording = false; }}>
+ {hotkeyRecording ? $t('settings.download.hotkey_press') : (hotkeyInput || $t('settings.download.hotkey_press'))}
+ </button>
+ {/if}
+ </div>
+ </div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.copy_to_clipboard_on_hotkey')}</span>
+ <span class="setting-path">{$t('settings.download.copy_to_clipboard_on_hotkey_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.copy_to_clipboard_on_hotkey} onclick={() => toggleBool("download", "copy_to_clipboard_on_hotkey", settings.download.copy_to_clipboard_on_hotkey)} role="switch" aria-checked={settings.download.copy_to_clipboard_on_hotkey} aria-label={$t('settings.download.copy_to_clipboard_on_hotkey') as string}><span class="toggle-knob"></span></button>
+ </div>
+ {/if}
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.music_hotkey_enabled')}</span>
+ <span class="setting-path">{$t('settings.download.music_hotkey_enabled_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.music_hotkey_enabled} onclick={() => toggleBool("download", "music_hotkey_enabled", settings.download.music_hotkey_enabled)} role="switch" aria-checked={settings.download.music_hotkey_enabled} aria-label={$t('settings.download.music_hotkey_enabled') as string}><span class="toggle-knob"></span></button>
+ </div>
+ {#if settings.download.music_hotkey_enabled}
+ <div class="divider"></div>
+ <div class="setting-row hotkey-row">
+ <span class="setting-label">{$t('settings.download.music_hotkey_binding')}</span>
+ <div class="hotkey-controls">
+ <div class="hotkey-mode-switch">
+ <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'record'} onclick={() => { musicHotkeyMode = 'record'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_record')}</button>
+ <button class="hotkey-mode-btn" class:active={musicHotkeyMode === 'type'} onclick={() => { musicHotkeyMode = 'type'; musicHotkeyRecording = false; }}>{$t('settings.download.hotkey_type')}</button>
+ </div>
+ {#if musicHotkeyMode === 'type'}
+ <input type="text" class="input-hotkey" value={musicHotkeyInput} oninput={handleMusicHotkeyInput} spellcheck="false" />
+ {:else}
+ <button class="input-hotkey hotkey-record-btn" class:recording={musicHotkeyRecording} onclick={(e) => { musicHotkeyRecording = true; startRecording(e); }} onkeydown={musicHotkeyRecording ? handleMusicHotkeyKeyDown : undefined} onblur={() => { musicHotkeyRecording = false; }}>
+ {musicHotkeyRecording ? $t('settings.download.hotkey_press') : (musicHotkeyInput || $t('settings.download.hotkey_press'))}
+ </button>
+ {/if}
+ </div>
+ </div>
+ {/if}
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.music_audio_format')}</span>
+ <span class="setting-path">{$t('settings.download.music_audio_format_desc')}</span>
+ </div>
+ <select class="select" value={settings.download.music_audio_format} onchange={changeMusicAudioFormat}>
+ <option value="m4a">M4A (AAC)</option>
+ <option value="mp3">MP3</option>
+ <option value="flac">FLAC (lossless)</option>
+ <option value="opus">Opus</option>
+ <option value="wav">WAV</option>
+ </select>
+ </div>
+ </div>
+{/if}
diff --git a/src/components/settings/settings-helpers.ts b/src/components/settings/settings-helpers.ts
index 16e50f30..1d9e8aa5 100644
--- a/src/components/settings/settings-helpers.ts
+++ b/src/components/settings/settings-helpers.ts
@@ -63,6 +63,7 @@ export type DependencyStatus = {
name: string;
installed: boolean;
version: string | null;
+ outdated: boolean;
};
export async function loadDeps(): Promise<DependencyStatus[]> {
diff --git a/src/components/shell/AppToolbar.svelte b/src/components/shell/AppToolbar.svelte
index 9cfd410c..33b2018e 100644
--- a/src/components/shell/AppToolbar.svelte
+++ b/src/components/shell/AppToolbar.svelte
@@ -1,25 +1,25 @@
-<script lang="ts">
- import { page } from "$app/state";
- import { t } from "$lib/i18n";
- import { openCommandPalette } from "$lib/stores/command-palette-store.svelte";
-
- let pageTitle = $derived.by(() => {
- const path = page.url.pathname;
- if (path === "/") return $t("nav.home");
- if (path.startsWith("/downloads")) return $t("nav.downloads");
- if (path.startsWith("/marketplace")) return $t("nav.marketplace");
- if (path.startsWith("/settings")) return $t("nav.settings");
- if (path.startsWith("/about")) return $t("nav.about");
- return "OmniGet";
- });
-</script>
-
-<header class="mac-titlebar">
- <span class="mac-titlebar-title">{pageTitle}</span>
- <div class="mac-titlebar-actions">
- <button type="button" class="btn btn-secondary btn-sm" onclick={() => openCommandPalette()}>
- {$t("command_palette.open")}
- <span class="mac-kbd">⌘K</span>
- </button>
- </div>
-</header>
+<script lang="ts">
+ import { page } from "$app/state";
+ import { t } from "$lib/i18n";
+ import { openCommandPalette } from "$lib/stores/command-palette-store.svelte";
+
+ let pageTitle = $derived.by(() => {
+ const path = page.url.pathname;
+ if (path === "/") return $t("nav.home");
+ if (path.startsWith("/downloads")) return $t("nav.downloads");
+ if (path.startsWith("/marketplace")) return $t("nav.marketplace");
+ if (path.startsWith("/settings")) return $t("nav.settings");
+ if (path.startsWith("/about")) return $t("nav.about");
+ return "OmniGet";
+ });
+</script>
+
+<header class="mac-titlebar" data-tauri-drag-region>
+ <span class="mac-titlebar-title" data-tauri-drag-region>{pageTitle}</span>
+ <div class="mac-titlebar-actions">
+ <button type="button" class="btn btn-secondary btn-sm" onclick={() => openCommandPalette()}>
+ {$t("command_palette.open")}
+ <span class="mac-kbd">⌘K</span>
+ </button>
+ </div>
+</header>
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 7237e1d9..9d47f29e 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -446,6 +446,11 @@
"auto_download_started": "Αυτόματη λήψη ξεκίνησε",
"external_url_ready": "Το URL λήφθηκε και είναι έτοιμο για λήψη",
"external_url_queued": "Η λήψη προστέθηκε από την επέκταση Chrome",
+ "hotkey_queued": "Η λήψη ξεκίνησε από το πρόχειρο",
+ "hotkey_already_queued": "Αυτός ο σύνδεσμος είναι ήδη στην ουρά",
+ "hotkey_not_a_url": "Αντιγράψτε πρώτα έναν σύνδεσμο — δεν υπάρχει διεύθυνση στο πρόχειρο",
+ "hotkey_unsupported": "Κανένα πρόγραμμα λήψης δεν καλύπτει αυτόν τον σύνδεσμο. Επικολλήστε τον στην αρχική οθόνη για να δείτε τις επιλογές.",
+ "hotkey_clipboard_error": "Δεν ήταν δυνατή η ανάγνωση του προχείρου. Αντιγράψτε ξανά τον σύνδεσμο και πατήστε τη συντόμευση.",
"channel_new": "{{channel}}: {{count}} νέο/α βίντεο",
"channel_new_auto": "{{channel}}: λήψη {{count}} νέου/ων βίντεο",
"file_copied_to_clipboard": "Το αρχείο αντιγράφηκε στο πρόχειρο",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Παρωχημένο",
+ "outdated_hint": "Αυτή η έκδοση δεν έχει τις δημοσιευμένες διορθώσεις ασφαλείας. Χρησιμοποιήστε την Ενημέρωση για την τρέχουσα.",
"status_missing": "Missing",
"not_found": "δεν βρέθηκε",
"install": "Εγκατάσταση",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index bfd04fa5..1aa78b2b 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -446,6 +446,11 @@
"auto_download_started": "Auto-download started",
"external_url_ready": "URL received and ready to download",
"external_url_queued": "Download added from the Chrome extension",
+ "hotkey_queued": "Download started from your clipboard",
+ "hotkey_already_queued": "That link is already in your queue",
+ "hotkey_not_a_url": "Copy a link first — there's no web address on your clipboard",
+ "hotkey_unsupported": "No downloader handles that link. Paste it on the home screen to see your options.",
+ "hotkey_clipboard_error": "Couldn't read your clipboard. Copy the link again and press the shortcut.",
"channel_new": "{{channel}}: {{count}} new video(s)",
"channel_new_auto": "{{channel}}: downloading {{count}} new video(s)",
"file_copied_to_clipboard": "File copied to clipboard",
@@ -558,7 +563,7 @@
"language": "Language",
"lang_pt": "Português",
"lang_en": "English",
- "lang_ru": "Русский",
+ "lang_ru": "Русский",
"lang_zh": "中文",
"lang_ja": "日本語",
"lang_it": "Italiano",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Outdated",
+ "outdated_hint": "This version is missing published security fixes. Use Update to get the current one.",
"status_missing": "Missing",
"not_found": "not found",
"install": "Install",
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index 1802339f..9bcc1e2c 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -446,6 +446,11 @@
"auto_download_started": "Auto-download started",
"external_url_ready": "URL recibida y lista para descargar",
"external_url_queued": "Descarga añadida desde la extensión de Chrome",
+ "hotkey_queued": "Descarga iniciada desde el portapapeles",
+ "hotkey_already_queued": "Ese enlace ya está en la cola",
+ "hotkey_not_a_url": "Copia un enlace primero: no hay ninguna dirección en el portapapeles",
+ "hotkey_unsupported": "Ningún descargador cubre ese enlace. Pégalo en la pantalla de inicio para ver las opciones.",
+ "hotkey_clipboard_error": "No se pudo leer el portapapeles. Copia el enlace otra vez y usa el atajo.",
"channel_new": "{{channel}}: {{count}} vídeo(s) nuevo(s)",
"channel_new_auto": "{{channel}}: descargando {{count}} vídeo(s) nuevo(s)",
"file_copied_to_clipboard": "Archivo copiado al portapapeles",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Desactualizado",
+ "outdated_hint": "Esta versión no incluye correcciones de seguridad ya publicadas. Usa Actualizar para obtener la actual.",
"status_missing": "Missing",
"not_found": "no encontrado",
"install": "Instalar",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index 67cefa03..b62e77c7 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -446,6 +446,11 @@
"auto_download_started": "Téléchargement automatique lancé",
"external_url_ready": "URL reçue et prête à être téléchargée",
"external_url_queued": "Téléchargement ajouté depuis l'extension Chrome",
+ "hotkey_queued": "Téléchargement lancé depuis le presse-papiers",
+ "hotkey_already_queued": "Ce lien est déjà dans la file",
+ "hotkey_not_a_url": "Copiez d'abord un lien — le presse-papiers ne contient aucune adresse",
+ "hotkey_unsupported": "Aucun téléchargeur ne gère ce lien. Collez-le sur l'écran d'accueil pour voir les options.",
+ "hotkey_clipboard_error": "Impossible de lire le presse-papiers. Recopiez le lien puis réessayez le raccourci.",
"channel_new": "{{channel}} : {{count}} nouvelle(s) vidéo(s)",
"channel_new_auto": "{{channel}} : téléchargement de {{count}} nouvelle(s) vidéo(s)",
"file_copied_to_clipboard": "Fichier copié dans le presse-papiers",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Obsolète",
+ "outdated_hint": "Cette version n'a pas les correctifs de sécurité déjà publiés. Utilisez Mettre à jour pour obtenir la version actuelle.",
"status_missing": "Missing",
"not_found": "non trouvé",
"install": "Installer",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 002207e3..b6d89116 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -446,6 +446,11 @@
"auto_download_started": "Download automatico avviato",
"external_url_ready": "URL ricevuto e pronto per il download",
"external_url_queued": "Download aggiunto dall'estensione Chrome",
+ "hotkey_queued": "Download avviato dagli appunti",
+ "hotkey_already_queued": "Questo link è già in coda",
+ "hotkey_not_a_url": "Copia prima un link: negli appunti non c'è nessun indirizzo",
+ "hotkey_unsupported": "Nessun downloader gestisce questo link. Incollalo nella schermata iniziale per vedere le opzioni.",
+ "hotkey_clipboard_error": "Non è stato possibile leggere gli appunti. Copia di nuovo il link e usa la scorciatoia.",
"channel_new": "{{channel}}: {{count}} nuovo/i video",
"channel_new_auto": "{{channel}}: download di {{count}} nuovo/i video",
"file_copied_to_clipboard": "File copiato negli appunti",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Non aggiornato",
+ "outdated_hint": "Questa versione non ha le correzioni di sicurezza già pubblicate. Usa Aggiorna per ottenere quella attuale.",
"status_missing": "Missing",
"not_found": "non trovato",
"install": "Installa",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index d6c31b21..b5c7a762 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -446,6 +446,11 @@
"auto_download_started": "自動ダウンロードを開始しました",
"external_url_ready": "URLを受信し、ダウンロードの準備ができました",
"external_url_queued": "Chrome拡張機能からダウンロードを追加しました",
+ "hotkey_queued": "クリップボードのリンクをダウンロードに追加しました",
+ "hotkey_already_queued": "そのリンクはすでにキューにあります",
+ "hotkey_not_a_url": "先にリンクをコピーしてください。クリップボードにURLがありません",
+ "hotkey_unsupported": "そのリンクに対応するダウンローダーがありません。ホーム画面に貼り付けて選択肢を確認してください。",
+ "hotkey_clipboard_error": "クリップボードを読み取れませんでした。リンクをコピーし直してショートカットを押してください。",
"channel_new": "{{channel}}:新着動画 {{count}} 件",
"channel_new_auto": "{{channel}}:新着動画 {{count}} 件をダウンロード中",
"file_copied_to_clipboard": "ファイルをクリップボードにコピーしました",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "更新が必要",
+ "outdated_hint": "このバージョンには公開済みのセキュリティ修正が含まれていません。「更新」で最新版を取得してください。",
"status_missing": "Missing",
"not_found": "見つかりません",
"install": "インストール",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index 0066669c..412780e8 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -1170,12 +1170,14 @@ export type TranslationKeys =
| 'settings.dependencies.more_options'
| 'settings.dependencies.not_found'
| 'settings.dependencies.open_folder_failed'
+ | 'settings.dependencies.outdated_hint'
| 'settings.dependencies.pick_custom_file'
| 'settings.dependencies.pick_dialog_title'
| 'settings.dependencies.set_file_failed'
| 'settings.dependencies.show_folder'
| 'settings.dependencies.status_installed'
| 'settings.dependencies.status_missing'
+ | 'settings.dependencies.status_outdated'
| 'settings.dependencies.system_font_suffix'
| 'settings.dependencies.title'
| 'settings.dependencies.update'
@@ -3448,6 +3450,11 @@ export type TranslationKeys =
| 'toast.external_url_ready'
| 'toast.file_copied_to_clipboard'
| 'toast.generic_download_complete'
+ | 'toast.hotkey_already_queued'
+ | 'toast.hotkey_clipboard_error'
+ | 'toast.hotkey_not_a_url'
+ | 'toast.hotkey_queued'
+ | 'toast.hotkey_unsupported'
| 'tools.cc_chapters'
| 'tools.cc_comments'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index 24d882ba..ea56516d 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -446,6 +446,11 @@
"auto_download_started": "Download automático iniciado",
"external_url_ready": "URL recebida e pronta para download",
"external_url_queued": "Download adicionado pela extensão do Chrome",
+ "hotkey_queued": "Download iniciado a partir da área de transferência",
+ "hotkey_already_queued": "Esse link já está na fila",
+ "hotkey_not_a_url": "Copie um link primeiro — não há nenhum endereço na área de transferência",
+ "hotkey_unsupported": "Nenhum downloader cobre esse link. Cole na tela inicial para ver as opções.",
+ "hotkey_clipboard_error": "Não consegui ler a área de transferência. Copie o link de novo e use o atalho.",
"channel_new": "{{channel}}: {{count}} vídeo(s) novo(s)",
"channel_new_auto": "{{channel}}: baixando {{count}} vídeo(s) novo(s)",
"file_copied_to_clipboard": "Arquivo copiado para o clipboard",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "Desatualizado",
+ "outdated_hint": "Esta versão não tem correções de segurança já publicadas. Use Atualizar para pegar a atual.",
"status_missing": "Missing",
"not_found": "não encontrado",
"install": "Instalar",
diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.json
index 4abc05aa..a97afb1e 100644
--- a/src/lib/i18n/ru.json
+++ b/src/lib/i18n/ru.json
@@ -446,6 +446,11 @@
"auto_download_started": "Автозагрузка начата",
"external_url_ready": "URL получен, готов к скачиванию",
"external_url_queued": "Загрузка добавлена из расширения Chrome",
+ "hotkey_queued": "Загрузка запущена из буфера обмена",
+ "hotkey_already_queued": "Эта ссылка уже в очереди",
+ "hotkey_not_a_url": "Сначала скопируйте ссылку — в буфере обмена нет адреса",
+ "hotkey_unsupported": "Для этой ссылки нет подходящего загрузчика. Вставьте её на главном экране, чтобы увидеть варианты.",
+ "hotkey_clipboard_error": "Не удалось прочитать буфер обмена. Скопируйте ссылку заново и нажмите сочетание клавиш.",
"channel_new": "{{channel}}: новых видео — {{count}}",
"channel_new_auto": "{{channel}}: скачивание новых видео ({{count}})",
"file_copied_to_clipboard": "Файл скопирован в буфер обмена",
@@ -710,6 +715,8 @@
"col_status": "Статус",
"col_action": "Действие",
"status_installed": "Установлено",
+ "status_outdated": "Устарело",
+ "outdated_hint": "В этой версии нет уже опубликованных исправлений безопасности. Нажмите «Обновить», чтобы получить актуальную.",
"status_missing": "Отсутствует",
"not_found": "не найдено",
"install": "Установить",
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index af5e34a1..414535e0 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -446,6 +446,11 @@
"auto_download_started": "已啟動自動下載",
"external_url_ready": "已收到 URL,可以开始下载",
"external_url_queued": "已从 Chrome 扩展添加下载",
+ "hotkey_queued": "已從剪貼簿開始下載",
+ "hotkey_already_queued": "該連結已在佇列中",
+ "hotkey_not_a_url": "請先複製一個連結——剪貼簿裡沒有網址",
+ "hotkey_unsupported": "沒有下載器支援該連結。請在首頁貼上以查看可用選項。",
+ "hotkey_clipboard_error": "無法讀取剪貼簿。請重新複製連結後再按快速鍵。",
"channel_new": "{{channel}}:{{count}} 個新影片",
"channel_new_auto": "{{channel}}:正在下載 {{count}} 個新影片",
"file_copied_to_clipboard": "檔案已複製到剪貼簿",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "已過時",
+ "outdated_hint": "此版本缺少已發布的安全修復。請點選「更新」取得目前版本。",
"status_missing": "Missing",
"not_found": "找不到",
"install": "安裝",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index 8d0d3b2f..fb8f00c1 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -446,6 +446,11 @@
"auto_download_started": "已启动自动下载",
"external_url_ready": "已收到 URL,可以开始下载",
"external_url_queued": "已从 Chrome 扩展添加下载",
+ "hotkey_queued": "已从剪贴板开始下载",
+ "hotkey_already_queued": "该链接已在队列中",
+ "hotkey_not_a_url": "请先复制一个链接——剪贴板里没有网址",
+ "hotkey_unsupported": "没有下载器支持该链接。请在首页粘贴以查看可用选项。",
+ "hotkey_clipboard_error": "无法读取剪贴板。请重新复制链接后再按快捷键。",
"channel_new": "{{channel}}:{{count}} 个新视频",
"channel_new_auto": "{{channel}}:正在下载 {{count}} 个新视频",
"file_copied_to_clipboard": "文件已复制到剪贴板",
@@ -710,6 +715,8 @@
"col_status": "Status",
"col_action": "Action",
"status_installed": "Installed",
+ "status_outdated": "已过时",
+ "outdated_hint": "此版本缺少已发布的安全修复。请点击“更新”获取当前版本。",
"status_missing": "Missing",
"not_found": "未找到",
"install": "安装",
diff --git a/src/lib/style/macos-shell.css b/src/lib/style/macos-shell.css
index ae2d35f3..c12235ad 100644
--- a/src/lib/style/macos-shell.css
+++ b/src/lib/style/macos-shell.css
@@ -1,627 +1,629 @@
-[data-shell="mac"] {
- --sidebar-width: 220px; --titlebar-height: 44px;
- --toolbar-height: 44px;
- --inspector-width: 320px;
-
- --font-display: -apple-system, BlinkMacSystemFont, 'SF Pro Display', system-ui, sans-serif;
- --font-body: -apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif;
-
- --radius-xs: 4px;
- --radius-sm: 6px;
- --radius-md: 8px;
- --radius-lg: 10px;
-}
-
-[data-shell="mac"][data-theme="light"],
-[data-shell="mac"][data-theme="catppuccin-latte"],
-[data-shell="mac"][data-theme="eink-day"],
-[data-shell="mac"][data-theme="eink-sepia"],
-[data-shell="mac"][data-theme="nyxvamp-radiance"] {
- --sidebar-bg: #EBEBED;
- --sidebar-highlight: #E0E0E4;
- --content-border: #D1D1D6;
- --primary: #F5F5F7;
- --secondary: #1D1D1F;
- --tertiary: #8E8E93;
- --accent: #007AFF;
- --button: #FFFFFF;
- --button-hover: #F0F0F2;
- --button-press: #E5E5EA;
- --button-elevated: #FFFFFF;
- --button-elevated-hover: #F5F5F7;
- --input-bg: #FFFFFF;
- --input-border: #D1D1D6;
- --cta: #007AFF;
- --on-cta: #FFFFFF;
-}
-
-[data-shell="mac"][data-theme="dark"],
-[data-shell="mac"][data-theme="system"] {
- color-scheme: dark;
-}
-
-[data-shell="mac"][data-theme="dark"],
-[data-shell="mac"]:not([data-theme="light"]):not([data-theme="catppuccin-latte"]):not([data-theme="eink-day"]):not([data-theme="eink-sepia"]):not([data-theme="nyxvamp-radiance"]) {
- --sidebar-bg: #252527;
- --sidebar-highlight: #2C2C2E;
- --content-border: #38383A;
- --primary: #1C1C1E;
- --secondary: #F5F5F7;
- --tertiary: #8E8E93;
- --accent: #0A84FF;
- --button: #2C2C2E;
- --button-hover: #3A3A3C;
- --button-press: #48484A;
- --button-elevated: #2C2C2E;
- --button-elevated-hover: #3A3A3C;
- --input-bg: #1C1C1E;
- --input-border: #48484A;
- --cta: #0A84FF;
- --on-cta: #FFFFFF;
-}
-
-.mac-shell {
- display: flex;
- flex-direction: column;
- height: 100vh;
- overflow: hidden;
- background: var(--bg);
-}
-
-.mac-shell-body {
- display: flex;
- flex: 1;
- min-height: 0;
- overflow: hidden;
-}
-
-.mac-titlebar {
- display: flex;
- align-items: center;
- height: var(--titlebar-height);
- padding: 0 var(--space-4);
- padding-left: calc(var(--space-4) + 78px);
- border-bottom: 1px solid var(--border);
- background: var(--bg);
- flex-shrink: 0;
- -webkit-app-region: drag;
- user-select: none;
-}
-
-.mac-titlebar-title {
- font-size: var(--text-md);
- font-weight: 600;
- color: var(--text);
- letter-spacing: -0.01em;
-}
-
-.mac-titlebar-actions {
- margin-left: auto;
- display: flex;
- align-items: center;
- gap: var(--space-2);
- -webkit-app-region: no-drag;
-}
-
-.mac-toolbar {
- display: flex;
- align-items: center;
- gap: var(--space-3);
- min-height: var(--toolbar-height);
- padding: var(--space-2) var(--space-5);
- border-bottom: 1px solid var(--border);
- background: var(--surface);
- flex-shrink: 0;
-}
-
-.mac-content {
- flex: 1;
- overflow-y: auto;
- padding: var(--space-4);
- min-width: 0;
-}
-
-.mac-content--home {
- padding: var(--space-3);
- display: flex;
- flex-direction: column;
- min-height: 0;
-}
-
-.mac-content--pane {
- padding: 0;
- display: flex;
- flex-direction: column;
- min-height: 0;
- overflow: hidden;
-}
-
-.mac-source-list {
- width: var(--sidebar-width);
- min-width: var(--sidebar-width);
- display: flex;
- flex-direction: column;
- background: var(--sidebar-bg);
- border-right: 1px solid var(--border);
- padding: var(--space-3) var(--space-2);
- overflow-y: auto;
- flex-shrink: 0;
-}
-
-.mac-nav-section {
- margin-bottom: var(--space-3);
-}
-
-.mac-nav-section-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: var(--space-1) var(--space-3);
- font-size: 11px;
- font-weight: 600;
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--text-dim);
-}
-
-.mac-nav-item {
- display: flex;
- align-items: center;
- gap: var(--space-3);
- padding: 6px var(--space-3);
- border-radius: var(--radius-sm);
- color: var(--text);
- font-size: var(--text-base);
- font-weight: 500;
- text-decoration: none;
- transition: background var(--duration-fast) var(--ease-out), color var(--duration-fast) var(--ease-out);
- position: relative;
-}
-
-@media (hover: hover) {
- .mac-nav-item:hover {
- background: var(--sidebar-highlight);
- }
-}
-
-.mac-nav-item.active {
- background: color-mix(in srgb, var(--accent) 18%, transparent);
- color: var(--accent);
-}
-
-.mac-nav-item:focus-visible {
- outline: var(--focus-ring);
- outline-offset: var(--focus-ring-offset);
-}
-
-.mac-nav-label {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.mac-nav-badge {
- min-width: 18px;
- height: 18px;
- padding: 0 5px;
- font-size: 11px;
- font-weight: 600;
- line-height: 18px;
- text-align: center;
- color: var(--on-accent);
- background: var(--accent);
- border-radius: var(--radius-full);
-}
-
-.mac-plugins-toggle {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 22px;
- height: 22px;
- border: none;
- background: transparent;
- color: var(--text-dim);
- border-radius: var(--radius-xs);
- cursor: pointer;
- padding: 0;
-}
-
-@media (hover: hover) {
- .mac-plugins-toggle:hover {
- background: var(--sidebar-highlight);
- color: var(--text);
- }
-}
-
-.mac-segmented {
- display: inline-flex;
- padding: 2px;
- background: var(--surface-mut);
- border-radius: var(--radius-md);
- border: 1px solid var(--border);
-}
-
-.mac-segmented-btn {
- padding: 5px 12px;
- font-size: var(--text-sm);
- font-weight: 500;
- border: none;
- background: transparent;
- color: var(--text-muted);
- border-radius: calc(var(--radius-md) - 2px);
- cursor: pointer;
- transition: background var(--duration-fast) var(--ease-out), color var(--duration-fast) var(--ease-out), box-shadow var(--duration-fast) var(--ease-out);
-}
-
-.mac-segmented-btn.active {
- background: var(--surface);
- color: var(--text);
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
-}
-
-.mac-inspector {
- width: var(--inspector-width);
- min-width: var(--inspector-width);
- border-left: 1px solid var(--border);
- background: var(--surface);
- overflow-y: auto;
- padding: var(--space-4);
- flex-shrink: 0;
-}
-
-.mac-command-backdrop {
- position: fixed;
- inset: 0;
- background: color-mix(in srgb, var(--bg) 40%, transparent);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- z-index: 200;
- display: flex;
- align-items: flex-start;
- justify-content: center;
- padding-top: 18vh;
-}
-
-.mac-command-palette {
- width: min(560px, calc(100vw - 48px));
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: var(--radius-lg);
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.22);
- overflow: hidden;
-}
-
-.mac-command-input-row {
- display: flex;
- align-items: center;
- gap: var(--space-3);
- padding: var(--space-3) var(--space-4);
- border-bottom: 1px solid var(--border);
-}
-
-.mac-command-input {
- flex: 1;
- border: none;
- background: transparent;
- font-size: var(--text-md);
- color: var(--text);
- outline: none;
-}
-
-.mac-command-input::placeholder {
- color: var(--text-dim);
-}
-
-.mac-command-list {
- max-height: 320px;
- overflow-y: auto;
- padding: var(--space-2);
-}
-
-.mac-command-item {
- display: flex;
- align-items: center;
- gap: var(--space-3);
- width: 100%;
- padding: 8px var(--space-3);
- border: none;
- background: transparent;
- border-radius: var(--radius-sm);
- color: var(--text);
- font-size: var(--text-base);
- text-align: left;
- cursor: pointer;
-}
-
-@media (hover: hover) {
- .mac-command-item:hover {
- background: color-mix(in srgb, var(--accent) 12%, transparent);
- }
-}
-
-.mac-command-item.selected {
- background: color-mix(in srgb, var(--accent) 18%, transparent);
-}
-
-.mac-command-footer {
- display: flex;
- gap: var(--space-4);
- padding: var(--space-2) var(--space-4);
- border-top: 1px solid var(--border);
- font-size: 11px;
- color: var(--text-dim);
-}
-
-.mac-kbd {
- display: inline-flex;
- align-items: center;
- padding: 1px 5px;
- border-radius: 4px;
- background: var(--surface-mut);
- border: 1px solid var(--border);
- font-size: 10px;
- font-family: var(--font-mono);
-}
-
-.settings-mac {
- display: flex;
- flex-direction: column;
- flex: 1;
- min-height: 0;
- gap: 0;
-}
-
-.settings-mac-sidebar {
- width: 200px;
- flex-shrink: 0;
- padding: var(--space-2);
- border-right: 1px solid var(--border);
- overflow-y: auto;
-}
-
-.settings-mac-body {
- display: flex;
- flex: 1;
- min-height: 0;
- overflow: hidden;
-}
-
-.settings-mac-cat {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: var(--space-2);
- width: 100%;
- text-align: left;
- padding: 6px var(--space-3);
- border: none;
- background: transparent;
- border-radius: var(--radius-sm);
- font-size: var(--text-base);
- color: var(--text);
- cursor: pointer;
-}
-
-.settings-mac-cat-label {
- flex: 1;
- min-width: 0;
-}
-
-.settings-mac-cat.search-match {
- color: var(--accent);
- font-weight: 600;
-}
-
-.settings-cat-match-count {
- flex-shrink: 0;
- min-width: 1.25rem;
- padding: 0 6px;
- font-size: 11px;
- font-weight: 600;
- line-height: 1.4;
- text-align: center;
- border-radius: 999px;
- background: color-mix(in srgb, var(--accent) 20%, transparent);
- color: var(--accent);
-}
-
-.settings-mac-cat.active {
- background: color-mix(in srgb, var(--accent) 18%, transparent);
- color: var(--accent);
- font-weight: 600;
-}
-
-.settings-mac-nav-group {
- margin-bottom: var(--space-3);
-}
-
-.settings-mac-nav-group:last-child {
- margin-bottom: 0;
-}
-
-.settings-mac-nav-group .mac-nav-section-header {
- padding-left: var(--space-2);
- padding-right: var(--space-2);
-}
-
-.settings-mac-content {
- flex: 1;
- min-width: 0;
- padding: var(--space-4);
- overflow-y: auto;
-}
-
-.downloads-mac.downloads-page {
- max-width: none;
- margin: 0;
- padding: var(--space-4);
- gap: var(--space-3);
- flex: 1;
- min-height: 0;
- overflow-y: auto;
-}
-
-.downloads-mac .downloads-header {
- gap: var(--space-3);
-}
-
-.downloads-mac .downloads-header:not(:has(.downloads-stats)) {
- justify-content: flex-end;
-}
-
-.downloads-mac .downloads-stats {
- font-size: var(--text-sm);
- color: var(--text-muted);
-}
-
-.downloads-mac .filter-pills {
- width: fit-content;
- max-width: 100%;
-}
-
-.downloads-mac-empty {
- flex: 1;
- min-height: 0;
- padding: var(--space-6) var(--space-4);
- gap: var(--space-4);
-}
-
-.downloads-mac .downloads-empty {
- min-height: 0;
- flex: 1;
- padding: var(--space-6) 0;
-}
-
-.downloads-table-wrap {
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- overflow: hidden;
- background: var(--surface);
-}
-
-.downloads-table {
- width: 100%;
- border-collapse: collapse;
- font-size: var(--text-sm);
-}
-
-.downloads-table th {
- text-align: left;
- padding: 8px var(--space-3);
- font-weight: 600;
- color: var(--text-muted);
- background: var(--surface-mut);
- border-bottom: 1px solid var(--border);
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.03em;
-}
-
-.downloads-table td {
- padding: 10px var(--space-3);
- border-bottom: 1px solid var(--border);
- color: var(--text);
- vertical-align: middle;
-}
-
-.downloads-table tr:last-child td {
- border-bottom: none;
-}
-
-@media (hover: hover) {
- .downloads-table tbody tr:hover {
- background: color-mix(in srgb, var(--accent) 6%, transparent);
- }
-}
-
-.home-mac {
- display: flex;
- flex-direction: column;
- gap: var(--space-3);
- width: 100%;
- flex: 1;
- min-height: 0;
-}
-
-.home-mac-workspace {
- display: flex;
- flex: 0 1 auto;
- gap: 0;
- min-width: 0;
- min-height: 0;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- overflow: visible;
- background: var(--surface);
-}
-
-.home-mac-hero {
- flex-shrink: 0;
- width: 132px;
- padding: var(--space-5) var(--space-3) var(--space-4);
- border-right: 1px solid var(--border);
- display: flex;
- align-items: flex-start;
- justify-content: center;
- background: color-mix(in srgb, var(--surface) 92%, var(--bg));
- overflow: visible;
-}
-
-.home-mac-hero .mascot-bubble {
- max-width: 100%;
- font-size: var(--text-xs);
- padding: var(--space-1) var(--space-2);
- line-height: 1.35;
-}
-
-.home-mac-main {
- flex: 1;
- min-width: 0;
- min-height: 0;
- padding: var(--space-4);
- display: flex;
- flex-direction: column;
- gap: var(--space-3);
- overflow-y: auto;
-}
-
-@media (max-width: 900px) {
- .home-mac-workspace {
- flex-direction: column;
- }
-
- .home-mac-hero {
- width: 100%;
- border-right: none;
- border-bottom: 1px solid var(--border);
- padding: var(--space-3);
- justify-content: flex-start;
- }
-
- .mac-inspector {
- width: 100%;
- min-width: 0;
- border-left: none;
- border-top: 1px solid var(--border);
- }
-}
-
-@media (max-width: 860px) {
- .mac-source-list {
- width: 72px;
- min-width: 72px;
- }
-
- .mac-nav-label,
- .mac-nav-section-header {
- display: none;
- }
-
- .mac-nav-item {
- justify-content: center;
- padding: 8px;
- }
-}
+[data-shell="mac"] {
+ --sidebar-width: 220px; --titlebar-height: 44px;
+ --toolbar-height: 44px;
+ --inspector-width: 320px;
+
+ --font-display: -apple-system, BlinkMacSystemFont, 'SF Pro Display', system-ui, sans-serif;
+ --font-body: -apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif;
+
+ --radius-xs: 4px;
+ --radius-sm: 6px;
+ --radius-md: 8px;
+ --radius-lg: 10px;
+}
+
+[data-shell="mac"][data-theme="light"],
+[data-shell="mac"][data-theme="catppuccin-latte"],
+[data-shell="mac"][data-theme="eink-day"],
+[data-shell="mac"][data-theme="eink-sepia"],
+[data-shell="mac"][data-theme="nyxvamp-radiance"] {
+ --sidebar-bg: #EBEBED;
+ --sidebar-highlight: #E0E0E4;
+ --content-border: #D1D1D6;
+ --primary: #F5F5F7;
+ --secondary: #1D1D1F;
+ --tertiary: #8E8E93;
+ --accent: #007AFF;
+ --button: #FFFFFF;
+ --button-hover: #F0F0F2;
+ --button-press: #E5E5EA;
+ --button-elevated: #FFFFFF;
+ --button-elevated-hover: #F5F5F7;
+ --input-bg: #FFFFFF;
+ --input-border: #D1D1D6;
+ --cta: #007AFF;
+ --on-cta: #FFFFFF;
+}
+
+[data-shell="mac"][data-theme="dark"],
+[data-shell="mac"][data-theme="system"] {
+ color-scheme: dark;
+}
+
+[data-shell="mac"][data-theme="dark"],
+[data-shell="mac"]:not([data-theme="light"]):not([data-theme="catppuccin-latte"]):not([data-theme="eink-day"]):not([data-theme="eink-sepia"]):not([data-theme="nyxvamp-radiance"]) {
+ --sidebar-bg: #252527;
+ --sidebar-highlight: #2C2C2E;
+ --content-border: #38383A;
+ --primary: #1C1C1E;
+ --secondary: #F5F5F7;
+ --tertiary: #8E8E93;
+ --accent: #0A84FF;
+ --button: #2C2C2E;
+ --button-hover: #3A3A3C;
+ --button-press: #48484A;
+ --button-elevated: #2C2C2E;
+ --button-elevated-hover: #3A3A3C;
+ --input-bg: #1C1C1E;
+ --input-border: #48484A;
+ --cta: #0A84FF;
+ --on-cta: #FFFFFF;
+}
+
+.mac-shell {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ overflow: hidden;
+ background: var(--bg);
+}
+
+.mac-shell-body {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.mac-titlebar {
+ display: flex;
+ align-items: center;
+ height: var(--titlebar-height);
+ padding: 0 var(--space-4);
+ padding-left: calc(var(--space-4) + 78px);
+ border-bottom: 1px solid var(--border);
+ background: var(--bg);
+ flex-shrink: 0;
+ /* Arrastar é feito por `data-tauri-drag-region` no markup, não por
+ `-webkit-app-region` — essa propriedade é do Chromium/Electron e o
+ WKWebView do macOS a ignora, o que deixava a janela impossível de
+ arrastar. */
+ user-select: none;
+}
+
+.mac-titlebar-title {
+ font-size: var(--text-md);
+ font-weight: 600;
+ color: var(--text);
+ letter-spacing: -0.01em;
+}
+
+.mac-titlebar-actions {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.mac-toolbar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ min-height: var(--toolbar-height);
+ padding: var(--space-2) var(--space-5);
+ border-bottom: 1px solid var(--border);
+ background: var(--surface);
+ flex-shrink: 0;
+}
+
+.mac-content {
+ flex: 1;
+ overflow-y: auto;
+ padding: var(--space-4);
+ min-width: 0;
+}
+
+.mac-content--home {
+ padding: var(--space-3);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.mac-content--pane {
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.mac-source-list {
+ width: var(--sidebar-width);
+ min-width: var(--sidebar-width);
+ display: flex;
+ flex-direction: column;
+ background: var(--sidebar-bg);
+ border-right: 1px solid var(--border);
+ padding: var(--space-3) var(--space-2);
+ overflow-y: auto;
+ flex-shrink: 0;
+}
+
+.mac-nav-section {
+ margin-bottom: var(--space-3);
+}
+
+.mac-nav-section-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-1) var(--space-3);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-dim);
+}
+
+.mac-nav-item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ padding: 6px var(--space-3);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-size: var(--text-base);
+ font-weight: 500;
+ text-decoration: none;
+ transition: background var(--duration-fast) var(--ease-out), color var(--duration-fast) var(--ease-out);
+ position: relative;
+}
+
+@media (hover: hover) {
+ .mac-nav-item:hover {
+ background: var(--sidebar-highlight);
+ }
+}
+
+.mac-nav-item.active {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+}
+
+.mac-nav-item:focus-visible {
+ outline: var(--focus-ring);
+ outline-offset: var(--focus-ring-offset);
+}
+
+.mac-nav-label {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.mac-nav-badge {
+ min-width: 18px;
+ height: 18px;
+ padding: 0 5px;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 18px;
+ text-align: center;
+ color: var(--on-accent);
+ background: var(--accent);
+ border-radius: var(--radius-full);
+}
+
+.mac-plugins-toggle {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ border: none;
+ background: transparent;
+ color: var(--text-dim);
+ border-radius: var(--radius-xs);
+ cursor: pointer;
+ padding: 0;
+}
+
+@media (hover: hover) {
+ .mac-plugins-toggle:hover {
+ background: var(--sidebar-highlight);
+ color: var(--text);
+ }
+}
+
+.mac-segmented {
+ display: inline-flex;
+ padding: 2px;
+ background: var(--surface-mut);
+ border-radius: var(--radius-md);
+ border: 1px solid var(--border);
+}
+
+.mac-segmented-btn {
+ padding: 5px 12px;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ border: none;
+ background: transparent;
+ color: var(--text-muted);
+ border-radius: calc(var(--radius-md) - 2px);
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-out), color var(--duration-fast) var(--ease-out), box-shadow var(--duration-fast) var(--ease-out);
+}
+
+.mac-segmented-btn.active {
+ background: var(--surface);
+ color: var(--text);
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
+}
+
+.mac-inspector {
+ width: var(--inspector-width);
+ min-width: var(--inspector-width);
+ border-left: 1px solid var(--border);
+ background: var(--surface);
+ overflow-y: auto;
+ padding: var(--space-4);
+ flex-shrink: 0;
+}
+
+.mac-command-backdrop {
+ position: fixed;
+ inset: 0;
+ background: color-mix(in srgb, var(--bg) 40%, transparent);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ z-index: 200;
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ padding-top: 18vh;
+}
+
+.mac-command-palette {
+ width: min(560px, calc(100vw - 48px));
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-lg);
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.22);
+ overflow: hidden;
+}
+
+.mac-command-input-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ padding: var(--space-3) var(--space-4);
+ border-bottom: 1px solid var(--border);
+}
+
+.mac-command-input {
+ flex: 1;
+ border: none;
+ background: transparent;
+ font-size: var(--text-md);
+ color: var(--text);
+ outline: none;
+}
+
+.mac-command-input::placeholder {
+ color: var(--text-dim);
+}
+
+.mac-command-list {
+ max-height: 320px;
+ overflow-y: auto;
+ padding: var(--space-2);
+}
+
+.mac-command-item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ width: 100%;
+ padding: 8px var(--space-3);
+ border: none;
+ background: transparent;
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-size: var(--text-base);
+ text-align: left;
+ cursor: pointer;
+}
+
+@media (hover: hover) {
+ .mac-command-item:hover {
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ }
+}
+
+.mac-command-item.selected {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+}
+
+.mac-command-footer {
+ display: flex;
+ gap: var(--space-4);
+ padding: var(--space-2) var(--space-4);
+ border-top: 1px solid var(--border);
+ font-size: 11px;
+ color: var(--text-dim);
+}
+
+.mac-kbd {
+ display: inline-flex;
+ align-items: center;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--surface-mut);
+ border: 1px solid var(--border);
+ font-size: 10px;
+ font-family: var(--font-mono);
+}
+
+.settings-mac {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+ gap: 0;
+}
+
+.settings-mac-sidebar {
+ width: 200px;
+ flex-shrink: 0;
+ padding: var(--space-2);
+ border-right: 1px solid var(--border);
+ overflow-y: auto;
+}
+
+.settings-mac-body {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ overflow: hidden;
+}
+
+.settings-mac-cat {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ width: 100%;
+ text-align: left;
+ padding: 6px var(--space-3);
+ border: none;
+ background: transparent;
+ border-radius: var(--radius-sm);
+ font-size: var(--text-base);
+ color: var(--text);
+ cursor: pointer;
+}
+
+.settings-mac-cat-label {
+ flex: 1;
+ min-width: 0;
+}
+
+.settings-mac-cat.search-match {
+ color: var(--accent);
+ font-weight: 600;
+}
+
+.settings-cat-match-count {
+ flex-shrink: 0;
+ min-width: 1.25rem;
+ padding: 0 6px;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1.4;
+ text-align: center;
+ border-radius: 999px;
+ background: color-mix(in srgb, var(--accent) 20%, transparent);
+ color: var(--accent);
+}
+
+.settings-mac-cat.active {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ color: var(--accent);
+ font-weight: 600;
+}
+
+.settings-mac-nav-group {
+ margin-bottom: var(--space-3);
+}
+
+.settings-mac-nav-group:last-child {
+ margin-bottom: 0;
+}
+
+.settings-mac-nav-group .mac-nav-section-header {
+ padding-left: var(--space-2);
+ padding-right: var(--space-2);
+}
+
+.settings-mac-content {
+ flex: 1;
+ min-width: 0;
+ padding: var(--space-4);
+ overflow-y: auto;
+}
+
+.downloads-mac.downloads-page {
+ max-width: none;
+ margin: 0;
+ padding: var(--space-4);
+ gap: var(--space-3);
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+}
+
+.downloads-mac .downloads-header {
+ gap: var(--space-3);
+}
+
+.downloads-mac .downloads-header:not(:has(.downloads-stats)) {
+ justify-content: flex-end;
+}
+
+.downloads-mac .downloads-stats {
+ font-size: var(--text-sm);
+ color: var(--text-muted);
+}
+
+.downloads-mac .filter-pills {
+ width: fit-content;
+ max-width: 100%;
+}
+
+.downloads-mac-empty {
+ flex: 1;
+ min-height: 0;
+ padding: var(--space-6) var(--space-4);
+ gap: var(--space-4);
+}
+
+.downloads-mac .downloads-empty {
+ min-height: 0;
+ flex: 1;
+ padding: var(--space-6) 0;
+}
+
+.downloads-table-wrap {
+ border: 1px solid var(--border);
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ background: var(--surface);
+}
+
+.downloads-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: var(--text-sm);
+}
+
+.downloads-table th {
+ text-align: left;
+ padding: 8px var(--space-3);
+ font-weight: 600;
+ color: var(--text-muted);
+ background: var(--surface-mut);
+ border-bottom: 1px solid var(--border);
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+}
+
+.downloads-table td {
+ padding: 10px var(--space-3);
+ border-bottom: 1px solid var(--border);
+ color: var(--text);
+ vertical-align: middle;
+}
+
+.downloads-table tr:last-child td {
+ border-bottom: none;
+}
+
+@media (hover: hover) {
+ .downloads-table tbody tr:hover {
+ background: color-mix(in srgb, var(--accent) 6%, transparent);
+ }
+}
+
+.home-mac {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ width: 100%;
+ flex: 1;
+ min-height: 0;
+}
+
+.home-mac-workspace {
+ display: flex;
+ flex: 0 1 auto;
+ gap: 0;
+ min-width: 0;
+ min-height: 0;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-md);
+ overflow: visible;
+ background: var(--surface);
+}
+
+.home-mac-hero {
+ flex-shrink: 0;
+ width: 132px;
+ padding: var(--space-5) var(--space-3) var(--space-4);
+ border-right: 1px solid var(--border);
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ background: color-mix(in srgb, var(--surface) 92%, var(--bg));
+ overflow: visible;
+}
+
+.home-mac-hero .mascot-bubble {
+ max-width: 100%;
+ font-size: var(--text-xs);
+ padding: var(--space-1) var(--space-2);
+ line-height: 1.35;
+}
+
+.home-mac-main {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ padding: var(--space-4);
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ overflow-y: auto;
+}
+
+@media (max-width: 900px) {
+ .home-mac-workspace {
+ flex-direction: column;
+ }
+
+ .home-mac-hero {
+ width: 100%;
+ border-right: none;
+ border-bottom: 1px solid var(--border);
+ padding: var(--space-3);
+ justify-content: flex-start;
+ }
+
+ .mac-inspector {
+ width: 100%;
+ min-width: 0;
+ border-left: none;
+ border-top: 1px solid var(--border);
+ }
+}
+
+@media (max-width: 860px) {
+ .mac-source-list {
+ width: 72px;
+ min-width: 72px;
+ }
+
+ .mac-nav-label,
+ .mac-nav-section-header {
+ display: none;
+ }
+
+ .mac-nav-item {
+ justify-content: center;
+ padding: 8px;
+ }
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 32a940f6..4a9dde15 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -1,440 +1,454 @@
-<script lang="ts">
- import "../app.css";
- import "$lib/style/queue-kinds.css";
- import { page } from "$app/state";
- import { goto } from "$app/navigation";
- import { onMount } from "svelte";
- import { invoke } from "@tauri-apps/api/core";
- import { listen } from "@tauri-apps/api/event";
- import { initDownloadListener } from "$lib/stores/download-listener";
- import { getCounts } from "$lib/stores/download-store.svelte";
- import { getSettings } from "$lib/stores/settings-store.svelte";
- import { queueExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";
- import Toast from "$components/toast/Toast.svelte";
- import AppSidebar from "$components/shell/AppSidebar.svelte";
- import AppToolbar from "$components/shell/AppToolbar.svelte";
- import CommandPalette from "$components/shell/CommandPalette.svelte";
- import { setCommandPaletteItems } from "$lib/stores/command-palette-store.svelte";
- import { refreshUpdateInfo } from "$lib/stores/update-store.svelte";
- import { startClipboardMonitor, stopClipboardMonitor } from "$lib/stores/clipboard-monitor";
- import { initChangelog } from "$lib/stores/changelog-store.svelte";
- import { needsOnboarding } from "$lib/stores/onboarding-store.svelte";
- import { isYtdlpAvailable, isDepsChecked, refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
- import { showToast } from "$lib/stores/toast-store.svelte";
- import { ensureTrackerNotifications } from "$lib/tracker-notifications.svelte";
- import { t, locale } from "$lib/i18n";
- import { get } from "svelte/store";
- import { CORE_NAV_ITEMS, type NavItem } from "$lib/nav-config";
- import {
- STUDY_FOCUS_ENABLED,
- STUDY_PROGRESS_ENABLED,
- STUDY_ACHIEVEMENTS_ENABLED,
- STUDY_NOTES_ENABLED,
- } from "$lib/study-feature-flags";
- import type { Snippet } from "svelte";
- import type { Component } from "svelte";
-
- let pluginNavItems = $state<NavItem[]>([]);
-
- let leagueNavItems = $derived<NavItem[]>(
- getSettings()?.league?.enabled
- ? [{ href: "/league", labelKey: "league.nav", icon: "league", group: "app", order: 45 }]
- : []
- );
-
- let allNav = $derived([...CORE_NAV_ITEMS, ...leagueNavItems, ...pluginNavItems].sort((a, b) => (a.order ?? 50) - (b.order ?? 50)));
- let primaryNav = $derived(allNav.filter((item) => item.group === "primary"));
- let appNav = $derived(allNav.filter((item) => item.group === "app"));
- let pluginNav = $derived(allNav.filter((item) => item.group === "plugins"));
-
- let ytdlpDismissed = $state(false);
- let ytdlpMissing = $derived(isDepsChecked() && !isYtdlpAvailable());
- let showOnboarding = $derived(needsOnboarding());
-
- let counts = $derived(getCounts());
- let badgeLabel = $derived(counts.badge > 99 ? "99+" : String(counts.badge));
- let settings = $derived(getSettings());
-
- let isStudyRoute = $derived(page.url.pathname.startsWith("/study"));
- let isCoreRoute = $derived(
- page.url.pathname === "/" ||
- page.url.pathname.startsWith("/downloads") ||
- page.url.pathname.startsWith("/settings") ||
- page.url.pathname.startsWith("/marketplace") ||
- page.url.pathname.startsWith("/league") ||
- page.url.pathname.startsWith("/about"),
- );
-
- let DebugPanel = $state<Component | null>(null);
- let OnboardingWizard = $state<Component | null>(null);
- let BandwidthPill = $state<Component | null>(null);
- let NotificationBell = $state<Component | null>(null);
- let ChangelogDialog = $state<Component | null>(null);
- let ConfirmCloseDialog = $state<Component | null>(null);
- let ShortcutsDialog = $state<Component | null>(null);
- let LegalDialog = $state<Component | null>(null);
- let RecoveryDialog = $state<Component | null>(null);
- let BilibiliSessionExpiredBanner = $state<Component | null>(null);
-
- function handleExternalUrlEvent(event: Omit<ExternalUrlEvent, "id">) {
- if (event.action === "prefill") {
- queueExternalPrefill(event);
- showToast("info", $t("toast.external_url_ready"));
- if (page.url.pathname !== "/") {
- goto("/");
- }
- return;
- }
-
- if (event.action === "queued") {
- showToast("success", $t("toast.external_url_queued"));
- }
- }
-
- function reloadPluginNav() {
- invoke<{ id: string; enabled: boolean; nav: { route: string; label: Record<string, string>; icon_svg: string | null; group: string; order: number }[] }[]>("list_plugins")
- .then((plugins) => {
- const items: NavItem[] = [];
- for (const p of plugins) {
- if (!p.enabled) continue;
- for (const n of p.nav) {
- if (n.route === "/study/focus" && !STUDY_FOCUS_ENABLED) continue;
- if (n.route === "/study/progress" && !STUDY_PROGRESS_ENABLED) continue;
- if (n.route === "/study/achievements" && !STUDY_ACHIEVEMENTS_ENABLED) continue;
- if (n.route === "/study/notes" && !STUDY_NOTES_ENABLED) continue;
- items.push({
- href: n.route,
- label: n.label[get(locale)] || n.label["en"] || p.id,
- icon: "plugin",
- iconSvg: n.icon_svg || undefined,
- group: "plugins",
- pluginId: p.id,
- order: n.order,
- });
- }
- }
- pluginNavItems = items;
- buildCommandPaletteItems();
- })
- .catch(() => {});
- }
-
- function buildCommandPaletteItems() {
- const navItems = [...CORE_NAV_ITEMS, ...pluginNavItems].map((item) => ({
- id: `nav-${item.href}`,
- label: item.label || (item.labelKey ? get(t)(item.labelKey) : item.href),
- group: get(t)("command_palette.group_nav"),
- keywords: item.href,
- action: () => goto(item.href),
- }));
-
- setCommandPaletteItems([
- ...navItems,
- {
- id: "action-paste",
- label: get(t)("command_palette.action_paste"),
- group: get(t)("command_palette.group_action"),
- keywords: "clipboard url paste",
- action: () => goto("/"),
- },
- {
- id: "action-downloads",
- label: get(t)("command_palette.action_downloads"),
- group: get(t)("command_palette.group_action"),
- keywords: "queue",
- action: () => goto("/downloads"),
- },
- {
- id: "action-settings",
- label: get(t)("command_palette.action_settings"),
- group: get(t)("command_palette.group_action"),
- keywords: "preferences",
- action: () => goto("/settings"),
- },
- ]);
- }
-
- $effect(() => {
- if (settings?.download.clipboard_detection) {
- startClipboardMonitor();
- } else {
- stopClipboardMonitor();
- }
- return () => {
- stopClipboardMonitor();
- };
- });
-
- $effect(() => {
- document.documentElement.setAttribute("data-shell", "mac");
- void $locale;
- buildCommandPaletteItems();
- });
-
- let { children }: { children: Snippet } = $props();
-
- const VACUUM_LAST_RUN_KEY = "study.library.auto_vacuum.last_run";
-
- async function checkAutoVacuum() {
- try {
- const { studySettingsGet, studyLibraryVacuum } = await import("$lib/study-bridge");
- const studySettings = await studySettingsGet();
- const enabled = studySettings.library?.auto_vacuum ?? true;
- if (!enabled) return;
- const intervalDays = studySettings.library?.auto_vacuum_interval_days ?? 30;
- const intervalMs = intervalDays * 86400 * 1000;
- const last = Number(localStorage.getItem(VACUUM_LAST_RUN_KEY) ?? "0");
- const now = Date.now();
- if (now - last < intervalMs) return;
- const result = await studyLibraryVacuum();
- localStorage.setItem(VACUUM_LAST_RUN_KEY, String(now));
- const total =
- (result.seek_logs_deleted ?? 0)
- + (result.notifications_deleted ?? 0)
- + (result.recents_deleted ?? 0);
- if (total > 0) {
- console.info(`[study] auto-vacuum: ${total} items cleaned`, result);
- }
- } catch (e) {
- console.warn("auto-vacuum failed", e);
- }
- }
-
- onMount(() => {
- let cleanup: (() => void) | undefined;
- let unlistenExternal: (() => void) | undefined;
- let unlistenChannels: (() => void) | undefined;
- initDownloadListener().then((fn) => (cleanup = fn));
- setTimeout(() => void checkAutoVacuum(), 5000);
- void ensureTrackerNotifications();
- import("$lib/rpc").then(({ rpcSyncIdleStats }) => rpcSyncIdleStats());
-
- void import("$components/dialog/ChangelogDialog.svelte").then((m) => { ChangelogDialog = m.default; });
- void import("$components/dialog/ConfirmCloseDialog.svelte").then((m) => { ConfirmCloseDialog = m.default; });
- void import("$components/dialog/ShortcutsDialog.svelte").then((m) => { ShortcutsDialog = m.default; });
- void import("$components/dialog/LegalDialog.svelte").then((m) => { LegalDialog = m.default; });
- void import("$components/dialog/RecoveryDialog.svelte").then((m) => { RecoveryDialog = m.default; });
- void import("$lib/components/BilibiliSessionExpiredBanner.svelte").then((m) => { BilibiliSessionExpiredBanner = m.default; });
- if (showOnboarding) {
- void import("$components/onboarding/OnboardingWizard.svelte").then((m) => { OnboardingWizard = m.default; });
- }
- void import("$components/debug/DebugPanel.svelte").then((m) => { DebugPanel = m.default; });
-
- reloadPluginNav();
- listen("plugins-changed", () => { reloadPluginNav(); });
- listen<Omit<ExternalUrlEvent, "id">>("external-url", (event) => {
- handleExternalUrlEvent(event.payload);
- }).then((fn) => {
- unlistenExternal = fn;
- invoke<Omit<ExternalUrlEvent, "id">[]>("register_external_frontend")
- .then((events) => {
- for (const event of events) {
- handleExternalUrlEvent(event);
- }
- })
- .catch(() => {});
- });
- listen<{ channel_title: string; auto_download: boolean; videos: unknown[] }>(
- "channel-new-videos",
- (event) => {
- const p = event.payload;
- const count = p.videos?.length ?? 0;
- if (count <= 0) return;
- showToast(
- "info",
- $t(
- p.auto_download
- ? "toast.channel_new_auto"
- : "toast.channel_new",
- { channel: p.channel_title, count },
- ) as string,
- );
- },
- ).then((fn) => {
- unlistenChannels = fn;
- });
- refreshUpdateInfo();
- initChangelog();
- refreshYtdlpStatus();
-
- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
- const handleChange = () => {
- const s = getSettings();
- if (s?.appearance.theme === "system") {
- document.documentElement.setAttribute("data-theme", mediaQuery.matches ? "dark" : "light");
- }
- };
- mediaQuery.addEventListener("change", handleChange);
-
- return () => {
- cleanup?.();
- unlistenExternal?.();
- unlistenChannels?.();
- mediaQuery.removeEventListener("change", handleChange);
- };
- });
-
- $effect(() => {
- if (isStudyRoute) {
- void import("$lib/study-components/BandwidthPill.svelte").then((m) => { BandwidthPill = m.default; });
- void import("$lib/study-components/shelves/NotificationBell.svelte").then((m) => { NotificationBell = m.default; });
- } else {
- BandwidthPill = null;
- NotificationBell = null;
- }
- });
-</script>
-
-<div class="mac-shell">
- <AppToolbar />
- <div class="mac-shell-body">
- <AppSidebar
- {primaryNav}
- {appNav}
- {pluginNav}
- {badgeLabel}
- badgeCount={counts.badge}
- />
- <main
- class="mac-content"
- class:mac-content--home={page.url.pathname === "/"}
- class:mac-content--pane={
- page.url.pathname.startsWith("/settings") ||
- page.url.pathname.startsWith("/downloads")
- }
- >
- {#if ytdlpMissing && !ytdlpDismissed && isCoreRoute}
- <div class="ytdlp-banner">
- <span class="ytdlp-banner-text">{$t('common.ytdlp_missing')}</span>
- <button class="button ytdlp-banner-link" onclick={() => goto('/settings#dependencies')}>
- {$t('common.go_to_settings')}
- </button>
- <button class="ytdlp-banner-close" onclick={() => ytdlpDismissed = true} aria-label={$t('common.close')}>
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
- </button>
- </div>
- {/if}
- {@render children()}
- </main>
- </div>
-</div>
-
-<CommandPalette />
-
-{#if isStudyRoute && BandwidthPill}
- <div class="bandwidth-pill-mount">
- <BandwidthPill />
- </div>
-{/if}
-
-{#if isStudyRoute && NotificationBell}
- <div class="notification-bell-mount">
- <NotificationBell />
- </div>
-{/if}
-
-<Toast />
-{#if DebugPanel}
- <DebugPanel />
-{/if}
-{#if BilibiliSessionExpiredBanner}
- <BilibiliSessionExpiredBanner />
-{/if}
-{#if ChangelogDialog}
- <ChangelogDialog />
-{/if}
-{#if ConfirmCloseDialog}
- <ConfirmCloseDialog />
-{/if}
-{#if ShortcutsDialog}
- <ShortcutsDialog />
-{/if}
-{#if LegalDialog}
- <LegalDialog />
-{/if}
-{#if RecoveryDialog}
- <RecoveryDialog />
-{/if}
-{#if showOnboarding && OnboardingWizard}
- <OnboardingWizard />
-{/if}
-
-<style>
- .bandwidth-pill-mount {
- position: fixed;
- bottom: 12px;
- right: 12px;
- z-index: 50;
- pointer-events: none;
- }
-
- .notification-bell-mount {
- position: fixed;
- top: calc(var(--titlebar-height) + 8px);
- right: 16px;
- z-index: 60;
- }
-
- .ytdlp-banner {
- display: flex;
- align-items: center;
- gap: 10px;
- padding: 10px 14px;
- margin-bottom: var(--padding);
- background: color-mix(in srgb, var(--warning) 18%, var(--surface));
- color: color-mix(in srgb, var(--warning) 82%, var(--text));
- border: 1px solid color-mix(in srgb, var(--warning) 34%, var(--border));
- border-radius: var(--border-radius);
- font-size: 12.5px;
- font-weight: 500;
- }
-
- :global([data-theme="light"]) .ytdlp-banner,
- :global([data-theme="catppuccin-latte"]) .ytdlp-banner,
- :global([data-theme="eink-day"]) .ytdlp-banner,
- :global([data-theme="eink-sepia"]) .ytdlp-banner,
- :global([data-theme="nyxvamp-radiance"]) .ytdlp-banner {
- color: var(--on-warning);
- }
-
- .ytdlp-banner-text {
- flex: 1;
- }
-
- .ytdlp-banner-link {
- background: var(--warning);
- color: #fff;
- border: none;
- font-size: 12px;
- padding: 4px 10px;
- border-radius: calc(var(--border-radius) - 4px);
- cursor: pointer;
- white-space: nowrap;
- box-shadow: none;
- }
-
- @media (hover: hover) {
- .ytdlp-banner-link:hover {
- background: color-mix(in srgb, var(--warning) 65%, black);
- }
- }
-
- .ytdlp-banner-close {
- background: none;
- border: none;
- color: inherit;
- cursor: pointer;
- padding: 2px;
- opacity: 0.7;
- display: flex;
- align-items: center;
- }
-
- @media (hover: hover) {
- .ytdlp-banner-close:hover {
- opacity: 1;
- }
- }
-</style>
+<script lang="ts">
+ import "../app.css";
+ import "$lib/style/queue-kinds.css";
+ import { page } from "$app/state";
+ import { goto } from "$app/navigation";
+ import { onMount } from "svelte";
+ import { invoke } from "@tauri-apps/api/core";
+ import { listen } from "@tauri-apps/api/event";
+ import { initDownloadListener } from "$lib/stores/download-listener";
+ import { getCounts } from "$lib/stores/download-store.svelte";
+ import { getSettings } from "$lib/stores/settings-store.svelte";
+ import { queueExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";
+ import Toast from "$components/toast/Toast.svelte";
+ import AppSidebar from "$components/shell/AppSidebar.svelte";
+ import AppToolbar from "$components/shell/AppToolbar.svelte";
+ import CommandPalette from "$components/shell/CommandPalette.svelte";
+ import { setCommandPaletteItems } from "$lib/stores/command-palette-store.svelte";
+ import { refreshUpdateInfo } from "$lib/stores/update-store.svelte";
+ import { startClipboardMonitor, stopClipboardMonitor } from "$lib/stores/clipboard-monitor";
+ import { initChangelog } from "$lib/stores/changelog-store.svelte";
+ import { needsOnboarding } from "$lib/stores/onboarding-store.svelte";
+ import { isYtdlpAvailable, isDepsChecked, refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { ensureTrackerNotifications } from "$lib/tracker-notifications.svelte";
+ import { t, locale } from "$lib/i18n";
+ import { get } from "svelte/store";
+ import { CORE_NAV_ITEMS, type NavItem } from "$lib/nav-config";
+ import {
+ STUDY_FOCUS_ENABLED,
+ STUDY_PROGRESS_ENABLED,
+ STUDY_ACHIEVEMENTS_ENABLED,
+ STUDY_NOTES_ENABLED,
+ } from "$lib/study-feature-flags";
+ import type { Snippet } from "svelte";
+ import type { Component } from "svelte";
+
+ let pluginNavItems = $state<NavItem[]>([]);
+
+ let leagueNavItems = $derived<NavItem[]>(
+ getSettings()?.league?.enabled
+ ? [{ href: "/league", labelKey: "league.nav", icon: "league", group: "app", order: 45 }]
+ : []
+ );
+
+ let allNav = $derived([...CORE_NAV_ITEMS, ...leagueNavItems, ...pluginNavItems].sort((a, b) => (a.order ?? 50) - (b.order ?? 50)));
+ let primaryNav = $derived(allNav.filter((item) => item.group === "primary"));
+ let appNav = $derived(allNav.filter((item) => item.group === "app"));
+ let pluginNav = $derived(allNav.filter((item) => item.group === "plugins"));
+
+ let ytdlpDismissed = $state(false);
+ let ytdlpMissing = $derived(isDepsChecked() && !isYtdlpAvailable());
+ let showOnboarding = $derived(needsOnboarding());
+
+ let counts = $derived(getCounts());
+ let badgeLabel = $derived(counts.badge > 99 ? "99+" : String(counts.badge));
+ let settings = $derived(getSettings());
+
+ let isStudyRoute = $derived(page.url.pathname.startsWith("/study"));
+ let isCoreRoute = $derived(
+ page.url.pathname === "/" ||
+ page.url.pathname.startsWith("/downloads") ||
+ page.url.pathname.startsWith("/settings") ||
+ page.url.pathname.startsWith("/marketplace") ||
+ page.url.pathname.startsWith("/league") ||
+ page.url.pathname.startsWith("/about"),
+ );
+
+ let DebugPanel = $state<Component | null>(null);
+ let OnboardingWizard = $state<Component | null>(null);
+ let BandwidthPill = $state<Component | null>(null);
+ let NotificationBell = $state<Component | null>(null);
+ let ChangelogDialog = $state<Component | null>(null);
+ let ConfirmCloseDialog = $state<Component | null>(null);
+ let ShortcutsDialog = $state<Component | null>(null);
+ let LegalDialog = $state<Component | null>(null);
+ let RecoveryDialog = $state<Component | null>(null);
+ let BilibiliSessionExpiredBanner = $state<Component | null>(null);
+
+ function handleExternalUrlEvent(event: Omit<ExternalUrlEvent, "id">) {
+ if (event.action === "prefill") {
+ queueExternalPrefill(event);
+ showToast("info", $t("toast.external_url_ready"));
+ if (page.url.pathname !== "/") {
+ goto("/");
+ }
+ return;
+ }
+
+ if (event.action === "queued") {
+ showToast("success", $t("toast.external_url_queued"));
+ }
+ }
+
+ function reloadPluginNav() {
+ invoke<{ id: string; enabled: boolean; nav: { route: string; label: Record<string, string>; icon_svg: string | null; group: string; order: number }[] }[]>("list_plugins")
+ .then((plugins) => {
+ const items: NavItem[] = [];
+ for (const p of plugins) {
+ if (!p.enabled) continue;
+ for (const n of p.nav) {
+ if (n.route === "/study/focus" && !STUDY_FOCUS_ENABLED) continue;
+ if (n.route === "/study/progress" && !STUDY_PROGRESS_ENABLED) continue;
+ if (n.route === "/study/achievements" && !STUDY_ACHIEVEMENTS_ENABLED) continue;
+ if (n.route === "/study/notes" && !STUDY_NOTES_ENABLED) continue;
+ items.push({
+ href: n.route,
+ label: n.label[get(locale)] || n.label["en"] || p.id,
+ icon: "plugin",
+ iconSvg: n.icon_svg || undefined,
+ group: "plugins",
+ pluginId: p.id,
+ order: n.order,
+ });
+ }
+ }
+ pluginNavItems = items;
+ buildCommandPaletteItems();
+ })
+ .catch(() => {});
+ }
+
+ function buildCommandPaletteItems() {
+ const navItems = [...CORE_NAV_ITEMS, ...pluginNavItems].map((item) => ({
+ id: `nav-${item.href}`,
+ label: item.label || (item.labelKey ? get(t)(item.labelKey) : item.href),
+ group: get(t)("command_palette.group_nav"),
+ keywords: item.href,
+ action: () => goto(item.href),
+ }));
+
+ setCommandPaletteItems([
+ ...navItems,
+ {
+ id: "action-paste",
+ label: get(t)("command_palette.action_paste"),
+ group: get(t)("command_palette.group_action"),
+ keywords: "clipboard url paste",
+ action: () => goto("/"),
+ },
+ {
+ id: "action-downloads",
+ label: get(t)("command_palette.action_downloads"),
+ group: get(t)("command_palette.group_action"),
+ keywords: "queue",
+ action: () => goto("/downloads"),
+ },
+ {
+ id: "action-settings",
+ label: get(t)("command_palette.action_settings"),
+ group: get(t)("command_palette.group_action"),
+ keywords: "preferences",
+ action: () => goto("/settings"),
+ },
+ ]);
+ }
+
+ $effect(() => {
+ if (settings?.download.clipboard_detection) {
+ startClipboardMonitor();
+ } else {
+ stopClipboardMonitor();
+ }
+ return () => {
+ stopClipboardMonitor();
+ };
+ });
+
+ $effect(() => {
+ document.documentElement.setAttribute("data-shell", "mac");
+ void $locale;
+ buildCommandPaletteItems();
+ });
+
+ let { children }: { children: Snippet } = $props();
+
+ const VACUUM_LAST_RUN_KEY = "study.library.auto_vacuum.last_run";
+
+ async function checkAutoVacuum() {
+ try {
+ const { studySettingsGet, studyLibraryVacuum } = await import("$lib/study-bridge");
+ const studySettings = await studySettingsGet();
+ const enabled = studySettings.library?.auto_vacuum ?? true;
+ if (!enabled) return;
+ const intervalDays = studySettings.library?.auto_vacuum_interval_days ?? 30;
+ const intervalMs = intervalDays * 86400 * 1000;
+ const last = Number(localStorage.getItem(VACUUM_LAST_RUN_KEY) ?? "0");
+ const now = Date.now();
+ if (now - last < intervalMs) return;
+ const result = await studyLibraryVacuum();
+ localStorage.setItem(VACUUM_LAST_RUN_KEY, String(now));
+ const total =
+ (result.seek_logs_deleted ?? 0)
+ + (result.notifications_deleted ?? 0)
+ + (result.recents_deleted ?? 0);
+ if (total > 0) {
+ console.info(`[study] auto-vacuum: ${total} items cleaned`, result);
+ }
+ } catch (e) {
+ console.warn("auto-vacuum failed", e);
+ }
+ }
+
+ onMount(() => {
+ let cleanup: (() => void) | undefined;
+ let unlistenExternal: (() => void) | undefined;
+ let unlistenChannels: (() => void) | undefined;
+ initDownloadListener().then((fn) => (cleanup = fn));
+ setTimeout(() => void checkAutoVacuum(), 5000);
+ void ensureTrackerNotifications();
+ import("$lib/rpc").then(({ rpcSyncIdleStats }) => rpcSyncIdleStats());
+
+ void import("$components/dialog/ChangelogDialog.svelte").then((m) => { ChangelogDialog = m.default; });
+ void import("$components/dialog/ConfirmCloseDialog.svelte").then((m) => { ConfirmCloseDialog = m.default; });
+ void import("$components/dialog/ShortcutsDialog.svelte").then((m) => { ShortcutsDialog = m.default; });
+ void import("$components/dialog/LegalDialog.svelte").then((m) => { LegalDialog = m.default; });
+ void import("$components/dialog/RecoveryDialog.svelte").then((m) => { RecoveryDialog = m.default; });
+ void import("$lib/components/BilibiliSessionExpiredBanner.svelte").then((m) => { BilibiliSessionExpiredBanner = m.default; });
+ if (showOnboarding) {
+ void import("$components/onboarding/OnboardingWizard.svelte").then((m) => { OnboardingWizard = m.default; });
+ }
+ void import("$components/debug/DebugPanel.svelte").then((m) => { DebugPanel = m.default; });
+
+ reloadPluginNav();
+ listen("plugins-changed", () => { reloadPluginNav(); });
+ listen<{ outcome: string; url: string | null }>("hotkey-download-result", (event) => {
+ const outcome = event.payload.outcome;
+ if (outcome === "queued") {
+ showToast("success", $t("toast.hotkey_queued"));
+ } else if (outcome === "already_queued") {
+ showToast("info", $t("toast.hotkey_already_queued"));
+ } else if (outcome === "not_a_url") {
+ showToast("info", $t("toast.hotkey_not_a_url"));
+ } else if (outcome === "unsupported") {
+ showToast("error", $t("toast.hotkey_unsupported"));
+ } else {
+ showToast("error", $t("toast.hotkey_clipboard_error"));
+ }
+ });
+ listen<Omit<ExternalUrlEvent, "id">>("external-url", (event) => {
+ handleExternalUrlEvent(event.payload);
+ }).then((fn) => {
+ unlistenExternal = fn;
+ invoke<Omit<ExternalUrlEvent, "id">[]>("register_external_frontend")
+ .then((events) => {
+ for (const event of events) {
+ handleExternalUrlEvent(event);
+ }
+ })
+ .catch(() => {});
+ });
+ listen<{ channel_title: string; auto_download: boolean; videos: unknown[] }>(
+ "channel-new-videos",
+ (event) => {
+ const p = event.payload;
+ const count = p.videos?.length ?? 0;
+ if (count <= 0) return;
+ showToast(
+ "info",
+ $t(
+ p.auto_download
+ ? "toast.channel_new_auto"
+ : "toast.channel_new",
+ { channel: p.channel_title, count },
+ ) as string,
+ );
+ },
+ ).then((fn) => {
+ unlistenChannels = fn;
+ });
+ refreshUpdateInfo();
+ initChangelog();
+ refreshYtdlpStatus();
+
+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
+ const handleChange = () => {
+ const s = getSettings();
+ if (s?.appearance.theme === "system") {
+ document.documentElement.setAttribute("data-theme", mediaQuery.matches ? "dark" : "light");
+ }
+ };
+ mediaQuery.addEventListener("change", handleChange);
+
+ return () => {
+ cleanup?.();
+ unlistenExternal?.();
+ unlistenChannels?.();
+ mediaQuery.removeEventListener("change", handleChange);
+ };
+ });
+
+ $effect(() => {
+ if (isStudyRoute) {
+ void import("$lib/study-components/BandwidthPill.svelte").then((m) => { BandwidthPill = m.default; });
+ void import("$lib/study-components/shelves/NotificationBell.svelte").then((m) => { NotificationBell = m.default; });
+ } else {
+ BandwidthPill = null;
+ NotificationBell = null;
+ }
+ });
+</script>
+
+<div class="mac-shell">
+ <AppToolbar />
+ <div class="mac-shell-body">
+ <AppSidebar
+ {primaryNav}
+ {appNav}
+ {pluginNav}
+ {badgeLabel}
+ badgeCount={counts.badge}
+ />
+ <main
+ class="mac-content"
+ class:mac-content--home={page.url.pathname === "/"}
+ class:mac-content--pane={
+ page.url.pathname.startsWith("/settings") ||
+ page.url.pathname.startsWith("/downloads")
+ }
+ >
+ {#if ytdlpMissing && !ytdlpDismissed && isCoreRoute}
+ <div class="ytdlp-banner">
+ <span class="ytdlp-banner-text">{$t('common.ytdlp_missing')}</span>
+ <button class="button ytdlp-banner-link" onclick={() => goto('/settings#dependencies')}>
+ {$t('common.go_to_settings')}
+ </button>
+ <button class="ytdlp-banner-close" onclick={() => ytdlpDismissed = true} aria-label={$t('common.close')}>
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ {/if}
+ {@render children()}
+ </main>
+ </div>
+</div>
+
+<CommandPalette />
+
+{#if isStudyRoute && BandwidthPill}
+ <div class="bandwidth-pill-mount">
+ <BandwidthPill />
+ </div>
+{/if}
+
+{#if isStudyRoute && NotificationBell}
+ <div class="notification-bell-mount">
+ <NotificationBell />
+ </div>
+{/if}
+
+<Toast />
+{#if DebugPanel}
+ <DebugPanel />
+{/if}
+{#if BilibiliSessionExpiredBanner}
+ <BilibiliSessionExpiredBanner />
+{/if}
+{#if ChangelogDialog}
+ <ChangelogDialog />
+{/if}
+{#if ConfirmCloseDialog}
+ <ConfirmCloseDialog />
+{/if}
+{#if ShortcutsDialog}
+ <ShortcutsDialog />
+{/if}
+{#if LegalDialog}
+ <LegalDialog />
+{/if}
+{#if RecoveryDialog}
+ <RecoveryDialog />
+{/if}
+{#if showOnboarding && OnboardingWizard}
+ <OnboardingWizard />
+{/if}
+
+<style>
+ .bandwidth-pill-mount {
+ position: fixed;
+ bottom: 12px;
+ right: 12px;
+ z-index: 50;
+ pointer-events: none;
+ }
+
+ .notification-bell-mount {
+ position: fixed;
+ top: calc(var(--titlebar-height) + 8px);
+ right: 16px;
+ z-index: 60;
+ }
+
+ .ytdlp-banner {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 14px;
+ margin-bottom: var(--padding);
+ background: color-mix(in srgb, var(--warning) 18%, var(--surface));
+ color: color-mix(in srgb, var(--warning) 82%, var(--text));
+ border: 1px solid color-mix(in srgb, var(--warning) 34%, var(--border));
+ border-radius: var(--border-radius);
+ font-size: 12.5px;
+ font-weight: 500;
+ }
+
+ :global([data-theme="light"]) .ytdlp-banner,
+ :global([data-theme="catppuccin-latte"]) .ytdlp-banner,
+ :global([data-theme="eink-day"]) .ytdlp-banner,
+ :global([data-theme="eink-sepia"]) .ytdlp-banner,
+ :global([data-theme="nyxvamp-radiance"]) .ytdlp-banner {
+ color: var(--on-warning);
+ }
+
+ .ytdlp-banner-text {
+ flex: 1;
+ }
+
+ .ytdlp-banner-link {
+ background: var(--warning);
+ color: #fff;
+ border: none;
+ font-size: 12px;
+ padding: 4px 10px;
+ border-radius: calc(var(--border-radius) - 4px);
+ cursor: pointer;
+ white-space: nowrap;
+ box-shadow: none;
+ }
+
+ @media (hover: hover) {
+ .ytdlp-banner-link:hover {
+ background: color-mix(in srgb, var(--warning) 65%, black);
+ }
+ }
+
+ .ytdlp-banner-close {
+ background: none;
+ border: none;
+ color: inherit;
+ cursor: pointer;
+ padding: 2px;
+ opacity: 0.7;
+ display: flex;
+ align-items: center;
+ }
+
+ @media (hover: hover) {
+ .ytdlp-banner-close:hover {
+ opacity: 1;
+ }
+ }
+</style>
diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte
index ee278856..ca8aa9c0 100644
--- a/src/routes/settings/+page.svelte
+++ b/src/routes/settings/+page.svelte
@@ -1,608 +1,609 @@
-<script lang="ts">
- import { tick } from "svelte";
- import { invoke } from "@tauri-apps/api/core";
- import { open } from "@tauri-apps/plugin-dialog";
- import { t, locale, loadTranslations } from "$lib/i18n";
- import { getSettings, updateSettings, resetSettings } from "$lib/stores/settings-store.svelte";
- import { getUpdateInfo } from "$lib/stores/update-store.svelte";
- import { installUpdate } from "$lib/updater";
- import { showToast } from "$lib/stores/toast-store.svelte";
- import { refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
- import { isDebugEnabled, setDebugEnabled, setDebugPanelOpen } from "$lib/stores/debug-store.svelte";
- import ContextHint from "$components/hints/ContextHint.svelte";
- import SettingsPlugins from "$components/settings/SettingsPlugins.svelte";
- import SettingsAdvanced from "$components/settings/SettingsAdvanced.svelte";
- import SettingsAppearance from "$components/settings/SettingsAppearance.svelte";
- import SettingsNetwork from "$components/settings/SettingsNetwork.svelte";
- import SettingsDownloads from "$components/settings/SettingsDownloads.svelte";
- import SettingsTypography from "$components/settings/SettingsTypography.svelte";
- import SettingsBrowserExtension from "$components/settings/SettingsBrowserExtension.svelte";
- import SettingsCookies from "$components/settings/SettingsCookies.svelte";
- import SettingsChannels from "$components/settings/SettingsChannels.svelte";
- import SettingsAI from "$components/settings/SettingsAI.svelte";
-
- type DependencyStatus = {
- name: string;
- installed: boolean;
- version: string | null;
- };
-
- let settings = $derived(getSettings());
- let updateInfo = $derived(getUpdateInfo());
- let isWindows = typeof navigator !== "undefined" && navigator.userAgent.includes("Windows");
- let resetting = $state(false);
- let updating = $state(false);
- let deps = $state<DependencyStatus[]>([]);
- let installingDep = $state<string | null>(null);
-
- async function loadDeps() {
- try {
- deps = await invoke<DependencyStatus[]>("check_dependencies");
- } catch {}
- }
-
- async function chooseCookieFile() {
- const selected = await open({
- title: "Select cookies.txt file",
- filters: [{ name: "Cookies", extensions: ["txt"] }],
- multiple: false,
- });
- if (selected && typeof selected === "string") {
- await updateSettings({ download: { cookie_file: selected } });
- }
- }
-
- async function handleInstallDep(name: string, variant: string | null = null) {
- const wasInstalled = deps.find((d) => d.name === name)?.installed ?? false;
- installingDep = name;
- try {
- const version = await invoke<string>("install_dependency", { name, variant, force: wasInstalled });
- await loadDeps();
- await refreshYtdlpStatus();
- showToast(
- "success",
- $t(
- wasInstalled ? "settings.dependencies.update_success" : "settings.dependencies.install_success",
- { name, version },
- ) as string,
- );
- } catch (e: any) {
- showToast("error", typeof e === "string" ? e : e.message ?? $t("common.error"));
- } finally {
- installingDep = null;
- }
- }
-
- $effect(() => {
- if (settings) {
- loadDeps();
- }
- });
-
- async function handleUpdate() {
- updating = true;
- try {
- await installUpdate();
- } catch {
- updating = false;
- }
- }
-
- async function changeTheme(value: string) {
- await updateSettings({ appearance: { theme: value } });
- }
-
- const CORE_THEMES = [
- { id: "system", labelKey: "settings.appearance.theme_system", colors: null as string[] | null },
- { id: "light", labelKey: null, label: "Light", colors: ["#fafafa", "#1a1a1a", "#E05500"] },
- { id: "dark", labelKey: null, label: "Dark", colors: ["#0a0a0a", "#e8e8e8", "#FF7D38"] },
- ];
- const MORE_THEMES = [
- { id: "catppuccin-latte", label: "Catppuccin Latte", colors: ["#eff1f5", "#4c4f69", "#1e66f5"] },
- { id: "catppuccin-frappe", label: "Catppuccin Frappé", colors: ["#303446", "#c6d0f5", "#8caaee"] },
- { id: "catppuccin-macchiato", label: "Catppuccin Macchiato", colors: ["#24273a", "#cad3f5", "#8aadf4"] },
- { id: "catppuccin-mocha", label: "Catppuccin Mocha", colors: ["#1e1e2e", "#cdd6f4", "#89b4fa"] },
- { id: "one-dark-pro", label: "One Dark Pro", colors: ["#282c34", "#abb2bf", "#61afef"] },
- { id: "dracula", label: "Dracula", colors: ["#22212C", "#F8F8F2", "#9580FF"] },
- { id: "nyxvamp-veil", label: "NyxVamp Veil", colors: ["#1E1E2E", "#D9E0EE", "#F28FAD"] },
- { id: "nyxvamp-obsidian", label: "NyxVamp Obsidian", colors: ["#000A0F", "#C0C0CE", "#F28FAD"] },
- { id: "nyxvamp-radiance", label: "NyxVamp Radiance", colors: ["#F7F7FF", "#1E1E2E", "#9655FF"] },
- { id: "eink-day", label: "E-ink Day", colors: ["#f5f2ea", "#1d1d1b", "#2b2b28"] },
- { id: "eink-sepia", label: "E-ink Sepia", colors: ["#f0e6d2", "#3f2e20", "#7a4a22"] },
- { id: "eink-night", label: "E-ink Night", colors: ["#0a0a0a", "#d4d4d0", "#b0b0ab"] },
- ];
- const MORE_THEME_IDS = new Set(MORE_THEMES.map((t) => t.id));
- let selectedInMore = $derived(MORE_THEME_IDS.has(settings?.appearance?.theme ?? ""));
-
- async function changeLanguage(e: Event) {
- const value = (e.target as HTMLSelectElement).value;
- await updateSettings({ appearance: { language: value } });
- await loadTranslations(value, "/settings");
- locale.set(value);
- }
-
- async function chooseFolder() {
- const selected = await open({ directory: true, title: $t("settings.download.default_output_dir") });
- if (selected) {
- await updateSettings({ download: { default_output_dir: selected } });
- }
- }
-
- async function toggleBool(section: string, key: string, current: boolean) {
- await updateSettings({ [section]: { [key]: !current } });
- }
-
- async function changeNumber(section: string, key: string, e: Event) {
- const value = parseInt((e.target as HTMLInputElement).value, 10);
- if (!isNaN(value) && value > 0) {
- await updateSettings({ [section]: { [key]: value } });
- if (key === "max_concurrent_downloads") {
- try {
- await invoke("update_max_concurrent", { max: value });
- } catch {}
- }
- }
- }
-
- async function changeQuality(e: Event) {
- const value = (e.target as HTMLSelectElement).value;
- await updateSettings({ download: { video_quality: value } });
- }
-
- type SettingsCategory = "downloads" | "appearance" | "typography" | "network" | "cookies" | "channels" | "ai" | "plugins" | "advanced";
-
- const SETTINGS_NAV_GROUPS: {
- labelKey: string;
- items: [SettingsCategory, string][];
- }[] = [
- {
- labelKey: "settings.group_general",
- items: [
- ["appearance", "settings.cat_appearance"],
- ["typography", "settings.cat_typography"],
- ],
- },
- {
- labelKey: "settings.group_media",
- items: [["downloads", "settings.cat_downloads"]],
- },
- {
- labelKey: "settings.group_integrations",
- items: [
- ["network", "settings.cat_network"],
- ["cookies", "settings.cat_cookies"],
- ["channels", "settings.cat_channels"],
- ["ai", "settings.cat_ai"],
- ["plugins", "settings.cat_plugins"],
- ],
- },
- {
- labelKey: "settings.group_advanced",
- items: [["advanced", "settings.cat_advanced"]],
- },
- ];
-
- let activeCategory = $state<SettingsCategory>("downloads");
-
- let tabApplied = false;
- $effect(() => {
- if (tabApplied || typeof window === "undefined") return;
- tabApplied = true;
- const tab = new URLSearchParams(window.location.search).get("tab");
- const valid = ["downloads", "appearance", "typography", "network", "cookies", "channels", "ai", "plugins", "advanced"];
- if (tab && valid.includes(tab)) {
- activeCategory = tab as SettingsCategory;
- }
- });
-
- let searchQuery = $state("");
- let normalizedQuery = $derived(searchQuery.trim().toLowerCase());
- let isSearching = $derived(normalizedQuery.length > 0);
- let categoryMatchCounts = $state<Partial<Record<SettingsCategory, number>>>({});
-
- const PANEL_MATCH_SELECTORS =
- ".setting-row, .preset-card, .settings-section-head, .section-title, .deps-table-row";
-
- function clearSearchHighlights(root: ParentNode) {
- root.querySelectorAll("mark.settings-search-hit").forEach((mark) => {
- const parent = mark.parentNode;
- if (!parent) return;
- parent.replaceChild(document.createTextNode(mark.textContent ?? ""), mark);
- parent.normalize();
- });
- }
-
- function highlightPlainText(el: HTMLElement, query: string) {
- if (el.children.length > 0) return;
- const text = el.textContent ?? "";
- const lower = text.toLowerCase();
- const idx = lower.indexOf(query);
- if (idx === -1) return;
- const before = text.slice(0, idx);
- const match = text.slice(idx, idx + query.length);
- const after = text.slice(idx + query.length);
- el.textContent = "";
- if (before) el.appendChild(document.createTextNode(before));
- const mark = document.createElement("mark");
- mark.className = "settings-search-hit";
- mark.textContent = match;
- el.appendChild(mark);
- if (after) el.appendChild(document.createTextNode(after));
- }
-
- function applySearchHighlights(container: HTMLElement, query: string) {
- clearSearchHighlights(container);
- if (!query) return;
- const highlightSelectors =
- ".setting-path, .settings-section-hint, .preset-desc, .preset-label";
- container.querySelectorAll<HTMLElement>(highlightSelectors).forEach((el) => {
- if (el.style.display === "none") return;
- highlightPlainText(el, query);
- });
- container.querySelectorAll<HTMLElement>(".setting-label").forEach((el) => {
- if (el.style.display === "none" || el.children.length > 0) return;
- highlightPlainText(el, query);
- });
- }
-
- function countPanelMatches(panel: HTMLElement, query: string): number {
- let count = 0;
- panel.querySelectorAll<HTMLElement>(PANEL_MATCH_SELECTORS).forEach((el) => {
- if ((el.textContent ?? "").toLowerCase().includes(query)) count += 1;
- });
- return count;
- }
-
- function resetSettingsSearchDisplay(content: HTMLElement) {
- content
- .querySelectorAll<HTMLElement>(
- ".setting-row, .section-title, .settings-section-head, .card, .preset-card, .section, .deps-table-row",
- )
- .forEach((el) => {
- el.style.display = "";
- });
- clearSearchHighlights(content);
- categoryMatchCounts = {};
- }
-
- function applySettingsPanelFilter(content: HTMLElement, query: string) {
- const rows = content.querySelectorAll<HTMLElement>(
- ".setting-row, .section-title, .settings-section-head, .deps-table-row",
- );
- rows.forEach((row) => {
- const text = (row.textContent ?? "").toLowerCase();
- row.style.display = text.includes(query) ? "" : "none";
- });
- content.querySelectorAll<HTMLElement>(".preset-card").forEach((card) => {
- const text = (card.textContent ?? "").toLowerCase();
- card.style.display = text.includes(query) ? "" : "none";
- });
- content.querySelectorAll<HTMLElement>(".card").forEach((card) => {
- const hasVisibleRow = Array.from(
- card.querySelectorAll<HTMLElement>(".setting-row"),
- ).some((r) => r.style.display !== "none");
- card.style.display = hasVisibleRow ? "" : "none";
- });
- content.querySelectorAll<HTMLElement>(".section").forEach((section) => {
- const titleEl = section.querySelector<HTMLElement>(
- ".section-title, .settings-section-head",
- );
- const hasVisibleRow = Array.from(
- section.querySelectorAll<HTMLElement>(".setting-row, .deps-table-row"),
- ).some((r) => r.style.display !== "none");
- const hasVisibleCard = Array.from(
- section.querySelectorAll<HTMLElement>(".card"),
- ).some((c) => c.style.display !== "none");
- const hasVisiblePreset = Array.from(
- section.querySelectorAll<HTMLElement>(".preset-card"),
- ).some((p) => p.style.display !== "none");
- const hasMatchingTitle = (titleEl?.textContent ?? "")
- .toLowerCase()
- .includes(query);
- section.style.display =
- hasVisibleRow || hasVisibleCard || hasVisiblePreset || hasMatchingTitle
- ? ""
- : "none";
- });
- }
-
- $effect(() => {
- const q = normalizedQuery;
- if (typeof document === "undefined") return;
- let cancelled = false;
-
- (async () => {
- await tick();
- if (cancelled) return;
- const content = document.querySelector<HTMLElement>(".settings-content");
- if (!content) return;
-
- if (!q) {
- resetSettingsSearchDisplay(content);
- return;
- }
-
- if (isSearching) await tick();
- if (cancelled) return;
-
- applySettingsPanelFilter(content, q);
-
- const counts: Partial<Record<SettingsCategory, number>> = {};
- content.querySelectorAll<HTMLElement>("[data-settings-cat]").forEach((panel) => {
- const cat = panel.dataset.settingsCat as SettingsCategory | undefined;
- if (!cat) return;
- counts[cat] = countPanelMatches(panel, q);
- });
- categoryMatchCounts = counts;
-
- applySearchHighlights(content, q);
- })();
-
- return () => {
- cancelled = true;
- };
- });
-
- function groupHasSearchMatch(group: (typeof SETTINGS_NAV_GROUPS)[number]): boolean {
- if (!isSearching) return true;
- return group.items.some(([cat]) => (categoryMatchCounts[cat] ?? 0) > 0);
- }
-
- let templateInput = $state("");
- let templateTimer = $state<ReturnType<typeof setTimeout> | null>(null);
- let hotkeyInput = $state("");
- let hotkeyTimer = $state<ReturnType<typeof setTimeout> | null>(null);
- let hotkeyMode = $state<"record" | "type">("record");
- let hotkeyRecording = $state(false);
- let proxyHost = $state("");
- let proxyUsername = $state("");
- let proxyPassword = $state("");
- let proxyTimer = $state<ReturnType<typeof setTimeout> | null>(null);
-
- $effect(() => {
- if (settings) {
- templateInput = settings.download.filename_template;
- hotkeyInput = settings.download.hotkey_binding;
- proxyHost = settings.proxy?.host ?? "";
- proxyUsername = settings.proxy?.username ?? "";
- proxyPassword = settings.proxy?.password ?? "";
- }
- });
-
- function previewTemplate(template: string): string {
- return template
- .replace("%(title).200s", "My Video Title")
- .replace("%(title)s", "My Video Title")
- .replace("%(id)s", "dQw4w9WgXcQ")
- .replace("%(ext)s", "mp4")
- .replace("%(uploader)s", "Channel Name")
- .replace("%(upload_date)s", "20260217")
- .replace("%(resolution)s", "1920x1080")
- .replace("%(fps)s", "30")
- .replace("%(duration)s", "212");
- }
-
- function handleTemplateInput(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- templateInput = value;
- if (templateTimer) clearTimeout(templateTimer);
- templateTimer = setTimeout(async () => {
- if (value.trim() && value.includes("%(ext)s")) {
- await updateSettings({ download: { filename_template: value } });
- }
- }, 800);
- }
-
- function handleHotkeyInput(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- hotkeyInput = value;
- if (hotkeyTimer) clearTimeout(hotkeyTimer);
- hotkeyTimer = setTimeout(async () => {
- if (value.trim()) {
- await updateSettings({ download: { hotkey_binding: value } });
- }
- }, 800);
- }
-
- function mapKeyName(key: string): string | null {
- if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();
- if (key.length === 1 && /[0-9]/.test(key)) return key;
- if (/^F([1-9]|1[0-2])$/.test(key)) return key;
- const map: Record<string, string> = {
- " ": "Space", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",
- Enter: "Enter", Tab: "Tab", Escape: "Escape", Backspace: "Backspace", Delete: "Delete",
- Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", Insert: "Insert",
- };
- return map[key] ?? null;
- }
-
- function handleHotkeyKeyDown(e: KeyboardEvent) {
- e.preventDefault();
- e.stopPropagation();
- if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
- const keyName = mapKeyName(e.key);
- if (!keyName) return;
- const parts: string[] = [];
- if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
- if (e.shiftKey) parts.push("Shift");
- if (e.altKey) parts.push("Alt");
- parts.push(keyName);
- const value = parts.join("+");
- hotkeyInput = value;
- hotkeyRecording = false;
- updateSettings({ download: { hotkey_binding: value } });
- }
-
- async function changeProxyType(e: Event) {
- const value = (e.target as HTMLSelectElement).value;
- await updateSettings({ proxy: { proxy_type: value } });
- }
-
- function handleProxyHost(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- proxyHost = value;
- if (proxyTimer) clearTimeout(proxyTimer);
- proxyTimer = setTimeout(async () => {
- await updateSettings({ proxy: { host: value } });
- }, 800);
- }
-
- function handleProxyUsername(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- proxyUsername = value;
- if (proxyTimer) clearTimeout(proxyTimer);
- proxyTimer = setTimeout(async () => {
- await updateSettings({ proxy: { username: value } });
- }, 800);
- }
-
- function handleProxyPassword(e: Event) {
- const value = (e.target as HTMLInputElement).value;
- proxyPassword = value;
- if (proxyTimer) clearTimeout(proxyTimer);
- proxyTimer = setTimeout(async () => {
- await updateSettings({ proxy: { password: value } });
- }, 800);
- }
-
- async function handleReset() {
- if (!confirm($t("settings.advanced.reset_confirm"))) return;
- resetting = true;
- try {
- await resetSettings();
- } catch (e: any) {
- showToast("error", typeof e === "string" ? e : e.message ?? $t("common.error"));
- } finally {
- resetting = false;
- }
- }
-</script>
-
-{#if settings}
- <div class="settings settings-mac">
- {#if updateInfo.available}
- <div class="update-banner">
- <span class="update-text">
- {#if updating}
- {$t('settings.update_downloading')}
- {:else}
- {$t('settings.update_available', { version: updateInfo.version })}
- {/if}
- </span>
- <button class="update-btn" onclick={handleUpdate} disabled={updating}>
- {#if updating}
- <span class="update-spinner"></span>
- {:else}
- {$t('settings.update_button')}
- {/if}
- </button>
- </div>
- {/if}
-
- <div class="settings-mac-body">
- <aside class="settings-mac-sidebar">
- <div class="settings-search-row">
- <input
- type="search"
- class="settings-search"
- placeholder={$t('settings.search_placeholder')}
- value={searchQuery}
- oninput={(e) => searchQuery = (e.target as HTMLInputElement).value}
- spellcheck="false"
- aria-label={$t('settings.search_placeholder')}
- />
- </div>
- {#each SETTINGS_NAV_GROUPS as group (group.labelKey)}
- {#if groupHasSearchMatch(group)}
- <div class="settings-mac-nav-group">
- <div class="mac-nav-section-header">{$t(group.labelKey)}</div>
- {#each group.items as [cat, key] (cat)}
- {#if !isSearching || (categoryMatchCounts[cat] ?? 0) > 0}
- <button
- class="settings-mac-cat"
- class:active={!isSearching && activeCategory === cat}
- class:search-match={isSearching && (categoryMatchCounts[cat] ?? 0) > 0}
- onclick={() => { activeCategory = cat; searchQuery = ""; }}
- >
- <span class="settings-mac-cat-label">{$t(key)}</span>
- {#if isSearching && (categoryMatchCounts[cat] ?? 0) > 0}
- <span class="settings-cat-match-count">{categoryMatchCounts[cat]}</span>
- {/if}
- </button>
- {/if}
- {/each}
- </div>
- {/if}
- {/each}
- </aside>
-
- <div class="settings-mac-content settings-content">
-
- {#if isSearching || activeCategory === "appearance"}
- <div class="settings-panel" data-settings-cat="appearance">
- <SettingsAppearance searchActive={isSearching} />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "typography"}
- <div class="settings-panel" data-settings-cat="typography">
- <SettingsTypography />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "downloads"}
- <div class="settings-panel" data-settings-cat="downloads">
- <SettingsDownloads searchActive={isSearching} />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "plugins"}
- <div class="settings-panel" data-settings-cat="plugins">
- <SettingsPlugins
- {deps}
- {installingDep}
- onInstallDep={handleInstallDep}
- onRefresh={loadDeps}
- />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "network"}
- <div class="settings-panel" data-settings-cat="network">
- <SettingsBrowserExtension />
- <SettingsNetwork />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "cookies"}
- <div class="settings-panel" data-settings-cat="cookies">
- <SettingsCookies />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "channels"}
- <div class="settings-panel" data-settings-cat="channels">
- <SettingsChannels />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "ai"}
- <div class="settings-panel" data-settings-cat="ai">
- <SettingsAI />
- </div>
- {/if}
-
- {#if isSearching || activeCategory === "advanced"}
- <div class="settings-panel" data-settings-cat="advanced">
- <SettingsAdvanced {resetting} onReset={handleReset} searchActive={isSearching} />
- </div>
- {/if}
- </div>
- </div>
- </div>
-{:else}
- <div class="settings-loading">
- <span class="spinner"></span>
- </div>
-{/if}
-
+<script lang="ts">
+ import { tick } from "svelte";
+ import { invoke } from "@tauri-apps/api/core";
+ import { open } from "@tauri-apps/plugin-dialog";
+ import { t, locale, loadTranslations } from "$lib/i18n";
+ import { getSettings, updateSettings, resetSettings } from "$lib/stores/settings-store.svelte";
+ import { getUpdateInfo } from "$lib/stores/update-store.svelte";
+ import { installUpdate } from "$lib/updater";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
+ import { isDebugEnabled, setDebugEnabled, setDebugPanelOpen } from "$lib/stores/debug-store.svelte";
+ import ContextHint from "$components/hints/ContextHint.svelte";
+ import SettingsPlugins from "$components/settings/SettingsPlugins.svelte";
+ import SettingsAdvanced from "$components/settings/SettingsAdvanced.svelte";
+ import SettingsAppearance from "$components/settings/SettingsAppearance.svelte";
+ import SettingsNetwork from "$components/settings/SettingsNetwork.svelte";
+ import SettingsDownloads from "$components/settings/SettingsDownloads.svelte";
+ import SettingsTypography from "$components/settings/SettingsTypography.svelte";
+ import SettingsBrowserExtension from "$components/settings/SettingsBrowserExtension.svelte";
+ import SettingsCookies from "$components/settings/SettingsCookies.svelte";
+ import SettingsChannels from "$components/settings/SettingsChannels.svelte";
+ import SettingsAI from "$components/settings/SettingsAI.svelte";
+
+ type DependencyStatus = {
+ name: string;
+ installed: boolean;
+ version: string | null;
+ outdated: boolean;
+ };
+
+ let settings = $derived(getSettings());
+ let updateInfo = $derived(getUpdateInfo());
+ let isWindows = typeof navigator !== "undefined" && navigator.userAgent.includes("Windows");
+ let resetting = $state(false);
+ let updating = $state(false);
+ let deps = $state<DependencyStatus[]>([]);
+ let installingDep = $state<string | null>(null);
+
+ async function loadDeps() {
+ try {
+ deps = await invoke<DependencyStatus[]>("check_dependencies");
+ } catch {}
+ }
+
+ async function chooseCookieFile() {
+ const selected = await open({
+ title: "Select cookies.txt file",
+ filters: [{ name: "Cookies", extensions: ["txt"] }],
+ multiple: false,
+ });
+ if (selected && typeof selected === "string") {
+ await updateSettings({ download: { cookie_file: selected } });
+ }
+ }
+
+ async function handleInstallDep(name: string, variant: string | null = null) {
+ const wasInstalled = deps.find((d) => d.name === name)?.installed ?? false;
+ installingDep = name;
+ try {
+ const version = await invoke<string>("install_dependency", { name, variant, force: wasInstalled });
+ await loadDeps();
+ await refreshYtdlpStatus();
+ showToast(
+ "success",
+ $t(
+ wasInstalled ? "settings.dependencies.update_success" : "settings.dependencies.install_success",
+ { name, version },
+ ) as string,
+ );
+ } catch (e: any) {
+ showToast("error", typeof e === "string" ? e : e.message ?? $t("common.error"));
+ } finally {
+ installingDep = null;
+ }
+ }
+
+ $effect(() => {
+ if (settings) {
+ loadDeps();
+ }
+ });
+
+ async function handleUpdate() {
+ updating = true;
+ try {
+ await installUpdate();
+ } catch {
+ updating = false;
+ }
+ }
+
+ async function changeTheme(value: string) {
+ await updateSettings({ appearance: { theme: value } });
+ }
+
+ const CORE_THEMES = [
+ { id: "system", labelKey: "settings.appearance.theme_system", colors: null as string[] | null },
+ { id: "light", labelKey: null, label: "Light", colors: ["#fafafa", "#1a1a1a", "#E05500"] },
+ { id: "dark", labelKey: null, label: "Dark", colors: ["#0a0a0a", "#e8e8e8", "#FF7D38"] },
+ ];
+ const MORE_THEMES = [
+ { id: "catppuccin-latte", label: "Catppuccin Latte", colors: ["#eff1f5", "#4c4f69", "#1e66f5"] },
+ { id: "catppuccin-frappe", label: "Catppuccin Frappé", colors: ["#303446", "#c6d0f5", "#8caaee"] },
+ { id: "catppuccin-macchiato", label: "Catppuccin Macchiato", colors: ["#24273a", "#cad3f5", "#8aadf4"] },
+ { id: "catppuccin-mocha", label: "Catppuccin Mocha", colors: ["#1e1e2e", "#cdd6f4", "#89b4fa"] },
+ { id: "one-dark-pro", label: "One Dark Pro", colors: ["#282c34", "#abb2bf", "#61afef"] },
+ { id: "dracula", label: "Dracula", colors: ["#22212C", "#F8F8F2", "#9580FF"] },
+ { id: "nyxvamp-veil", label: "NyxVamp Veil", colors: ["#1E1E2E", "#D9E0EE", "#F28FAD"] },
+ { id: "nyxvamp-obsidian", label: "NyxVamp Obsidian", colors: ["#000A0F", "#C0C0CE", "#F28FAD"] },
+ { id: "nyxvamp-radiance", label: "NyxVamp Radiance", colors: ["#F7F7FF", "#1E1E2E", "#9655FF"] },
+ { id: "eink-day", label: "E-ink Day", colors: ["#f5f2ea", "#1d1d1b", "#2b2b28"] },
+ { id: "eink-sepia", label: "E-ink Sepia", colors: ["#f0e6d2", "#3f2e20", "#7a4a22"] },
+ { id: "eink-night", label: "E-ink Night", colors: ["#0a0a0a", "#d4d4d0", "#b0b0ab"] },
+ ];
+ const MORE_THEME_IDS = new Set(MORE_THEMES.map((t) => t.id));
+ let selectedInMore = $derived(MORE_THEME_IDS.has(settings?.appearance?.theme ?? ""));
+
+ async function changeLanguage(e: Event) {
+ const value = (e.target as HTMLSelectElement).value;
+ await updateSettings({ appearance: { language: value } });
+ await loadTranslations(value, "/settings");
+ locale.set(value);
+ }
+
+ async function chooseFolder() {
+ const selected = await open({ directory: true, title: $t("settings.download.default_output_dir") });
+ if (selected) {
+ await updateSettings({ download: { default_output_dir: selected } });
+ }
+ }
+
+ async function toggleBool(section: string, key: string, current: boolean) {
+ await updateSettings({ [section]: { [key]: !current } });
+ }
+
+ async function changeNumber(section: string, key: string, e: Event) {
+ const value = parseInt((e.target as HTMLInputElement).value, 10);
+ if (!isNaN(value) && value > 0) {
+ await updateSettings({ [section]: { [key]: value } });
+ if (key === "max_concurrent_downloads") {
+ try {
+ await invoke("update_max_concurrent", { max: value });
+ } catch {}
+ }
+ }
+ }
+
+ async function changeQuality(e: Event) {
+ const value = (e.target as HTMLSelectElement).value;
+ await updateSettings({ download: { video_quality: value } });
+ }
+
+ type SettingsCategory = "downloads" | "appearance" | "typography" | "network" | "cookies" | "channels" | "ai" | "plugins" | "advanced";
+
+ const SETTINGS_NAV_GROUPS: {
+ labelKey: string;
+ items: [SettingsCategory, string][];
+ }[] = [
+ {
+ labelKey: "settings.group_general",
+ items: [
+ ["appearance", "settings.cat_appearance"],
+ ["typography", "settings.cat_typography"],
+ ],
+ },
+ {
+ labelKey: "settings.group_media",
+ items: [["downloads", "settings.cat_downloads"]],
+ },
+ {
+ labelKey: "settings.group_integrations",
+ items: [
+ ["network", "settings.cat_network"],
+ ["cookies", "settings.cat_cookies"],
+ ["channels", "settings.cat_channels"],
+ ["ai", "settings.cat_ai"],
+ ["plugins", "settings.cat_plugins"],
+ ],
+ },
+ {
+ labelKey: "settings.group_advanced",
+ items: [["advanced", "settings.cat_advanced"]],
+ },
+ ];
+
+ let activeCategory = $state<SettingsCategory>("downloads");
+
+ let tabApplied = false;
+ $effect(() => {
+ if (tabApplied || typeof window === "undefined") return;
+ tabApplied = true;
+ const tab = new URLSearchParams(window.location.search).get("tab");
+ const valid = ["downloads", "appearance", "typography", "network", "cookies", "channels", "ai", "plugins", "advanced"];
+ if (tab && valid.includes(tab)) {
+ activeCategory = tab as SettingsCategory;
+ }
+ });
+
+ let searchQuery = $state("");
+ let normalizedQuery = $derived(searchQuery.trim().toLowerCase());
+ let isSearching = $derived(normalizedQuery.length > 0);
+ let categoryMatchCounts = $state<Partial<Record<SettingsCategory, number>>>({});
+
+ const PANEL_MATCH_SELECTORS =
+ ".setting-row, .preset-card, .settings-section-head, .section-title, .deps-table-row";
+
+ function clearSearchHighlights(root: ParentNode) {
+ root.querySelectorAll("mark.settings-search-hit").forEach((mark) => {
+ const parent = mark.parentNode;
+ if (!parent) return;
+ parent.replaceChild(document.createTextNode(mark.textContent ?? ""), mark);
+ parent.normalize();
+ });
+ }
+
+ function highlightPlainText(el: HTMLElement, query: string) {
+ if (el.children.length > 0) return;
+ const text = el.textContent ?? "";
+ const lower = text.toLowerCase();
+ const idx = lower.indexOf(query);
+ if (idx === -1) return;
+ const before = text.slice(0, idx);
+ const match = text.slice(idx, idx + query.length);
+ const after = text.slice(idx + query.length);
+ el.textContent = "";
+ if (before) el.appendChild(document.createTextNode(before));
+ const mark = document.createElement("mark");
+ mark.className = "settings-search-hit";
+ mark.textContent = match;
+ el.appendChild(mark);
+ if (after) el.appendChild(document.createTextNode(after));
+ }
+
+ function applySearchHighlights(container: HTMLElement, query: string) {
+ clearSearchHighlights(container);
+ if (!query) return;
+ const highlightSelectors =
+ ".setting-path, .settings-section-hint, .preset-desc, .preset-label";
+ container.querySelectorAll<HTMLElement>(highlightSelectors).forEach((el) => {
+ if (el.style.display === "none") return;
+ highlightPlainText(el, query);
+ });
+ container.querySelectorAll<HTMLElement>(".setting-label").forEach((el) => {
+ if (el.style.display === "none" || el.children.length > 0) return;
+ highlightPlainText(el, query);
+ });
+ }
+
+ function countPanelMatches(panel: HTMLElement, query: string): number {
+ let count = 0;
+ panel.querySelectorAll<HTMLElement>(PANEL_MATCH_SELECTORS).forEach((el) => {
+ if ((el.textContent ?? "").toLowerCase().includes(query)) count += 1;
+ });
+ return count;
+ }
+
+ function resetSettingsSearchDisplay(content: HTMLElement) {
+ content
+ .querySelectorAll<HTMLElement>(
+ ".setting-row, .section-title, .settings-section-head, .card, .preset-card, .section, .deps-table-row",
+ )
+ .forEach((el) => {
+ el.style.display = "";
+ });
+ clearSearchHighlights(content);
+ categoryMatchCounts = {};
+ }
+
+ function applySettingsPanelFilter(content: HTMLElement, query: string) {
+ const rows = content.querySelectorAll<HTMLElement>(
+ ".setting-row, .section-title, .settings-section-head, .deps-table-row",
+ );
+ rows.forEach((row) => {
+ const text = (row.textContent ?? "").toLowerCase();
+ row.style.display = text.includes(query) ? "" : "none";
+ });
+ content.querySelectorAll<HTMLElement>(".preset-card").forEach((card) => {
+ const text = (card.textContent ?? "").toLowerCase();
+ card.style.display = text.includes(query) ? "" : "none";
+ });
+ content.querySelectorAll<HTMLElement>(".card").forEach((card) => {
+ const hasVisibleRow = Array.from(
+ card.querySelectorAll<HTMLElement>(".setting-row"),
+ ).some((r) => r.style.display !== "none");
+ card.style.display = hasVisibleRow ? "" : "none";
+ });
+ content.querySelectorAll<HTMLElement>(".section").forEach((section) => {
+ const titleEl = section.querySelector<HTMLElement>(
+ ".section-title, .settings-section-head",
+ );
+ const hasVisibleRow = Array.from(
+ section.querySelectorAll<HTMLElement>(".setting-row, .deps-table-row"),
+ ).some((r) => r.style.display !== "none");
+ const hasVisibleCard = Array.from(
+ section.querySelectorAll<HTMLElement>(".card"),
+ ).some((c) => c.style.display !== "none");
+ const hasVisiblePreset = Array.from(
+ section.querySelectorAll<HTMLElement>(".preset-card"),
+ ).some((p) => p.style.display !== "none");
+ const hasMatchingTitle = (titleEl?.textContent ?? "")
+ .toLowerCase()
+ .includes(query);
+ section.style.display =
+ hasVisibleRow || hasVisibleCard || hasVisiblePreset || hasMatchingTitle
+ ? ""
+ : "none";
+ });
+ }
+
+ $effect(() => {
+ const q = normalizedQuery;
+ if (typeof document === "undefined") return;
+ let cancelled = false;
+
+ (async () => {
+ await tick();
+ if (cancelled) return;
+ const content = document.querySelector<HTMLElement>(".settings-content");
+ if (!content) return;
+
+ if (!q) {
+ resetSettingsSearchDisplay(content);
+ return;
+ }
+
+ if (isSearching) await tick();
+ if (cancelled) return;
+
+ applySettingsPanelFilter(content, q);
+
+ const counts: Partial<Record<SettingsCategory, number>> = {};
+ content.querySelectorAll<HTMLElement>("[data-settings-cat]").forEach((panel) => {
+ const cat = panel.dataset.settingsCat as SettingsCategory | undefined;
+ if (!cat) return;
+ counts[cat] = countPanelMatches(panel, q);
+ });
+ categoryMatchCounts = counts;
+
+ applySearchHighlights(content, q);
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ });
+
+ function groupHasSearchMatch(group: (typeof SETTINGS_NAV_GROUPS)[number]): boolean {
+ if (!isSearching) return true;
+ return group.items.some(([cat]) => (categoryMatchCounts[cat] ?? 0) > 0);
+ }
+
+ let templateInput = $state("");
+ let templateTimer = $state<ReturnType<typeof setTimeout> | null>(null);
+ let hotkeyInput = $state("");
+ let hotkeyTimer = $state<ReturnType<typeof setTimeout> | null>(null);
+ let hotkeyMode = $state<"record" | "type">("record");
+ let hotkeyRecording = $state(false);
+ let proxyHost = $state("");
+ let proxyUsername = $state("");
+ let proxyPassword = $state("");
+ let proxyTimer = $state<ReturnType<typeof setTimeout> | null>(null);
+
+ $effect(() => {
+ if (settings) {
+ templateInput = settings.download.filename_template;
+ hotkeyInput = settings.download.hotkey_binding;
+ proxyHost = settings.proxy?.host ?? "";
+ proxyUsername = settings.proxy?.username ?? "";
+ proxyPassword = settings.proxy?.password ?? "";
+ }
+ });
+
+ function previewTemplate(template: string): string {
+ return template
+ .replace("%(title).200s", "My Video Title")
+ .replace("%(title)s", "My Video Title")
+ .replace("%(id)s", "dQw4w9WgXcQ")
+ .replace("%(ext)s", "mp4")
+ .replace("%(uploader)s", "Channel Name")
+ .replace("%(upload_date)s", "20260217")
+ .replace("%(resolution)s", "1920x1080")
+ .replace("%(fps)s", "30")
+ .replace("%(duration)s", "212");
+ }
+
+ function handleTemplateInput(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ templateInput = value;
+ if (templateTimer) clearTimeout(templateTimer);
+ templateTimer = setTimeout(async () => {
+ if (value.trim() && value.includes("%(ext)s")) {
+ await updateSettings({ download: { filename_template: value } });
+ }
+ }, 800);
+ }
+
+ function handleHotkeyInput(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ hotkeyInput = value;
+ if (hotkeyTimer) clearTimeout(hotkeyTimer);
+ hotkeyTimer = setTimeout(async () => {
+ if (value.trim()) {
+ await updateSettings({ download: { hotkey_binding: value } });
+ }
+ }, 800);
+ }
+
+ function mapKeyName(key: string): string | null {
+ if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();
+ if (key.length === 1 && /[0-9]/.test(key)) return key;
+ if (/^F([1-9]|1[0-2])$/.test(key)) return key;
+ const map: Record<string, string> = {
+ " ": "Space", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",
+ Enter: "Enter", Tab: "Tab", Escape: "Escape", Backspace: "Backspace", Delete: "Delete",
+ Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", Insert: "Insert",
+ };
+ return map[key] ?? null;
+ }
+
+ function handleHotkeyKeyDown(e: KeyboardEvent) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;
+ const keyName = mapKeyName(e.key);
+ if (!keyName) return;
+ const parts: string[] = [];
+ if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");
+ if (e.shiftKey) parts.push("Shift");
+ if (e.altKey) parts.push("Alt");
+ parts.push(keyName);
+ const value = parts.join("+");
+ hotkeyInput = value;
+ hotkeyRecording = false;
+ updateSettings({ download: { hotkey_binding: value } });
+ }
+
+ async function changeProxyType(e: Event) {
+ const value = (e.target as HTMLSelectElement).value;
+ await updateSettings({ proxy: { proxy_type: value } });
+ }
+
+ function handleProxyHost(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ proxyHost = value;
+ if (proxyTimer) clearTimeout(proxyTimer);
+ proxyTimer = setTimeout(async () => {
+ await updateSettings({ proxy: { host: value } });
+ }, 800);
+ }
+
+ function handleProxyUsername(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ proxyUsername = value;
+ if (proxyTimer) clearTimeout(proxyTimer);
+ proxyTimer = setTimeout(async () => {
+ await updateSettings({ proxy: { username: value } });
+ }, 800);
+ }
+
+ function handleProxyPassword(e: Event) {
+ const value = (e.target as HTMLInputElement).value;
+ proxyPassword = value;
+ if (proxyTimer) clearTimeout(proxyTimer);
+ proxyTimer = setTimeout(async () => {
+ await updateSettings({ proxy: { password: value } });
+ }, 800);
+ }
+
+ async function handleReset() {
+ if (!confirm($t("settings.advanced.reset_confirm"))) return;
+ resetting = true;
+ try {
+ await resetSettings();
+ } catch (e: any) {
+ showToast("error", typeof e === "string" ? e : e.message ?? $t("common.error"));
+ } finally {
+ resetting = false;
+ }
+ }
+</script>
+
+{#if settings}
+ <div class="settings settings-mac">
+ {#if updateInfo.available}
+ <div class="update-banner">
+ <span class="update-text">
+ {#if updating}
+ {$t('settings.update_downloading')}
+ {:else}
+ {$t('settings.update_available', { version: updateInfo.version })}
+ {/if}
+ </span>
+ <button class="update-btn" onclick={handleUpdate} disabled={updating}>
+ {#if updating}
+ <span class="update-spinner"></span>
+ {:else}
+ {$t('settings.update_button')}
+ {/if}
+ </button>
+ </div>
+ {/if}
+
+ <div class="settings-mac-body">
+ <aside class="settings-mac-sidebar">
+ <div class="settings-search-row">
+ <input
+ type="search"
+ class="settings-search"
+ placeholder={$t('settings.search_placeholder')}
+ value={searchQuery}
+ oninput={(e) => searchQuery = (e.target as HTMLInputElement).value}
+ spellcheck="false"
+ aria-label={$t('settings.search_placeholder')}
+ />
+ </div>
+ {#each SETTINGS_NAV_GROUPS as group (group.labelKey)}
+ {#if groupHasSearchMatch(group)}
+ <div class="settings-mac-nav-group">
+ <div class="mac-nav-section-header">{$t(group.labelKey)}</div>
+ {#each group.items as [cat, key] (cat)}
+ {#if !isSearching || (categoryMatchCounts[cat] ?? 0) > 0}
+ <button
+ class="settings-mac-cat"
+ class:active={!isSearching && activeCategory === cat}
+ class:search-match={isSearching && (categoryMatchCounts[cat] ?? 0) > 0}
+ onclick={() => { activeCategory = cat; searchQuery = ""; }}
+ >
+ <span class="settings-mac-cat-label">{$t(key)}</span>
+ {#if isSearching && (categoryMatchCounts[cat] ?? 0) > 0}
+ <span class="settings-cat-match-count">{categoryMatchCounts[cat]}</span>
+ {/if}
+ </button>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ {/each}
+ </aside>
+
+ <div class="settings-mac-content settings-content">
+
+ {#if isSearching || activeCategory === "appearance"}
+ <div class="settings-panel" data-settings-cat="appearance">
+ <SettingsAppearance searchActive={isSearching} />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "typography"}
+ <div class="settings-panel" data-settings-cat="typography">
+ <SettingsTypography />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "downloads"}
+ <div class="settings-panel" data-settings-cat="downloads">
+ <SettingsDownloads searchActive={isSearching} />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "plugins"}
+ <div class="settings-panel" data-settings-cat="plugins">
+ <SettingsPlugins
+ {deps}
+ {installingDep}
+ onInstallDep={handleInstallDep}
+ onRefresh={loadDeps}
+ />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "network"}
+ <div class="settings-panel" data-settings-cat="network">
+ <SettingsBrowserExtension />
+ <SettingsNetwork />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "cookies"}
+ <div class="settings-panel" data-settings-cat="cookies">
+ <SettingsCookies />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "channels"}
+ <div class="settings-panel" data-settings-cat="channels">
+ <SettingsChannels />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "ai"}
+ <div class="settings-panel" data-settings-cat="ai">
+ <SettingsAI />
+ </div>
+ {/if}
+
+ {#if isSearching || activeCategory === "advanced"}
+ <div class="settings-panel" data-settings-cat="advanced">
+ <SettingsAdvanced {resetting} onReset={handleReset} searchActive={isSearching} />
+ </div>
+ {/if}
+ </div>
+ </div>
+ </div>
+{:else}
+ <div class="settings-loading">
+ <span class="spinner"></span>
+ </div>
+{/if}
+