diff --git a/crates/qbz-cache/src/image_cache.rs b/crates/qbz-cache/src/image_cache.rs index 634781dec..694d68cd3 100644 --- a/crates/qbz-cache/src/image_cache.rs +++ b/crates/qbz-cache/src/image_cache.rs @@ -197,6 +197,53 @@ impl ImageCacheService { Ok(batch) } + /// Delete `.img` files that have no row (a crash between `store`'s file + /// write and its insert, or a database that was lost), skipping anything + /// younger than `min_age` so a store in flight is never raced. Returns + /// (files removed, bytes freed). + pub fn sweep_orphans(&self, min_age: std::time::Duration) -> Result<(usize, u64), String> { + let mut stmt = self + .conn + .prepare("SELECT hash FROM cached_images") + .map_err(|e| format!("Failed to prepare orphan query: {}", e))?; + let tracked: std::collections::HashSet = stmt + .query_map([], |row| row.get::<_, String>(0)) + .map_err(|e| format!("Failed to query tracked images: {}", e))? + .filter_map(|r| r.ok()) + .collect(); + let entries = std::fs::read_dir(&self.cache_dir) + .map_err(|e| format!("Failed to read image cache dir: {}", e))?; + let now = std::time::SystemTime::now(); + let (mut files, mut bytes) = (0usize, 0u64); + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("img") { + continue; + } + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + if tracked.contains(stem) { + continue; + } + let Ok(meta) = entry.metadata() else { continue }; + let young = meta + .modified() + .ok() + .and_then(|m| now.duration_since(m).ok()) + .map(|age| age < min_age) + .unwrap_or(true); + if young { + continue; + } + if std::fs::remove_file(&path).is_ok() { + files += 1; + bytes += meta.len(); + } + } + Ok((files, bytes)) + } + /// Get cache statistics. pub fn stats(&self) -> Result { let (total_bytes, file_count): (i64, i64) = self @@ -297,6 +344,31 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn sweep_orphans_removes_only_old_files_without_a_row() { + let dir = fresh_dir("orphans"); + let cache = ImageCacheService::open_at(dir.clone()).unwrap(); + let tracked = cache.store("https://img/tracked", &[0u8; 100]).unwrap(); + let old_orphan = dir.join("0000000000000000000000000000dead.img"); + std::fs::write(&old_orphan, [0u8; 300]).unwrap(); + let two_hours_ago = filetime::FileTime::from_unix_time( + filetime::FileTime::now().unix_seconds() - 7_200, + 0, + ); + filetime::set_file_mtime(&old_orphan, two_hours_ago).unwrap(); + let fresh_orphan = dir.join("000000000000000000000000000beef1.img"); + std::fs::write(&fresh_orphan, [0u8; 50]).unwrap(); + + assert_eq!( + cache.sweep_orphans(std::time::Duration::from_secs(3_600)).unwrap(), + (1, 300) + ); + assert!(tracked.exists(), "a tracked file is never swept"); + assert!(!old_orphan.exists()); + assert!(fresh_orphan.exists(), "a store in flight is never raced"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn get_refreshes_last_accessed_so_a_touched_entry_survives_eviction() { let dir = fresh_dir("touch"); diff --git a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po index f49479b72..4f4b2e56e 100644 --- a/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/de/LC_MESSAGES/qbz-ui.po @@ -4638,10 +4638,6 @@ msgid "Random" msgstr "Zufällig" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Gibt zwischengespeicherte Daten frei. Deine heruntergeladenen Alben bleiben erhalten — entferne sie über den Offline-Manager oben." - msgid "Couldn't clear the cache" msgstr "Cache konnte nicht geleert werden" @@ -7487,3 +7483,95 @@ msgstr "Diese Optionen gelten nicht, solange Nur Streaming aktiviert ist. Deakti msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Entspricht dem Streaming-Verhalten der offiziellen Clients bei geringerem Speicherbedarf. Umgeht den Wiedergabe-Cache und seinen Schutz vor Netzwerkunterbrechungen: Der QBZ-Cache hält kommende Audiodaten für zuverlässigere Wiedergabe und sofortiges erneutes Abspielen bereit." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Gastkünstler in Titelzeilen anzeigen" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Schaltflächen für 10-Sekunden-Sprünge anzeigen" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Fügt ±10-s-Schaltflächen neben Zurück und Weiter in der Player-Leiste hinzu." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "10 Sekunden zurück" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "10 Sekunden vor" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Schleifenanfang setzen (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Schleifenende setzen (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Schleife aufheben" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "COVER-CACHE" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Maximale Größe" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Album- und Künstlerbilder werden bis zu diesem Budget auf der Festplatte behalten; die am längsten nicht gezeigten werden zuerst entfernt, während der Nutzung und beim Start." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Cover-Cache leeren" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} Bilder belegen {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Hängt \"feat. …\" mit den Gastinterpreten des Titels an die Künstlerzeile der Qobuz-Titelzeilen an. Standardmäßig aus." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Speicher" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "PLEX-CACHE" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Führt die Gastinterpreten des Titels nach dem Hauptkünstler in den Qobuz-Titelzeilen auf, durch Kommas getrennt. Jeder Name ist ein Link. Standardmäßig an." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Größenlimit anwenden" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Cache-Ordner öffnen" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Gesamten Offline-Cache leeren…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Offline-Cache leeren?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Entfernt alles, was zum Offline-Hören gespeichert ist: {} mit {}. Gekaufte Downloads in deinem Musikordner bleiben erhalten; Entferntes muss zum Offline-Hören erneut heruntergeladen werden." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Erweitert" diff --git a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po index 8acd13af6..828ce79bd 100644 --- a/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/en/LC_MESSAGES/qbz-ui.po @@ -294,10 +294,6 @@ msgid "Random" msgstr "Random" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." - msgid "Cache cleared" msgstr "Cache cleared" @@ -3113,3 +3109,95 @@ msgstr "These options do not apply while Streaming only is enabled. Turn it off msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Show featured artists in track rows" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Show 10-second skip buttons" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Add ±10 s buttons beside Previous and Next in the player bar." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "Back 10 seconds" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "Forward 10 seconds" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Set loop start (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Set loop end (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Clear loop" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "ARTWORK CACHE" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Maximum size" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Clear artwork cache" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} images using {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Storage" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "PLEX CACHE" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Apply the size limit" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Open the cache folder" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Clear the whole offline cache…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Clear the offline cache?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Advanced" diff --git a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po index e7429a328..fd2694fa7 100644 --- a/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/es/LC_MESSAGES/qbz-ui.po @@ -4674,10 +4674,6 @@ msgid "Random" msgstr "Aleatorio" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Libera datos en caché. Tus álbumes descargados se conservan — elimínalos desde el administrador offline de arriba." - msgid "Couldn't clear the cache" msgstr "No se pudo limpiar el caché" @@ -7493,3 +7489,95 @@ msgstr "Estas opciones no se aplican mientras Solo streaming esté activado. Des msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Imita el comportamiento de streaming de los clientes oficiales y usa menos memoria. Omite la caché de reproducción y su protección ante interrupciones de red: la caché de QBZ prepara el audio siguiente para una reproducción más fiable y permite volver a escuchar al instante." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Mostrar artistas invitados en las filas de pistas" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Mostrar botones de salto de 10 segundos" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Añade botones de ±10 s junto a Anterior y Siguiente en la barra del reproductor." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "Retroceder 10 segundos" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "Adelantar 10 segundos" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Fijar inicio del bucle (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Fijar fin del bucle (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Quitar bucle" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "CACHÉ DE PORTADAS" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Tamaño máximo" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Las imágenes de álbumes y artistas se guardan en disco hasta este límite; las que llevan más tiempo sin mostrarse se descartan primero, durante el uso y al arrancar." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Vaciar caché de portadas" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} imágenes ocupando {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Añade \"feat. …\" con los intérpretes invitados de la pista a la línea de artista en las filas de pistas de Qobuz. Desactivado por defecto." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Almacenamiento" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "CACHÉ DE PLEX" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Muestra los intérpretes invitados de la pista después del artista principal en las filas de pistas de Qobuz, separados por comas. Cada nombre es un enlace. Activado por defecto." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Aplicar el límite de tamaño" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Abrir la carpeta del caché" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Vaciar todo el caché offline…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "¿Vaciar el caché offline?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Elimina todo lo guardado para escuchar sin conexión: {} que ocupan {}. Las compras descargadas en tu carpeta de música se conservan; lo que se elimine tendrá que descargarse de nuevo para escucharse sin conexión." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Avanzado" diff --git a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po index 250571998..c0e832e0c 100644 --- a/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/fr/LC_MESSAGES/qbz-ui.po @@ -4638,10 +4638,6 @@ msgid "Random" msgstr "Aléatoire" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Libère les données en cache. Vos albums téléchargés sont conservés — supprimez-les depuis le gestionnaire hors ligne ci-dessus." - msgid "Couldn't clear the cache" msgstr "Impossible de vider le cache" @@ -7485,3 +7481,95 @@ msgstr "Ces options ne s’appliquent pas lorsque Streaming uniquement est activ msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Reproduit le comportement de streaming des clients officiels en utilisant moins de mémoire. Désactive le cache de lecture et sa protection contre les interruptions réseau : le cache de QBZ prépare les prochains contenus audio pour une lecture plus fiable et une réécoute immédiate." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Afficher les artistes invités dans les lignes de piste" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Afficher les boutons de saut de 10 secondes" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Ajoute des boutons ±10 s à côté de Précédent et Suivant dans la barre de lecture." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "Reculer de 10 secondes" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "Avancer de 10 secondes" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Définir le début de la boucle (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Définir la fin de la boucle (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Supprimer la boucle" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "CACHE DES POCHETTES" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Taille maximale" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Les images d'albums et d'artistes sont conservées sur le disque jusqu'à ce plafond ; les moins récemment affichées sont supprimées en premier, pendant l'utilisation et au démarrage." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Vider le cache des pochettes" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} images occupant {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Ajoute « feat. … » avec les interprètes invités du morceau sur la ligne d'artiste des lignes de piste Qobuz. Désactivé par défaut." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Stockage" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "CACHE PLEX" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Liste les interprètes invités du morceau après l'artiste principal sur les lignes de piste Qobuz, séparés par des virgules. Chaque nom est un lien. Activé par défaut." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Appliquer la limite de taille" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Ouvrir le dossier du cache" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Vider tout le cache hors ligne…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Vider le cache hors ligne ?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Supprime tout ce qui est enregistré pour l'écoute hors ligne : {} occupant {}. Les achats téléchargés dans votre dossier musique sont conservés ; ce qui est supprimé devra être retéléchargé pour être écouté hors ligne." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Avancé" diff --git a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po index b66323267..d41440285 100644 --- a/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ja/LC_MESSAGES/qbz-ui.po @@ -4627,10 +4627,6 @@ msgid "Random" msgstr "ランダム" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "キャッシュデータを解放します。ダウンロード済みのアルバムは保持されます。削除は上のオフラインマネージャーから行ってください。" - msgid "Couldn't clear the cache" msgstr "キャッシュを削除できませんでした" @@ -7468,3 +7464,95 @@ msgstr "「ストリーミングのみ」が有効な間、これらの設定は msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "公式クライアントと同様のストリーミング動作でメモリ使用量を抑えます。再生キャッシュとそのネットワーク中断への保護を無効にします。QBZのキャッシュは次の音声を事前に用意し、より安定した再生と即座のリプレイを可能にします。" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "トラック行にフィーチャリングアーティストを表示" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "10秒スキップボタンを表示" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "プレーヤーバーの「前へ」「次へ」の横に ±10 秒ボタンを追加します。" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "10秒戻る" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "10秒進む" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "ループの開始点を設定 (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "ループの終了点を設定 (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "ループを解除" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "アートワークキャッシュ" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "最大サイズ" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "アルバムとアーティストの画像はこの上限までディスクに保持され、最も長く表示されていないものから削除されます(使用中および起動時)。" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "アートワークキャッシュを消去" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} 件の画像、使用量 {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Qobuz のトラック行のアーティスト欄に、フィーチャリングされた演奏者を「feat. …」として追加します。既定ではオフです。" + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "ストレージ" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "PLEX キャッシュ" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Qobuz のトラック行で、メインアーティストの後にフィーチャリングされた演奏者をカンマ区切りで表示します。各名前はリンクです。既定ではオンです。" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "サイズ上限を適用" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "キャッシュフォルダーを開く" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "オフラインキャッシュをすべて削除…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "オフラインキャッシュを削除しますか?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "オフライン再生用に保存したものをすべて削除します({}、{})。ミュージックフォルダー内の購入済みダウンロードは残ります。削除したものをオフラインで再生するには、再度ダウンロードが必要です。" + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "詳細" diff --git a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po index d0a80f4ef..d408b3209 100644 --- a/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/nl/LC_MESSAGES/qbz-ui.po @@ -4650,10 +4650,6 @@ msgid "Random" msgstr "Willekeurig" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Maakt cachegegevens vrij. Je gedownloade albums blijven behouden — verwijder die via de offline manager hierboven." - msgid "Couldn't clear the cache" msgstr "Kan de cache niet wissen" @@ -7475,3 +7471,95 @@ msgstr "Deze opties zijn niet van toepassing zolang Alleen streamen is ingeschak msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Bootst het streaminggedrag van de officiële clients na met minder geheugengebruik. Slaat de afspeelcache en de bescherming tegen netwerkonderbrekingen over: de cache van QBZ houdt komende audio gereed voor betrouwbaarder afspelen en direct opnieuw afspelen." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Gastartiesten in trackregels tonen" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Knoppen voor 10 seconden springen tonen" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Voegt ±10 s-knoppen toe naast Vorige en Volgende in de spelerbalk." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "10 seconden terug" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "10 seconden vooruit" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Loopbegin instellen (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Loopeinde instellen (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Loop wissen" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "ARTWORKCACHE" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Maximale grootte" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Album- en artiestafbeeldingen blijven op schijf tot dit budget; de minst recent getoonde worden het eerst verwijderd, tijdens gebruik en bij het opstarten." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Artworkcache wissen" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} afbeeldingen, {} in gebruik" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Voegt \"feat. …\" met de gastartiesten van de track toe aan de artiestregel van Qobuz-trackregels. Standaard uit." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Opslag" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "PLEX-CACHE" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Toont de gastartiesten van de track na de hoofdartiest in Qobuz-trackregels, gescheiden door komma's. Elke naam is een link. Standaard aan." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Groottelimiet toepassen" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Cachemap openen" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Volledige offline cache wissen…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Offline cache wissen?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Verwijdert alles wat voor offline luisteren is opgeslagen: {} met {}. Gekochte downloads in je muziekmap blijven staan; wat je wist moet opnieuw worden gedownload om offline af te spelen." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Geavanceerd" diff --git a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po index 010891937..d3d25dd00 100644 --- a/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/pt/LC_MESSAGES/qbz-ui.po @@ -4638,10 +4638,6 @@ msgid "Random" msgstr "Aleatório" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Libera dados em cache. Seus álbuns baixados são mantidos — remova-os no gerenciador offline acima." - msgid "Couldn't clear the cache" msgstr "Não foi possível limpar o cache" @@ -7485,3 +7481,95 @@ msgstr "Estas opções não se aplicam enquanto Apenas streaming estiver ativado msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Reproduz o comportamento de streaming dos clientes oficiais com menor uso de memória. Ignora o cache de reprodução e sua proteção contra interrupções de rede: o cache do QBZ prepara o próximo áudio para uma reprodução mais confiável e repetição imediata." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Mostrar artistas convidados nas linhas de faixa" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Mostrar botões de salto de 10 segundos" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Adiciona botões de ±10 s ao lado de Anterior e Seguinte na barra do reprodutor." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "Recuar 10 segundos" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "Avançar 10 segundos" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Definir início do loop (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Definir fim do loop (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Remover loop" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "CACHE DE CAPAS" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Tamanho máximo" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "As imagens de álbuns e artistas ficam no disco até este limite; as menos recentemente mostradas são descartadas primeiro, durante o uso e no arranque." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Limpar cache de capas" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} imagens ocupando {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Acrescenta \"feat. …\" com os intérpretes convidados da faixa à linha do artista nas linhas de faixa do Qobuz. Desligado por padrão." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Armazenamento" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "CACHE DO PLEX" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Lista os intérpretes convidados da faixa após o artista principal nas linhas de faixa do Qobuz, separados por vírgulas. Cada nome é um link. Ligado por padrão." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Aplicar o limite de tamanho" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Abrir a pasta do cache" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Limpar todo o cache offline…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Limpar o cache offline?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Remove tudo o que está salvo para ouvir offline: {} ocupando {}. As compras baixadas na sua pasta de música são mantidas; o que for removido precisará ser baixado de novo para tocar offline." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Avançado" diff --git a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po index db37399a1..384d6fe54 100644 --- a/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po +++ b/crates/qbz-i18n/translations/ru/LC_MESSAGES/qbz-ui.po @@ -4654,10 +4654,6 @@ msgid "Random" msgstr "Случайно" -# Offline cache clear — communicate it does not remove downloads (#606) -msgid "Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above." -msgstr "Освобождает кэшированные данные. Загруженные альбомы сохраняются — удаляйте их в офлайн-менеджере выше." - msgid "Couldn't clear the cache" msgstr "Не удалось очистить кэш" @@ -7506,3 +7502,95 @@ msgstr "Эти параметры не применяются, пока вклю msgid "Mimics official clients’ streaming behavior with lower memory usage. Skips the playback cache and its protection against network interruptions: QBZ’s cache keeps upcoming audio ready for more reliable playback and instant replay." msgstr "Повторяет поведение потокового воспроизведения официальных клиентов, используя меньше памяти. Отключает кэш воспроизведения и его защиту от перебоев сети: кэш QBZ заранее подготавливает аудио для более надёжного воспроизведения и мгновенного повтора." + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show featured artists in track rows" +msgstr "Показывать приглашённых артистов в строках треков" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Show 10-second skip buttons" +msgstr "Показывать кнопки перемотки на 10 секунд" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Add ±10 s buttons beside Previous and Next in the player bar." +msgstr "Добавляет кнопки ±10 с рядом с «Назад» и «Вперёд» на панели воспроизведения." + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Back 10 seconds" +msgstr "Назад на 10 секунд" + +#: qbz-qt/qml/shell/TransportControls.qml +msgid "Forward 10 seconds" +msgstr "Вперёд на 10 секунд" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop start (A)" +msgstr "Задать начало петли (A)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Set loop end (B)" +msgstr "Задать конец петли (B)" + +#: qbz-qt/qml/shell/PlayerBar.qml +msgid "Clear loop" +msgstr "Убрать петлю" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "ARTWORK CACHE" +msgstr "КЭШ ОБЛОЖЕК" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Maximum size" +msgstr "Максимальный размер" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup." +msgstr "Изображения альбомов и артистов хранятся на диске в пределах этого лимита; дольше всего не показывавшиеся удаляются первыми — во время работы и при запуске." + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "Clear artwork cache" +msgstr "Очистить кэш обложек" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "{} images using {}" +msgstr "{} изображений занимают {}" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "Append \"feat. …\" with the track's featured performers to the artist line of Qobuz track rows. Off by default." +msgstr "Добавляет «feat. …» с приглашёнными исполнителями трека к строке артиста в строках треков Qobuz. По умолчанию выключено." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Storage" +msgstr "Хранилище" + +#: qbz-qt/qml/settings/StorageSettings.qml +msgid "PLEX CACHE" +msgstr "КЭШ PLEX" + +#: qbz-qt/qml/settings/AppearanceSettings.qml +msgid "List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default." +msgstr "Перечисляет приглашённых исполнителей трека после основного артиста в строках треков Qobuz, через запятую. Каждое имя — ссылка. По умолчанию включено." + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Apply the size limit" +msgstr "Применить ограничение размера" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Open the cache folder" +msgstr "Открыть папку кэша" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the whole offline cache…" +msgstr "Очистить весь офлайн-кэш…" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Clear the offline cache?" +msgstr "Очистить офлайн-кэш?" + +#: qbz-qt/qml/views/OfflineManagerView.qml +msgid "Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline." +msgstr "Удаляет всё, что сохранено для прослушивания офлайн: {} объёмом {}. Купленные загрузки в папке с музыкой остаются; удалённое придётся скачать заново, чтобы слушать офлайн." + +#: qbz-qt/qml/settings/SettingsView.qml +msgid "Advanced" +msgstr "Дополнительно" diff --git a/crates/qbz-qobuz/src/performers.rs b/crates/qbz-qobuz/src/performers.rs index e6b58cf17..06f66bac5 100644 --- a/crates/qbz-qobuz/src/performers.rs +++ b/crates/qbz-qobuz/src/performers.rs @@ -198,6 +198,86 @@ pub fn group_credits_ordered(performers: &[Performer]) -> Vec<(String, Vec Vec { + let already: Vec = split_credit_names(row_artist).map(normalize_name).collect(); + let title_norm = normalize_name(title); + let mut out: Vec = Vec::new(); + let mut seen: Vec = Vec::new(); + for p in parse_performers(performers) { + let credited = p.roles.iter().any(|r| { + let k = role_key(r); + k == "featuredArtist" || k == "mainArtist" + }); + if !credited { + continue; + } + let key = normalize_name(&p.name); + if key.is_empty() || seen.contains(&key) { + continue; + } + seen.push(key.clone()); + if already.iter().any(|a| a == &key) { + continue; + } + if !title_norm.is_empty() && title_norm.contains(&key) { + continue; + } + out.push(p.name); + } + out +} + +/// "Is this the same person" for two credited names (the row's featured +/// performer vs. an album credit that carries an id). +pub fn same_artist_name(a: &str, b: &str) -> bool { + let (a, b) = (normalize_name(a), normalize_name(b)); + !a.is_empty() && a == b +} + +/// Lower-case, Latin-1 diacritics folded, apostrophes dropped, whitespace +/// collapsed — the comparison key for "is this the same person". +fn normalize_name(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars().flat_map(char::to_lowercase) { + let c = match c { + 'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' => 'a', + 'è' | 'é' | 'ê' | 'ë' => 'e', + 'ì' | 'í' | 'î' | 'ï' => 'i', + 'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' => 'o', + 'ù' | 'ú' | 'û' | 'ü' => 'u', + 'ç' => 'c', + 'ñ' => 'n', + 'ý' | 'ÿ' => 'y', + '\'' | '’' | '`' => continue, + c if c.is_whitespace() => ' ', + c => c, + }; + if c == ' ' && out.ends_with(' ') { + continue; + } + out.push(c); + } + out.trim().to_string() +} + +/// The individual names a row's artist string spells out ("A & B", "A, B", +/// "A and B", "A x B", "A feat. B"). +fn split_credit_names(s: &str) -> impl Iterator { + s.split(|c: char| c == '&' || c == ',' || c == '/' || c == '+') + .flat_map(|part| part.split(" and ")) + .flat_map(|part| part.split(" x ")) + .flat_map(|part| part.split(" feat. ")) + .flat_map(|part| part.split(" ft. ")) + .map(str::trim) + .filter(|s| !s.is_empty()) +} + #[cfg(test)] mod tests { use super::*; @@ -251,6 +331,43 @@ mod tests { assert_eq!(grouped.get("Saxophone").unwrap().len(), 2); assert_eq!(grouped.get("Vocals").unwrap().len(), 1); } + + const NOTHING_ELSE_MATTERS: &str = "Watt, FeaturedArtist - Robert Trujillo, Bass, FeaturedArtist - Elton John, Piano, FeaturedArtist - ALAN MOULDER, MixingEngineer - Paul Lamalfa, Engineer - Yo-Yo Ma, Cello, FeaturedArtist - Miley Cyrus, Vocalist, MainArtist - Chad Smith, FeaturedArtist, DrumKit - James Hetfield, ComposerLyricist - Lars Ulrich, ComposerLyricist - Mike Block, StringArranger - Andrew Watt, Producer, Guitar, StringArranger - Caesar Edmunds, MixingSecondEngineer - Randy Merrill, MasteringEngineer"; + + /// The real search sample: MainArtist mid-string, featured artists with + /// instruments, crew roles to ignore. + #[test] + fn featured_artists_keeps_featured_and_extra_mains_in_string_order_minus_the_row_artist() { + assert_eq!( + featured_artists(NOTHING_ELSE_MATTERS, "Miley Cyrus", "Nothing Else Matters"), + vec!["Watt", "Robert Trujillo", "Elton John", "Yo-Yo Ma", "Chad Smith"] + ); + } + + #[test] + fn featured_artists_skips_names_the_row_or_the_title_already_credits() { + let p = "Alice, MainArtist - Bob, MainArtist - Carol, FeaturedArtist"; + assert_eq!(featured_artists(p, "Alice & Bob", "Song"), vec!["Carol"]); + assert_eq!(featured_artists(p, "Alice", "Song (feat. Carol)"), vec!["Bob"]); + assert!(featured_artists(p, "Alice, Bob & Carol", "Song").is_empty()); + } + + #[test] + fn same_artist_name_folds_case_diacritics_and_apostrophes() { + assert!(same_artist_name("Émilie D'Angelo", "emilie dangelo")); + assert!(same_artist_name("Yo-Yo Ma", "YO-YO MA")); + assert!(!same_artist_name("Watt", "Andrew Watt")); + assert!(!same_artist_name("", "")); + } + + #[test] + fn featured_artists_dedupes_case_and_diacritics_and_ignores_crew() { + let p = "Émilie, FeaturedArtist - emilie, Vocalist, FeaturedArtist - Dan, Producer - Main, MainArtist"; + assert_eq!(featured_artists(p, "Main", ""), vec!["Émilie"]); + assert!(featured_artists("", "Main", "").is_empty()); + assert!(featured_artists("Solo, MainArtist", "Solo", "Song").is_empty()); + } + } pub(crate) static PERFORMER_ROLE_LABELS: &[(&str, &str)] = &[ ("a&R", "Artists and Repertoire"), diff --git a/crates/qbz-qt/build.rs b/crates/qbz-qt/build.rs index 8a4382e77..4c62da8a2 100644 --- a/crates/qbz-qt/build.rs +++ b/crates/qbz-qt/build.rs @@ -851,6 +851,7 @@ fn main() { "qml/settings/LocalLibrarySettings.qml", "qml/settings/LocalTabsConfigModal.qml", "qml/settings/OfflineSettings.qml", + "qml/settings/StorageSettings.qml", "qml/settings/PlaybackSettings.qml", // ONE component instantiated twice (Jellyfin + Subsonic). "qml/settings/MediaServerSettings.qml", diff --git a/crates/qbz-qt/qml/assets/icons/accent/database.svg b/crates/qbz-qt/qml/assets/icons/accent/database.svg new file mode 100644 index 000000000..e5ff4a218 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/accent/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/accent/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/accent/paintbrush-vertical.svg new file mode 100644 index 000000000..60c1563e2 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/accent/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/accent/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/accent/skip-back-10.svg new file mode 100644 index 000000000..35a583775 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/accent/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/accent/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/accent/skip-forward-10.svg new file mode 100644 index 000000000..07e1a7e05 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/accent/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/accent/unplug.svg b/crates/qbz-qt/qml/assets/icons/accent/unplug.svg new file mode 100644 index 000000000..d3dd5793e --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/accent/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/black/database.svg b/crates/qbz-qt/qml/assets/icons/black/database.svg new file mode 100644 index 000000000..464d13ddb --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/black/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/black/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/black/paintbrush-vertical.svg new file mode 100644 index 000000000..268ae7719 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/black/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/black/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/black/skip-back-10.svg new file mode 100644 index 000000000..5133614fa --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/black/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/black/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/black/skip-forward-10.svg new file mode 100644 index 000000000..29cfad18b --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/black/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/black/unplug.svg b/crates/qbz-qt/qml/assets/icons/black/unplug.svg new file mode 100644 index 000000000..f82dc0c40 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/black/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/muted/database.svg b/crates/qbz-qt/qml/assets/icons/muted/database.svg new file mode 100644 index 000000000..f0ec8db35 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/muted/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/muted/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/muted/paintbrush-vertical.svg new file mode 100644 index 000000000..4ee940e5b --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/muted/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/muted/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/muted/skip-back-10.svg new file mode 100644 index 000000000..6d4661aa1 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/muted/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/muted/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/muted/skip-forward-10.svg new file mode 100644 index 000000000..9a1dd31e0 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/muted/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/muted/unplug.svg b/crates/qbz-qt/qml/assets/icons/muted/unplug.svg new file mode 100644 index 000000000..071393c36 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/muted/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/primary/database.svg b/crates/qbz-qt/qml/assets/icons/primary/database.svg new file mode 100644 index 000000000..d26027369 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/primary/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/primary/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/primary/paintbrush-vertical.svg new file mode 100644 index 000000000..a9006fb77 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/primary/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/primary/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/primary/skip-back-10.svg new file mode 100644 index 000000000..365856fda --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/primary/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/primary/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/primary/skip-forward-10.svg new file mode 100644 index 000000000..37db948fc --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/primary/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/primary/unplug.svg b/crates/qbz-qt/qml/assets/icons/primary/unplug.svg new file mode 100644 index 000000000..f923b3612 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/primary/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/secondary/database.svg b/crates/qbz-qt/qml/assets/icons/secondary/database.svg new file mode 100644 index 000000000..f68524c4f --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/secondary/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/secondary/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/secondary/paintbrush-vertical.svg new file mode 100644 index 000000000..1bf1699cb --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/secondary/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/secondary/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/secondary/skip-back-10.svg new file mode 100644 index 000000000..788abc3c2 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/secondary/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/secondary/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/secondary/skip-forward-10.svg new file mode 100644 index 000000000..2cecf23c3 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/secondary/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/secondary/unplug.svg b/crates/qbz-qt/qml/assets/icons/secondary/unplug.svg new file mode 100644 index 000000000..7040653c3 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/secondary/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/warning/database.svg b/crates/qbz-qt/qml/assets/icons/warning/database.svg new file mode 100644 index 000000000..7e8d922da --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/warning/database.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/warning/paintbrush-vertical.svg b/crates/qbz-qt/qml/assets/icons/warning/paintbrush-vertical.svg new file mode 100644 index 000000000..5fc93c676 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/warning/paintbrush-vertical.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/warning/skip-back-10.svg b/crates/qbz-qt/qml/assets/icons/warning/skip-back-10.svg new file mode 100644 index 000000000..bfbeb3f23 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/warning/skip-back-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/warning/skip-forward-10.svg b/crates/qbz-qt/qml/assets/icons/warning/skip-forward-10.svg new file mode 100644 index 000000000..00d0dc62b --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/warning/skip-forward-10.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/crates/qbz-qt/qml/assets/icons/warning/unplug.svg b/crates/qbz-qt/qml/assets/icons/warning/unplug.svg new file mode 100644 index 000000000..bd3a90f85 --- /dev/null +++ b/crates/qbz-qt/qml/assets/icons/warning/unplug.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/qbz-qt/qml/rows/TrackRow.qml b/crates/qbz-qt/qml/rows/TrackRow.qml index 4e6675869..48fc9357a 100644 --- a/crates/qbz-qt/qml/rows/TrackRow.qml +++ b/crates/qbz-qt/qml/rows/TrackRow.qml @@ -507,6 +507,20 @@ Rectangle { } return false } + // "Show featured artists in track rows" (AppearanceSettings), ON by + // default: only an explicit false turns it off, so the rows never flash + // without names before the first settings snapshot lands. Same read as + // playIndicatorAnim otherwise: the settings document republishes on every + // settings write, which is the only time this re-evaluates. + readonly property bool showFeaturedArtists: { + var raw = QbzBridge.settingsJson + if (raw && raw.length > 2) { + try { + return JSON.parse(raw).showFeaturedArtists !== false + } catch (e) { /* fall through */ } + } + return true + } // The animated eq bars carry the playing state in the play cell when the // pref is ON (TrackPlayCell.slint:99-100 `show-bars`): only while this // row's track is actually PLAYING, at rest (hover reveals the pause @@ -966,17 +980,66 @@ Rectangle { } } Text { + id: artistLine width: parent.width visible: (root.item.artist || "") !== "" - text: root.item.artist || "" + // Main artist first, then the featured performers, one comma + // separated list. Local / media-server rows carry no + // `featured` and stay as they are. With links enabled and + // featured names present, every name is its own StyledText + // link: the main artist opens its page as before; a featured + // name opens its page when the album credits gave it an id + // and the search for that name otherwise. StyledText elides + // like plain text (probed: truncated stays true on one line). + readonly property var featured: root.showFeaturedArtists ? (root.item.featured || []) : [] + readonly property bool linkMode: root.artistLink && featured.length > 0 + function esc(s) { + return String(s).replace(/&/g, "&").replace(//g, ">") + } + function hex(c) { + return "#" + [c.r, c.g, c.b].map(function (v) { + return ("0" + Math.round(v * 255).toString(16)).slice(-2) + }).join("") + } + function link(href, name) { + var hot = artistLine.hoveredLink === href + return '' + esc(name) + '' + } + textFormat: linkMode ? Text.StyledText : Text.PlainText + text: { + var names = featured.map(function (f) { return f.name }) + if (!linkMode) + return (root.item.artist || "") + (names.length ? ", " + names.join(", ") : "") + var parts = [root.item.artistId ? link("main", root.item.artist) : esc(root.item.artist)] + for (var i = 0; i < featured.length; i++) + parts.push(link("f:" + i, featured[i].name)) + return parts.join(", ") + } + linkColor: theme.textMuted color: root.artistLink && root.item.artistId && artistLinkArea.containsMouse ? theme.textPrimary : theme.textMuted font.pixelSize: 12 elide: Text.ElideRight + onLinkActivated: function (href) { + if (href === "main") { + if (root.routeGoToExternally) root.goToRequested("artist") + else QbzArtist.openArtist(root.item.artistId) + return + } + var f = featured[parseInt(href.slice(2))] + if (!f) return + if (f.id) QbzArtist.openArtist(f.id) + else QbzSearch.searchSubmit(f.name) + } + HoverHandler { + enabled: artistLine.linkMode + cursorShape: artistLine.hoveredLink !== "" ? Qt.PointingHandCursor : Qt.ArrowCursor + } MouseArea { id: artistLinkArea anchors.fill: parent - enabled: root.artistLink && !!root.item.artistId + enabled: root.artistLink && !!root.item.artistId && !artistLine.linkMode hoverEnabled: true cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor // Same routing as the menu's "Go to artist" — Slint drives diff --git a/crates/qbz-qt/qml/settings/AppearanceSettings.qml b/crates/qbz-qt/qml/settings/AppearanceSettings.qml index 7ef3cc119..dd21a2f6b 100644 --- a/crates/qbz-qt/qml/settings/AppearanceSettings.qml +++ b/crates/qbz-qt/qml/settings/AppearanceSettings.qml @@ -289,6 +289,14 @@ Column { onToggled: function (v) { QbzBridge.settingsBool("show-volume-steppers", v) } } } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Show 10-second skip buttons", QbzSession.trRev) + description: QbzSession.tr("Add ±10 s buttons beside Previous and Next in the player bar.", QbzSession.trRev) + QbzToggle { kioskHost: root.kioskHost; + checked: root.doc.showSkipTen === true + onToggled: function (v) { QbzBridge.settingsBool("show-skip-ten", v) } + } + } SettingRow { kioskHost: root.kioskHost; label: QbzSession.tr("Startup page", QbzSession.trRev) description: QbzSession.tr("Choose which page to show when the app starts", QbzSession.trRev) @@ -326,6 +334,14 @@ Column { onToggled: function (v) { QbzBridge.settingsBool("play-indicator-animation", v) } } } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Show featured artists in track rows", QbzSession.trRev) + description: QbzSession.tr("List the track's featured performers after the main artist on Qobuz track rows, comma separated. Each name is a link. On by default.", QbzSession.trRev) + QbzToggle { kioskHost: root.kioskHost; + checked: root.doc.showFeaturedArtists === true + onToggled: function (v) { QbzBridge.settingsBool("show-featured-artists", v) } + } + } SettingRow { kioskHost: root.kioskHost; // Parked for a later visual pass. Keep the preference wiring intact so // restoring the experiment does not require a settings migration. diff --git a/crates/qbz-qt/qml/settings/OfflineSettings.qml b/crates/qbz-qt/qml/settings/OfflineSettings.qml index caef52619..ec3b44843 100644 --- a/crates/qbz-qt/qml/settings/OfflineSettings.qml +++ b/crates/qbz-qt/qml/settings/OfflineSettings.qml @@ -9,12 +9,13 @@ // snapshot). // // "Check now" IS shipped (`offline-recheck`); so is the live tri-state status -// line (QbzSession.offlineMode / captivePortal) and the lyrics-cache row. +// line (QbzSession.offlineMode / captivePortal). // -// Still missing: the whole OFFLINE CACHE group (Open manager / Open folder / -// Clear all). What blocks it is the MANAGER VIEW, which has no Qt counterpart -// yet — not the engine: `offline_cache_qt.rs` already runs the downloads from -// the album page and the track row. +// OFFLINE CACHE (Open manager / Open folder) is the downloads half and lives +// here too. Purging the whole cache is the manager's own trash glyph, with a +// tooltip and an explicit modal (OfflineManagerView.qml) — one destructive +// entry point, not two. The artwork and lyrics caches live in Settings > +// Storage (StorageSettings.qml) since 2026-09-13. import QtQuick import com.blitzfc.qbz @@ -28,10 +29,6 @@ Column { property var doc: ({}) readonly property var off: doc.offline || ({}) - /// The view-level SettingsConfirmHost (SettingsView.qml). Null in previews - /// — the Clear-all row guards, so a preview degrades to the unconfirmed - /// call rather than swallowing the click. - property var confirmHost: null QbzTheme { id: theme } @@ -106,11 +103,12 @@ Column { SettingsSpacer { } // ========================== OFFLINE CACHE ============================ - // The downloads half: the manager view plus the two whole-cache actions. - // All three ride QbzOffline, the same bridge the manager view uses — - // "Open folder" and "Clear all" are the manager's own stats-bar buttons, - // offered here too exactly as the reference offers them - // (OfflineSettings.slint:135-167). + // The downloads half: the manager view plus its folder. Both ride + // QbzOffline, the same bridge the manager view uses — "Open folder" is the + // manager's own stats-bar button, offered here too as the reference offers + // it (OfflineSettings.slint:135-167). The reference's "Clear all" row is + // deliberately NOT mirrored (2026-09-13): the manager's trash glyph is the + // one place the whole cache can be purged, tooltip and modal included. GroupHeader { kioskHost: root.kioskHost; text: QbzSession.tr("OFFLINE CACHE", QbzSession.trRev) } SettingRow { kioskHost: root.kioskHost; label: QbzSession.tr("Manage offline cache", QbzSession.trRev) @@ -128,47 +126,4 @@ Column { onClicked: QbzOffline.openFolder() } } - SettingRow { kioskHost: root.kioskHost; - label: QbzSession.tr("Clear cache", QbzSession.trRev) - description: QbzSession.tr("Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above.", QbzSession.trRev) - SettingsButton { kioskHost: root.kioskHost; - danger: true - text: QbzSession.tr("Clear all", QbzSession.trRev) - // ONE prompt before the purge. The reference fires straight from - // the button; this port confirms every destructive settings row, - // and undoing this one means re-downloading the whole cache. - onClicked: { - if (!root.confirmHost) { - QbzOffline.clearAll() - return - } - root.confirmHost.ask( - QbzSession.tr("Clear cache", QbzSession.trRev), - QbzSession.tr("Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above.", QbzSession.trRev), - QbzSession.tr("Clear all", QbzSession.trRev), - function () { QbzOffline.clearAll() }) - } - } - } - - SettingsSpacer { } - SettingsDivider { } - SettingsSpacer { } - - // ============================= LYRICS ================================ - GroupHeader { kioskHost: root.kioskHost; text: QbzSession.tr("LYRICS", QbzSession.trRev) } - SettingRow { kioskHost: root.kioskHost; - label: QbzSession.tr("Clear lyrics cache", QbzSession.trRev) - // "{} entries using {}" — the real per-user lyrics.db stats. - description: root.off.lyricsLoaded === true - ? QbzSession.tr("{} entries using {}", QbzSession.trRev) - .replace("{}", root.off.lyricsEntries) - .replace("{}", root.off.lyricsSize) - : "" - SettingsButton { kioskHost: root.kioskHost; - danger: true - text: QbzSession.tr("Clear", QbzSession.trRev) - onClicked: QbzBridge.settingsString("lyrics-cache-clear", "") - } - } } diff --git a/crates/qbz-qt/qml/settings/PlexSettings.qml b/crates/qbz-qt/qml/settings/PlexSettings.qml index 76dfd1ea4..d95a4fcf8 100644 --- a/crates/qbz-qt/qml/settings/PlexSettings.qml +++ b/crates/qbz-qt/qml/settings/PlexSettings.qml @@ -451,26 +451,5 @@ Column { } } } - SettingRow { kioskHost: root.kioskHost; - label: QbzSession.tr("Clear cache", QbzSession.trRev) - description: QbzSession.tr("Remove cached Plex libraries and tracks. Your sign-in is kept.", QbzSession.trRev) - SettingsButton { kioskHost: root.kioskHost; - danger: true - text: QbzSession.tr("Clear cache", QbzSession.trRev) - enabled: root.plex.hasToken === true - // plex_auth.rs:997-1001 — one prompt, sign-in kept. - onClicked: { - if (!root.confirmHost) { - QbzBridge.settingsString("plex-clear-cache", "") - return - } - root.confirmHost.ask( - QbzSession.tr("Clear Plex cache?", QbzSession.trRev), - QbzSession.tr("This removes cached Plex libraries and tracks. Your sign-in is kept.", QbzSession.trRev), - QbzSession.tr("Clear cache", QbzSession.trRev), - function () { QbzBridge.settingsString("plex-clear-cache", "") }) - } - } - } } } diff --git a/crates/qbz-qt/qml/settings/SettingsView.qml b/crates/qbz-qt/qml/settings/SettingsView.qml index 6e6248933..bf5a66f7d 100644 --- a/crates/qbz-qt/qml/settings/SettingsView.qml +++ b/crates/qbz-qt/qml/settings/SettingsView.qml @@ -9,15 +9,22 @@ // 1 Playback -> PlaybackSettings.qml // 2 Appearance -> AppearanceSettings.qml // 3 Offline -> OfflineSettings.qml +// 13 Storage -> StorageSettings.qml (artwork, lyrics and Plex caches) // 4 Local Library -> LocalLibrarySettings.qml (+ PlexSettings.qml) // 5 Blacklist -> BlacklistSettings.qml // 6 Integrations -> IntegrationsSettings.qml // 7 Developer -> DeveloperSettings.qml // 8 Flatpak/Snap -> SandboxSettings.qml (only on a sandboxed install) -// 9 Import/Export -> ImportExportSettings.qml (shown between -// Integrations and Developer; index 9 keeps the +// 9 Import/Export -> ImportExportSettings.qml (index 9 keeps the // persisted section numbers of 0-8 stable) // +// The sub-nav ORDER (2026-09-13) is not the index order: Audio, Playback, +// Appearance, Navigation, Local Library, Offline, Integrations, Updates, +// [Flatpak/Snap], then an ADVANCED fold (`advancedOpen`) holding Blacklist, +// Storage, Import / Export, Developer and Orbit. The fold opens itself when +// the current section lives inside it; "Share logs" stays pinned at the +// bottom of the column. +// // All state is ONE JSON document (QbzBridge.settingsJson, settings_qt.rs // SettingsDoc). Controls never keep local truth: they call the // settingsBool/Select/Slider/String invokables, Rust persists + applies + @@ -66,21 +73,36 @@ Item { // assignment destroys the binding it lands on, so a single surviving // `root.section = n` would work once and then re-introduce the bug one // navigation later, in a way that looks fixed under casual testing. + // Same order as the desktop column; the fold is flattened here because + // the kiosk selector is one list. readonly property var kioskSections: [ { label: QbzSession.tr("Audio", QbzSession.trRev), section: 0 }, { label: QbzSession.tr("Playback", QbzSession.trRev), section: 1 }, { label: QbzSession.tr("Appearance", QbzSession.trRev), section: 2 }, { label: QbzSession.tr("Navigation", QbzSession.trRev), section: 10 }, - { label: QbzSession.tr("Offline", QbzSession.trRev), section: 3 }, { label: QbzSession.tr("Local Library", QbzSession.trRev), section: 4 }, - { label: QbzSession.tr("Blacklist", QbzSession.trRev), section: 5 }, + { label: QbzSession.tr("Offline", QbzSession.trRev), section: 3 }, { label: QbzSession.tr("Integrations", QbzSession.trRev), section: 6 }, - { label: QbzSession.tr("Import / Export", QbzSession.trRev), section: 9 }, { label: QbzSession.tr("Updates", QbzSession.trRev), section: 12 }, + { label: QbzSession.tr("Blacklist", QbzSession.trRev), section: 5 }, + { label: QbzSession.tr("Storage", QbzSession.trRev), section: 13 }, + { label: QbzSession.tr("Import / Export", QbzSession.trRev), section: 9 }, { label: QbzSession.tr("Developer", QbzSession.trRev), section: 7 } ].concat(QbzOrbit.enabled ? [{ label: "Orbit", section: 11 }] : []).concat(root.sandboxed ? [{ label: (doc.dev || ({})).installMethod === "snap" ? QbzSession.tr("Snap", QbzSession.trRev) : QbzSession.tr("Flatpak", QbzSession.trRev), section: 8 }] : []) readonly property int section: QbzBridge.settingsSection === 11 && !QbzOrbit.enabled ? 0 : QbzBridge.settingsSection + /// The ADVANCED fold of the desktop sub-nav (Blacklist, Storage, + /// Import / Export, Developer, Orbit). Not persisted on purpose: it opens + /// itself whenever the current section lives inside it, so a restored or + /// programmatic selection is never hidden behind a closed fold, and it + /// stays open once opened until the next launch. + readonly property var advancedSections: [5, 13, 9, 7, 11] + property bool advancedOpen: false + function revealAdvanced() { + if (root.advancedSections.indexOf(root.section) >= 0) + root.advancedOpen = true + } + onSectionChanged: revealAdvanced() readonly property bool migrationRunning: (doc.importExport || ({})).migrationRunning === true @@ -96,7 +118,10 @@ Item { root.doc = ({}) } } - Component.onCompleted: reload() + Component.onCompleted: { + reload() + revealAdvanced() + } Connections { target: QbzBridge function onSettingsJsonChanged() { root.reload() } @@ -161,6 +186,10 @@ Item { property string name: "" property string label: "" property bool active: false + /// Extra left inset for the rows inside the ADVANCED fold. + property int indent: 0 + /// Optional right-aligned glyph — the fold's chevron. + property string trailing: "" signal clicked() width: parent ? parent.width : 0 @@ -186,8 +215,8 @@ Item { } Row { anchors.fill: parent - anchors.leftMargin: 12 - anchors.rightMargin: 12 + anchors.leftMargin: 12 + parent.indent + anchors.rightMargin: parent.trailing !== "" ? 36 : 12 spacing: 10 QbzIcon { name: parent.parent.name @@ -209,6 +238,21 @@ Item { verticalAlignment: Text.AlignVCenter } } + Loader { + active: parent.trailing !== "" + anchors.right: parent.right + anchors.rightMargin: 12 + anchors.verticalCenter: parent.verticalCenter + width: 16 + height: 16 + sourceComponent: QbzIcon { + name: snTrailingHost.trailing + width: 16 + height: 16 + tintName: "secondary" + } + readonly property Item snTrailingHost: parent + } MouseArea { id: snArea anchors.fill: parent @@ -241,7 +285,7 @@ Item { onClicked: QbzBridge.settingsSetSection(1) } SubNavItem { - name: "layers" + name: "paintbrush-vertical" label: QbzSession.tr("Appearance", QbzSession.trRev) active: root.section === 2 onClicked: QbzBridge.settingsSetSection(2) @@ -252,12 +296,6 @@ Item { active: root.section === 10 onClicked: QbzBridge.settingsSetSection(10) } - SubNavItem { - name: "cloud-download" - label: QbzSession.tr("Offline", QbzSession.trRev) - active: root.section === 3 - onClicked: QbzBridge.settingsSetSection(3) - } SubNavItem { name: "hard-drive" label: QbzSession.tr("Local Library", QbzSession.trRev) @@ -265,42 +303,23 @@ Item { onClicked: QbzBridge.settingsSetSection(4) } SubNavItem { - name: "blind-eye" - label: QbzSession.tr("Blacklist", QbzSession.trRev) - active: root.section === 5 - onClicked: QbzBridge.settingsSetSection(5) + name: "cloud-download" + label: QbzSession.tr("Offline", QbzSession.trRev) + active: root.section === 3 + onClicked: QbzBridge.settingsSetSection(3) } SubNavItem { - name: "refresh-cw" + name: "unplug" label: QbzSession.tr("Integrations", QbzSession.trRev) active: root.section === 6 onClicked: QbzBridge.settingsSetSection(6) } - SubNavItem { - name: "import" - label: QbzSession.tr("Import / Export", QbzSession.trRev) - active: root.section === 9 - onClicked: QbzBridge.settingsSetSection(9) - } SubNavItem { name: "refresh-cw" label: QbzSession.tr("Updates", QbzSession.trRev) active: root.section === 12 onClicked: QbzBridge.settingsSetSection(12) } - SubNavItem { - name: "bug" - label: QbzSession.tr("Developer", QbzSession.trRev) - active: root.section === 7 - onClicked: QbzBridge.settingsSetSection(7) - } - SubNavItem { - visible: QbzOrbit.enabled - name: "compass" - label: "Orbit" - active: root.section === 11 - onClicked: QbzBridge.settingsSetSection(11) - } // Sandboxed installs only (Flatpak / Snap permissions). SubNavItem { visible: root.sandboxed @@ -311,6 +330,57 @@ Item { active: root.section === 8 onClicked: QbzBridge.settingsSetSection(8) } + + // The ADVANCED fold: a disclosure row, not a section. It + // reads as active while it is closed over the selected + // page, so the column never shows nothing selected. + SubNavItem { + name: "sliders-horizontal" + trailing: root.advancedOpen ? "chevron-down" : "chevron-right" + label: QbzSession.tr("Advanced", QbzSession.trRev) + active: !root.advancedOpen && root.advancedSections.indexOf(root.section) >= 0 + onClicked: root.advancedOpen = !root.advancedOpen + } + SubNavItem { + visible: root.advancedOpen + indent: 16 + name: "blind-eye" + label: QbzSession.tr("Blacklist", QbzSession.trRev) + active: root.section === 5 + onClicked: QbzBridge.settingsSetSection(5) + } + SubNavItem { + visible: root.advancedOpen + indent: 16 + name: "database" + label: QbzSession.tr("Storage", QbzSession.trRev) + active: root.section === 13 + onClicked: QbzBridge.settingsSetSection(13) + } + SubNavItem { + visible: root.advancedOpen + indent: 16 + name: "import" + label: QbzSession.tr("Import / Export", QbzSession.trRev) + active: root.section === 9 + onClicked: QbzBridge.settingsSetSection(9) + } + SubNavItem { + visible: root.advancedOpen + indent: 16 + name: "bug" + label: QbzSession.tr("Developer", QbzSession.trRev) + active: root.section === 7 + onClicked: QbzBridge.settingsSetSection(7) + } + SubNavItem { + visible: root.advancedOpen && QbzOrbit.enabled + indent: 16 + name: "compass" + label: "Orbit" + active: root.section === 11 + onClicked: QbzBridge.settingsSetSection(11) + } } // Always-visible log affordance, pinned to the bottom of the @@ -474,6 +544,15 @@ Item { OfflineSettings { kioskHost: root.kioskHost; width: parent.width doc: root.doc + } + } + } + Panel { + panelIndex: 13 + sourceComponent: Component { + StorageSettings { kioskHost: root.kioskHost; + width: parent.width + doc: root.doc confirmHost: settingsConfirmHost } } diff --git a/crates/qbz-qt/qml/settings/StorageSettings.qml b/crates/qbz-qt/qml/settings/StorageSettings.qml new file mode 100644 index 000000000..6b780a0ee --- /dev/null +++ b/crates/qbz-qt/qml/settings/StorageSettings.qml @@ -0,0 +1,105 @@ +// Settings > Storage — the caches that have no section of their own: the +// shared artwork cache (new here, 2026-09-13), the lyrics cache (from +// Offline) and the Plex mirror (from Plex's danger zone). Each row still +// rides the bridge verb it always did. The offline downloads stay in +// Settings > Offline and the playback cache in Settings > Playback: both are +// part of how those features work, not just disk. + +import QtQuick +import com.blitzfc.qbz +import "../controls" +import "../theme" + +Column { + property bool kioskHost: false + + id: root + + property var doc: ({}) + readonly property var off: doc.offline || ({}) + readonly property var plex: (doc.library || ({})).plex || ({}) + /// The view-level SettingsConfirmHost (SettingsView.qml). Null in previews + /// — every destructive row guards, so a preview degrades to the + /// unconfirmed call rather than swallowing the click. + property var confirmHost: null + + QbzTheme { id: theme } + + spacing: 4 + + // ========================== ARTWORK CACHE ============================ + GroupHeader { kioskHost: root.kioskHost; text: QbzSession.tr("ARTWORK CACHE", QbzSession.trRev) } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Maximum size", QbzSession.trRev) + description: QbzSession.tr("Album and artist images are kept on disk up to this budget; the least recently shown are dropped first, during use and at startup.", QbzSession.trRev) + QbzSelect { kioskHost: root.kioskHost; + menuWidth: 160 + options: root.off.imageCacheSizes || [] + currentIndex: root.off.imageCacheSizeIndex || 0 + onSelected: function (i) { QbzBridge.settingsSelect("image-cache-max", i) } + } + } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Clear artwork cache", QbzSession.trRev) + // "{} images using {}" — the shared image cache's own stats. + description: root.off.imageCacheLoaded === true + ? QbzSession.tr("{} images using {}", QbzSession.trRev) + .replace("{}", root.off.imageCacheFiles) + .replace("{}", root.off.imageCacheSize) + : "" + SettingsButton { kioskHost: root.kioskHost; + danger: true + text: QbzSession.tr("Clear", QbzSession.trRev) + onClicked: QbzBridge.settingsString("image-cache-clear", "") + } + } + + SettingsSpacer { } + SettingsDivider { } + SettingsSpacer { } + + // ============================= LYRICS ================================ + GroupHeader { kioskHost: root.kioskHost; text: QbzSession.tr("LYRICS", QbzSession.trRev) } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Clear lyrics cache", QbzSession.trRev) + // "{} entries using {}" — the real per-user lyrics.db stats. + description: root.off.lyricsLoaded === true + ? QbzSession.tr("{} entries using {}", QbzSession.trRev) + .replace("{}", root.off.lyricsEntries) + .replace("{}", root.off.lyricsSize) + : "" + SettingsButton { kioskHost: root.kioskHost; + danger: true + text: QbzSession.tr("Clear", QbzSession.trRev) + onClicked: QbzBridge.settingsString("lyrics-cache-clear", "") + } + } + + SettingsSpacer { } + SettingsDivider { } + SettingsSpacer { } + + // ============================ PLEX CACHE ============================= + GroupHeader { kioskHost: root.kioskHost; text: QbzSession.tr("PLEX CACHE", QbzSession.trRev) } + SettingRow { kioskHost: root.kioskHost; + label: QbzSession.tr("Clear cache", QbzSession.trRev) + description: QbzSession.tr("Remove cached Plex libraries and tracks. Your sign-in is kept.", QbzSession.trRev) + SettingsButton { kioskHost: root.kioskHost; + danger: true + text: QbzSession.tr("Clear cache", QbzSession.trRev) + enabled: root.plex.hasToken === true + // plex_auth.rs:997-1001 — one prompt, sign-in kept. + onClicked: { + if (!root.confirmHost) { + QbzBridge.settingsString("plex-clear-cache", "") + return + } + root.confirmHost.ask( + QbzSession.tr("Clear Plex cache?", QbzSession.trRev), + QbzSession.tr("This removes cached Plex libraries and tracks. Your sign-in is kept.", QbzSession.trRev), + QbzSession.tr("Clear cache", QbzSession.trRev), + function () { QbzBridge.settingsString("plex-clear-cache", "") }) + } + } + } +} diff --git a/crates/qbz-qt/qml/shell/NowPlayingBarSmall.qml b/crates/qbz-qt/qml/shell/NowPlayingBarSmall.qml index 6de2342aa..5ac6f5f70 100644 --- a/crates/qbz-qt/qml/shell/NowPlayingBarSmall.qml +++ b/crates/qbz-qt/qml/shell/NowPlayingBarSmall.qml @@ -320,6 +320,7 @@ Rectangle { id: centreTransport anchors.centerIn: parent height: 34 + compact: root.width < 900 playCircle: false favorite: root.npFavorite ephemeral: root.npEphemeral @@ -531,6 +532,20 @@ Rectangle { // idiom: a raw JSON.parse in a binding throws on the pre-publish frame and // takes the whole bar down with it. readonly property var settingsDoc: parseSettings() + // A-B loop entries for the "+" menu (see PlayerBar.abEntries): local + // playback only. + function abEntries() { + if (QbzPlayer.npIsRemote || QbzPlayer.npCastActive) + return [] + var m = [{ "sep": true }] + if (QbzPlayer.abState === 0) + m.push({ "label": QbzSession.tr("Set loop start (A)", QbzSession.trRev), "icon": "repeat", "action": "ab-mark" }) + else if (QbzPlayer.abState === 1) + m.push({ "label": QbzSession.tr("Set loop end (B)", QbzSession.trRev), "icon": "repeat", "action": "ab-mark" }) + if (QbzPlayer.abState !== 0) + m.push({ "label": QbzSession.tr("Clear loop", QbzSession.trRev), "icon": "x", "action": "ab-clear" }) + return m + } function parseSettings() { try { return JSON.parse(QbzBridge.settingsJson) @@ -567,7 +582,7 @@ Rectangle { m.push({ "label": QbzSession.tr("Play later", QbzSession.trRev), "icon": "list-plus", "action": "later" }) m.push({ "label": QbzSession.tr("Play next", QbzSession.trRev), "icon": "list-start", "action": "next" }) if (root.npEphemeral) - return m + return m.concat(root.abEntries()) // "Add to playlist" is SECOND (TransportControls.slint:143 — the // full bar carries the rationale). Same `npSource` gate as the // mixtape entry: the picker's Qobuz arm takes catalog ids and an @@ -596,7 +611,7 @@ Rectangle { "action": "album-favorite" }) } - return m + return m.concat(root.abEntries()) } onPicked: function (a) { var id = QbzPlayer.npTrackId @@ -611,6 +626,10 @@ Rectangle { } else if (a === "album-favorite") { if (QbzPlayer.npAlbumId !== "") QbzLibrary.libraryToggleFavorite("album", QbzPlayer.npAlbumId) + } else if (a === "ab-mark") { + QbzPlayer.abMark() + } else if (a === "ab-clear") { + QbzPlayer.abClear() } else if (a === "mixtape") { // MyQBZ AddItem, built here from the now-playing state: // `npArtworkPath` is a file:// CACHE path, so it is NOT the diff --git a/crates/qbz-qt/qml/shell/PlayerBar.qml b/crates/qbz-qt/qml/shell/PlayerBar.qml index bb4354909..6e2113116 100644 --- a/crates/qbz-qt/qml/shell/PlayerBar.qml +++ b/crates/qbz-qt/qml/shell/PlayerBar.qml @@ -126,6 +126,20 @@ Rectangle { // AppearanceState.show-volume-steppers (PlayerBar.slint gates the −/+ // pair on it; Tauri always showed them). readonly property bool showVolumeSteppers: settingsDoc.showVolumeSteppers === true + // A-B loop entries for the "+" menu: one contextual verb + clear. Local + // playback only — the loop cannot follow a cast / Connect renderer. + function abEntries() { + if (QbzPlayer.npIsRemote || QbzPlayer.npCastActive) + return [] + var m = [{ "sep": true }] + if (QbzPlayer.abState === 0) + m.push({ "label": QbzSession.tr("Set loop start (A)", QbzSession.trRev), "icon": "repeat", "action": "ab-mark" }) + else if (QbzPlayer.abState === 1) + m.push({ "label": QbzSession.tr("Set loop end (B)", QbzSession.trRev), "icon": "repeat", "action": "ab-mark" }) + if (QbzPlayer.abState !== 0) + m.push({ "label": QbzSession.tr("Clear loop", QbzSession.trRev), "icon": "x", "action": "ab-clear" }) + return m + } // Favorite state of the now-playing track (Slint: // QueueState.now-playing-favorite). The queue document carries it on its @@ -426,6 +440,32 @@ Rectangle { x: parent.width * seekRow.visualProgress - width / 2 anchors.verticalCenter: parent.verticalCenter } + // A-B loop: the tinted section + two ticks. Static bindings only + // (no animation), so nothing here touches the repaint pulse. + Rectangle { + visible: QbzPlayer.abState === 2 && QbzPlayer.npDurationSecs > 0 + x: parent.width * (QbzPlayer.abStartSecs / Math.max(QbzPlayer.npDurationSecs, 1)) + width: Math.max(2, parent.width + * ((QbzPlayer.abEndSecs - QbzPlayer.abStartSecs) / Math.max(QbzPlayer.npDurationSecs, 1))) + height: parent.height + radius: 2 + color: Qt.rgba(theme.accent.r, theme.accent.g, theme.accent.b, 0.28) + } + Repeater { + model: QbzPlayer.abState === 0 ? [] + : (QbzPlayer.abState === 1 ? [QbzPlayer.abStartSecs] + : [QbzPlayer.abStartSecs, QbzPlayer.abEndSecs]) + Rectangle { + required property int modelData + visible: QbzPlayer.npDurationSecs > 0 + width: 2 + height: 10 + radius: 1 + color: theme.accent + x: seekTrack.width * (modelData / Math.max(QbzPlayer.npDurationSecs, 1)) - 1 + anchors.verticalCenter: parent.verticalCenter + } + } } Text { anchors.right: parent.right @@ -605,6 +645,7 @@ Rectangle { TransportControls { id: classicTransport visible: root.isClassic + compact: root.width < 1100 anchors.left: parent.left anchors.verticalCenter: parent.verticalCenter playCircle: false @@ -630,6 +671,7 @@ Rectangle { TransportControls { id: centreTransport visible: !root.isClassic + compact: root.width < 1366 anchors.centerIn: parent playCircle: true favorite: root.npFavorite @@ -885,7 +927,7 @@ Rectangle { m.push({ "label": QbzSession.tr("Play later", QbzSession.trRev), "icon": "list-plus", "action": "later" }) m.push({ "label": QbzSession.tr("Play next", QbzSession.trRev), "icon": "list-start", "action": "next" }) if (root.npEphemeral) - return m + return m.concat(root.abEntries()) // "Add to playlist" sits SECOND in TransportControls.slint:143 — // spliced in there rather than appended, because the flyout's // order is part of the parity. It rides the SAME `npSource` gate @@ -917,7 +959,7 @@ Rectangle { "action": "album-favorite" }) } - return m + return m.concat(root.abEntries()) } onPicked: function (a) { var id = QbzPlayer.npTrackId @@ -932,6 +974,10 @@ Rectangle { } else if (a === "album-favorite") { if (QbzPlayer.npAlbumId !== "") QbzLibrary.libraryToggleFavorite("album", QbzPlayer.npAlbumId) + } else if (a === "ab-mark") { + QbzPlayer.abMark() + } else if (a === "ab-clear") { + QbzPlayer.abClear() } else if (a === "mixtape") { // MyQBZ AddItem, built here from the now-playing state: // `npArtworkPath` is a file:// CACHE path, so it is NOT the diff --git a/crates/qbz-qt/qml/shell/TransportControls.qml b/crates/qbz-qt/qml/shell/TransportControls.qml index a8cc8870c..b262b6515 100644 --- a/crates/qbz-qt/qml/shell/TransportControls.qml +++ b/crates/qbz-qt/qml/shell/TransportControls.qml @@ -27,6 +27,10 @@ Row { property bool ephemeral: false /// AppShell's one shared hover-tooltip overlay. property var tooltip: null + /// A host whose zone cannot fit the ±10 s pair (see PlayerBar's column + /// budget) sets this; the pair then hides even with the pref on. + property bool compact: false + readonly property bool skipTenVisible: QbzPlayer.showSkipTen && !tc.compact /// Emitted by "+" with the button as anchor, so the flyout is owned /// by the bar (one menu, both mount points). @@ -94,6 +98,16 @@ Row { } } + QbzIconButton { + visible: tc.skipTenVisible + name: "skip-back-10" + btnEnabled: QbzPlayer.npHasTrack + anchors.verticalCenter: parent.verticalCenter + onClicked: QbzPlayer.seekBy(-10) + tooltip: tc.tooltip + tooltipKey: "npb-skip-back-10" + tooltipText: QbzSession.tr("Back 10 seconds", QbzSession.trRev) + } QbzIconButton { name: "skip-back" btnEnabled: QbzPlayer.npHasTrack @@ -166,6 +180,16 @@ Row { anchors.verticalCenter: parent.verticalCenter onClicked: QbzPlayer.next() } + QbzIconButton { + visible: tc.skipTenVisible + name: "skip-forward-10" + btnEnabled: QbzPlayer.npHasTrack + anchors.verticalCenter: parent.verticalCenter + onClicked: QbzPlayer.seekBy(10) + tooltip: tc.tooltip + tooltipKey: "npb-skip-forward-10" + tooltipText: QbzSession.tr("Forward 10 seconds", QbzSession.trRev) + } QbzIconButton { name: QbzPlayer.npRepeatMode === 2 ? "repeat-1" : "repeat" active: QbzPlayer.npRepeatMode > 0 diff --git a/crates/qbz-qt/qml/views/OfflineManagerView.qml b/crates/qbz-qt/qml/views/OfflineManagerView.qml index 71e917612..adb303195 100644 --- a/crates/qbz-qt/qml/views/OfflineManagerView.qml +++ b/crates/qbz-qt/qml/views/OfflineManagerView.qml @@ -174,6 +174,9 @@ Rectangle { id: gb property string name: "" property string tint: "muted" + /// Hover tooltip text, shown by the view's QbzTooltip overlay ("" = + /// none). Icon-only buttons get one; the row glyphs have their labels. + property string tip: "" signal clicked() width: root.kioskHost ? 44 : 30 height: root.kioskHost ? 44 : 30 @@ -191,7 +194,11 @@ Rectangle { anchors.fill: parent hoverEnabled: true cursorShape: Qt.PointingHandCursor - onClicked: gb.clicked() + onClicked: { + tips.hide("ghost-" + gb.name) + gb.clicked() + } + onContainsMouseChanged: tips.hover(containsMouse, gb, "ghost-" + gb.name, gb.tip) } } @@ -270,17 +277,23 @@ Rectangle { GhostBtn { anchors.verticalCenter: parent.verticalCenter name: "check" + tip: QbzSession.tr("Apply the size limit", QbzSession.trRev) onClicked: QbzOffline.setLimit(parseInt(limitField.text) || 0) } GhostBtn { anchors.verticalCenter: parent.verticalCenter name: "folder" + tip: QbzSession.tr("Open the cache folder", QbzSession.trRev) onClicked: QbzOffline.openFolder() } + // The ONE place the whole offline cache can be purged (the + // Settings row that mirrored it was dropped 2026-09-13): a + // tooltip says so before the click, the modal says what goes. GhostBtn { anchors.verticalCenter: parent.verticalCenter name: "trash-2" tint: "warning" + tip: QbzSession.tr("Clear the whole offline cache…", QbzSession.trRev) onClicked: clearConfirm.open() } } @@ -643,19 +656,32 @@ Rectangle { } // Clear-all confirmation. The Slint fires it straight from the trash glyph; - // this port asks first, the way every other destructive row in Settings - // does (SettingsConfirmHost). Purging the cache can be an hours-long - // re-download and there is no undo. + // this port asks first. Purging the cache can be an hours-long re-download + // and there is no undo, so the body says exactly what goes (the live + // count and size from the stats bar) and what stays (purchased downloads + // in the music folder — a different tree, never touched by clear_all). QbzConfirmModal { - kioskHost: root.kioskHost + kioskHost: root.kioskHost id: clearConfirm // Fills the VIEW, like BlacklistManagerView.qml:523 — without it the // modal has no size and its scrim covers nothing. anchors.fill: parent - title: QbzSession.tr("Clear cache", QbzSession.trRev) - body: QbzSession.tr("Frees up cached data. Your downloaded albums are kept — remove those from the offline manager above.", QbzSession.trRev) + title: QbzSession.tr("Clear the offline cache?", QbzSession.trRev) + body: QbzSession.tr("Removes everything saved for offline listening: {} using {}. Purchased downloads in your music folder are kept; anything cleared has to be downloaded again to play offline.", QbzSession.trRev) + .replace("{}", root.doc.tracksText || "") + .replace("{}", root.doc.sizeText || "") confirmLabel: QbzSession.tr("Clear all", QbzSession.trRev) danger: true onConfirmed: QbzOffline.clearAll() } + + // Hover tooltips for the icon-only stats-bar buttons. QbzTooltip is the + // shared overlay; it takes no pointer and owns no animator, so an idle + // one costs nothing (ArtistSceneView.qml mounts it the same way). Below + // the modal's z (ADR-009), so an open confirmation always covers it. + QbzTooltip { + id: tips + anchors.fill: parent + z: 900 + } } diff --git a/crates/qbz-qt/src/ab_loop_qt.rs b/crates/qbz-qt/src/ab_loop_qt.rs new file mode 100644 index 000000000..06091ba42 --- /dev/null +++ b/crates/qbz-qt/src/ab_loop_qt.rs @@ -0,0 +1,265 @@ +//! A-B loop (player bar "+" menu): repeat a section of the CURRENT track. +//! +//! Process-lifetime, never persisted. Cleared on track change, stop, remote +//! takeover (cast / QConnect) and on a manual seek outside the section. The +//! watcher is a 100 ms task that only exists while a loop is active; it reads +//! the player's millisecond position (a read-only derivation) and issues the +//! same local seek the seekbar does. The audio thread is untouched. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +use qbz_app::shell::AppRuntime; +use qbz_core::LoggingAdapter; + +/// B must sit at least this far after A. +const MIN_LOOP_MS: u64 = 2_000; +const WATCH_INTERVAL: Duration = Duration::from_millis(100); +/// Fire this much before B so the jump lands on B, not past it. +const LEAD_MS: u64 = 60; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Loop { + pub track_id: u64, + /// Whole seconds: `core.seek` is second-granular. + pub a_secs: u64, + /// Milliseconds: the watcher compares against the ms position. + pub b_ms: Option, +} + +static STATE: OnceLock>> = OnceLock::new(); +/// Bumped on every clear / re-arm; a watcher exits when its value differs. +static GENERATION: AtomicU64 = AtomicU64::new(0); + +fn slot() -> &'static Mutex> { + STATE.get_or_init(|| Mutex::new(None)) +} + +pub(crate) fn current() -> Option { + *slot().lock().unwrap_or_else(|p| p.into_inner()) +} + +/// 0 = no loop, 1 = A armed (waiting for B), 2 = looping. +fn state_code(l: Option) -> i32 { + match l { + None => 0, + Some(Loop { b_ms: None, .. }) => 1, + Some(_) => 2, + } +} + +/// What one press of the single "mark" verb does. +fn next_after_mark(cur: Option, track_id: u64, pos_ms: u64) -> Option { + match cur { + Some(l) if l.track_id == track_id => match l.b_ms { + None if pos_ms >= l.a_secs * 1000 + MIN_LOOP_MS => Some(Loop { + b_ms: Some(pos_ms), + ..l + }), + None => Some(l), + Some(_) => None, + }, + _ => Some(Loop { + track_id, + a_secs: pos_ms / 1000, + b_ms: None, + }), + } +} + +fn should_jump(l: &Loop, pos_ms: u64) -> bool { + matches!(l.b_ms, Some(b) if pos_ms + LEAD_MS >= b) +} + +/// A manual seek keeps the loop only while it lands inside the section +/// (or, with only A armed, at/after A). +fn survives_manual_seek(l: &Loop, target_secs: u64) -> bool { + if target_secs < l.a_secs { + return false; + } + match l.b_ms { + Some(b) => target_secs * 1000 <= b, + None => true, + } +} + +fn publish(l: Option) { + let state = state_code(l); + let a = l.map(|l| l.a_secs as i32).unwrap_or(0); + let b = l + .and_then(|l| l.b_ms) + .map(|b| (b / 1000) as i32) + .unwrap_or(0); + crate::player_bridge::ui(move |mut bridge| { + bridge.as_mut().set_ab_state(state); + bridge.as_mut().set_ab_start_secs(a); + bridge.as_mut().set_ab_end_secs(b); + }); +} + +fn set(l: Option) { + *slot().lock().unwrap_or_else(|p| p.into_inner()) = l; + GENERATION.fetch_add(1, Ordering::SeqCst); + publish(l); +} + +pub(crate) fn clear() { + if current().is_some() { + log::info!("[qbz-qt] A-B loop cleared"); + set(None); + } +} + +/// The "+" menu verb: arm A, then B, then clear. Local playback only. +pub(crate) async fn mark(runtime: Arc>) { + if crate::now_playing::remote_or_cast_active() { + log::info!("[qbz-qt] A-B loop: ignored while playback is remote"); + return; + } + let event = runtime.core().player().get_playback_event(); + if event.track_id == 0 || event.duration == 0 { + return; + } + let pos_ms = runtime.core().player().state.current_position_ms(); + let next = next_after_mark(current(), event.track_id, pos_ms); + log::info!("[qbz-qt] A-B loop: mark at {pos_ms} ms -> {next:?}"); + set(next); + if matches!(next, Some(Loop { b_ms: Some(_), .. })) { + spawn_watcher(runtime); + } +} + +fn spawn_watcher(runtime: Arc>) { + let my_gen = GENERATION.load(Ordering::SeqCst); + crate::spawn(async move { + let mut ticker = tokio::time::interval(WATCH_INTERVAL); + loop { + ticker.tick().await; + if GENERATION.load(Ordering::SeqCst) != my_gen { + return; + } + let Some(l) = current() else { return }; + if l.b_ms.is_none() { + return; + } + if crate::now_playing::remote_or_cast_active() { + clear(); + return; + } + let event = runtime.core().player().get_playback_event(); + if event.track_id != l.track_id { + clear(); + return; + } + if !event.is_playing { + continue; + } + if should_jump(&l, runtime.core().player().state.current_position_ms()) { + crate::playback_qt::seek_local_secs(&runtime, l.a_secs).await; + } + } + }); +} + +/// Poll-loop track edge (and stop: `track_id == 0`). +pub(crate) fn on_track_changed(track_id: u64) { + if let Some(l) = current() { + if l.track_id != track_id { + clear(); + } + } +} + +/// Every user seek funnels through `playback_qt::seek_frac`; the watcher's +/// own jump uses `seek_local_secs` directly and never reaches here. +pub(crate) fn on_manual_seek(target_secs: u64) { + if let Some(l) = current() { + if !survives_manual_seek(&l, target_secs) { + clear(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mark_arms_a_then_b_then_clears() { + let armed = next_after_mark(None, 7, 12_400); + assert_eq!( + armed, + Some(Loop { + track_id: 7, + a_secs: 12, + b_ms: None + }) + ); + // B too close to A is ignored (the loop stays armed on A). + assert_eq!(next_after_mark(armed, 7, 13_900), armed); + let active = next_after_mark(armed, 7, 30_250); + assert_eq!( + active, + Some(Loop { + track_id: 7, + a_secs: 12, + b_ms: Some(30_250) + }) + ); + assert_eq!(next_after_mark(active, 7, 40_000), None); + // A different track always starts over. + assert_eq!( + next_after_mark(active, 8, 5_000), + Some(Loop { + track_id: 8, + a_secs: 5, + b_ms: None + }) + ); + } + + #[test] + fn the_watcher_jumps_just_before_b_and_a_manual_seek_outside_the_section_clears() { + let l = Loop { + track_id: 7, + a_secs: 12, + b_ms: Some(30_250), + }; + assert!(!should_jump(&l, 29_000)); + assert!(should_jump(&l, 30_200)); + assert!(should_jump(&l, 31_000)); + assert!(survives_manual_seek(&l, 12)); + assert!(survives_manual_seek(&l, 25)); + assert!(!survives_manual_seek(&l, 11)); + assert!(!survives_manual_seek(&l, 31)); + let armed = Loop { + track_id: 7, + a_secs: 12, + b_ms: None, + }; + assert!(survives_manual_seek(&armed, 20)); + assert!(!survives_manual_seek(&armed, 3)); + } + + #[test] + fn state_codes() { + assert_eq!(state_code(None), 0); + assert_eq!( + state_code(Some(Loop { + track_id: 1, + a_secs: 0, + b_ms: None + })), + 1 + ); + assert_eq!( + state_code(Some(Loop { + track_id: 1, + a_secs: 0, + b_ms: Some(5_000) + })), + 2 + ); + } +} diff --git a/crates/qbz-qt/src/album_qt.rs b/crates/qbz-qt/src/album_qt.rs index 679e6d01c..6f022e4d5 100644 --- a/crates/qbz-qt/src/album_qt.rs +++ b/crates/qbz-qt/src/album_qt.rs @@ -30,6 +30,7 @@ use std::time::Instant; use cxx_qt_lib::QString; use qbz_app::shell::AppRuntime; use qbz_core::LoggingAdapter; +use qbz_models::types::AlbumArtist; use qbz_models::{Album, Track}; use serde::{Deserialize, Serialize}; use serde_json::json; @@ -41,6 +42,11 @@ const RELEASE_PAGE_SIZE: u32 = 20; #[derive(Clone, Default, Serialize)] pub struct TrackRow { + /// Featured performers, main artist excluded; `id` is the Qobuz artist id + /// when the album credits name the same person, "" otherwise (the row + /// then falls back to a search by name). Empty when none. + #[serde(rename = "featured")] + pub featured: Vec, pub id: String, pub number: String, pub title: String, @@ -509,7 +515,42 @@ fn build_credits(album: &Album) -> Vec<(String, String, String)> { } /// album.rs `map_track` (with work headers for classical albums). -fn map_track(track: &Track) -> TrackRow { +/// One featured performer on a track row (see `TrackRow::featured`). +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct FeaturedArtist { + pub name: String, + /// Qobuz artist id as a string, "" when unknown. + pub id: String, +} + +/// The row's featured performers (empty = nothing to add). Qobuz rows only — +/// local / media-server rows never carry `performers`. `credits` are the +/// album-level artists (id + roles) when the caller has them: a featured +/// name that matches a credit gets that credit's id and links straight to +/// the artist page; any other name links to a search. +pub(crate) fn featured_list( + performers: Option<&str>, + artist: &str, + title: &str, + credits: &[AlbumArtist], +) -> Vec { + let Some(performers) = performers else { + return Vec::new(); + }; + qbz_qobuz::performers::featured_artists(performers, artist, title) + .into_iter() + .map(|name| { + let id = credits + .iter() + .find(|c| qbz_qobuz::performers::same_artist_name(&c.name, &name)) + .map(|c| c.id.to_string()) + .unwrap_or_default(); + FeaturedArtist { name, id } + }) + .collect() +} + +fn map_track(track: &Track, credits: &[AlbumArtist]) -> TrackRow { let work = track .work .as_ref() @@ -536,6 +577,7 @@ fn map_track(track: &Track) -> TrackRow { .map(|p| (p.name.clone(), p.id.to_string())) .unwrap_or_default(); TrackRow { + featured: featured_list(track.performers.as_deref(), &artist, &track.title, credits), is_favorite: crate::fav_cache_qt::contains_track(track.id), id: track.id.to_string(), number: track.track_number.to_string(), @@ -666,10 +708,11 @@ pub async fn load_album( let booklet_url = pick_booklet_url(&album); set_booklet_stash(&title, &booklet_url); + let artist_credits: &[AlbumArtist] = album.artists.as_deref().unwrap_or(&[]); let tracks: Vec = album .tracks .as_ref() - .map(|container| container.items.iter().map(map_track).collect()) + .map(|container| container.items.iter().map(|t| map_track(t, artist_credits)).collect()) .unwrap_or_default(); // External links are built from the SAME artist/title the header shows. @@ -1496,3 +1539,34 @@ fn spawn_deferred_rows( publish_row(generation, "similarAlbums", "similarLoading", &similar); }); } + +#[cfg(test)] +mod tests { + use super::*; + + fn credit(id: u64, name: &str, role: &str) -> AlbumArtist { + AlbumArtist { + id, + name: name.into(), + roles: Some(vec![role.into()]), + } + } + + #[test] + fn featured_list_resolves_ids_from_the_album_credits_and_leaves_the_rest_searchable() { + let performers = "Alice, MainArtist - Bob, FeaturedArtist - Carol, Vocalist, FeaturedArtist"; + let credits = [credit(1, "Alice", "main-artist"), credit(2, "bob", "featured-artist")]; + assert_eq!( + featured_list(Some(performers), "Alice", "Song", &credits), + vec![ + FeaturedArtist { name: "Bob".into(), id: "2".into() }, + FeaturedArtist { name: "Carol".into(), id: String::new() }, + ] + ); + assert!(featured_list(None, "Alice", "Song", &credits).is_empty()); + assert_eq!( + featured_list(Some(performers), "Alice", "Song", &[])[0], + FeaturedArtist { name: "Bob".into(), id: String::new() } + ); + } +} diff --git a/crates/qbz-qt/src/artist_qt.rs b/crates/qbz-qt/src/artist_qt.rs index 377cb2f08..7e63ab452 100644 --- a/crates/qbz-qt/src/artist_qt.rs +++ b/crates/qbz-qt/src/artist_qt.rs @@ -594,6 +594,7 @@ fn map_track(index: usize, track: PageArtistTrack) -> TrackRow { .and_then(|r| r.streamable) .unwrap_or(true); TrackRow { + featured: Vec::new(), is_favorite: crate::fav_cache_qt::contains_track(track.id), id: track.id.to_string(), cache_status: if crate::offline_qt::is_cached(&track.id.to_string()) { diff --git a/crates/qbz-qt/src/artwork_qt.rs b/crates/qbz-qt/src/artwork_qt.rs index 57c2796f6..fdf90abe3 100644 --- a/crates/qbz-qt/src/artwork_qt.rs +++ b/crates/qbz-qt/src/artwork_qt.rs @@ -51,7 +51,9 @@ //! [`housekeeping`] runs on the blocking pool at boot and bounds BOTH caches: //! the SHARED `~/.cache/qbz/images` (the full-size originals `store` writes; //! `qbz_cache::ImageCacheService`, SQLite `last_accessed` LRU, budget -//! [`MAX_SHARED_BYTES`], trimmed in [`EVICT_BATCH_ENTRIES`]-row batches so the +//! [`shared_budget_bytes`] (a Settings preference, 200 MB by default), trimmed +//! at boot and again every [`TRIM_EVERY_BYTES`] of new originals, in +//! [`EVICT_BATCH_ENTRIES`]-row batches so the //! GUI thread is never parked behind a long unlink loop) and this module's //! OWN derivative directory `images/scaled` ([`MAX_SCALED_BYTES`], LRU by //! mtime, plus the one-time `.jpg` orphan sweep). The shared trim was the @@ -61,6 +63,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, LazyLock, Mutex, OnceLock, RwLock}; use qbz_cache::ImageCacheService; @@ -583,6 +586,7 @@ async fn fetch_jobs_with_ready(jobs: Vec<(String, String)>, ready: Option Option { /// order of magnitude under the 260 MB the parent image cache already holds. const MAX_SCALED_BYTES: u64 = 64 * 1024 * 1024; -/// Byte budget for the SHARED cache (`~/.cache/qbz/images`): the Slint app's -/// `MAX_CACHE_BYTES` ("matches the Tauri default"), restored unchanged. -const MAX_SHARED_BYTES: u64 = 200 * 1024 * 1024; +/// Default byte budget for the SHARED cache (`~/.cache/qbz/images`): the +/// Tauri/Slint default, now a preference (`ui_prefs` `image_cache_max_mb`, +/// Settings > Offline > Artwork cache). +pub(crate) const DEFAULT_SHARED_BUDGET_MB: u64 = 200; + +/// The budget in bytes, from the preference (0 / absent = the default). +pub(crate) fn shared_budget_bytes() -> u64 { + crate::settings_qt::pref_json("image_cache_max_mb") + .and_then(|v| v.as_u64()) + .filter(|mb| *mb > 0) + .unwrap_or(DEFAULT_SHARED_BUDGET_MB) + * 1024 + * 1024 +} /// Rows deleted per `evict` call; the cache mutex is released between calls. const EVICT_BATCH_ENTRIES: usize = 64; +/// Bytes stored since the last trim. The Tauri app evicted after EVERY +/// store; here a trim runs on the blocking pool once this many new bytes +/// have landed, so the directory can never sit more than this far above +/// the budget between the boot trim and the next one (an early release +/// grew the folder to 1 GB — never again). +const TRIM_EVERY_BYTES: u64 = 16 * 1024 * 1024; +static STORED_SINCE_TRIM: AtomicU64 = AtomicU64::new(0); +static TRIM_IN_FLIGHT: AtomicBool = AtomicBool::new(false); + +/// Account for a freshly stored original. Returns true when a trim is due +/// (the counter is reset by the caller that takes the trim). +fn trim_due_after(counter: &AtomicU64, stored: u64) -> bool { + counter.fetch_add(stored, Ordering::Relaxed) + stored >= TRIM_EVERY_BYTES +} + +fn note_stored(stored: usize) { + if !trim_due_after(&STORED_SINCE_TRIM, stored as u64) { + return; + } + STORED_SINCE_TRIM.store(0, Ordering::Relaxed); + trim_shared_now(); +} + +/// Trim the shared cache to its budget on the blocking pool (a budget +/// change, or the running counter above); one trim in flight at a time. +pub(crate) fn trim_shared_now() { + if TRIM_IN_FLIGHT.swap(true, Ordering::SeqCst) { + return; + } + tokio::task::spawn_blocking(|| { + if let Some(freed) = evict_shared(shared_budget_bytes()) { + if freed > 0 { + log::info!("[qbz-qt][perf] image cache trimmed {freed} B (budget {} B)", shared_budget_bytes()); + } + } + TRIM_IN_FLIGHT.store(false, Ordering::SeqCst); + }); +} + +/// (files, bytes) held by the shared cache, for the Settings stats line. +pub(crate) fn shared_stats() -> Option<(u64, u64)> { + let guard = cache()?.lock().ok()?; + let stats = guard.stats().ok()?; + Some((stats.file_count, stats.total_bytes)) +} + +/// Delete every original in the shared cache (Settings > Clear). Blocking — +/// call from `spawn_blocking`. The memo is dropped too so no row can keep +/// serving a path that is gone. +pub(crate) fn clear_shared() -> Result { + let cache = cache().ok_or_else(|| "image cache unavailable".to_string())?; + let freed = cache + .lock() + .map_err(|_| "image cache lock poisoned".to_string())? + .clear()?; + if let Ok(mut memo) = RESOLVED.write() { + memo.clear(); + } + Ok(freed) +} + /// Trim the shared cache to `max_bytes`, LRU by `last_accessed`, in batches. /// Blocking (SQLite + unlinks) — call from `spawn_blocking`. Returns the /// bytes freed, `None` when the cache could not be opened (already logged). @@ -1342,11 +1432,24 @@ fn sweep_orphan_scaled(dir: &Path) -> (usize, u64) { /// "Cache eviction". Blocking; call from `spawn_blocking`. pub fn housekeeping() { // 1. The SHARED cache (full-size originals): LRU trim to the budget. - if let Some(freed) = evict_shared(MAX_SHARED_BYTES) { + let budget = shared_budget_bytes(); + if let Some(freed) = evict_shared(budget) { if freed > 0 { - log::info!( - "[qbz-qt][perf] image cache evicted {freed} B (budget {MAX_SHARED_BYTES} B)" - ); + log::info!("[qbz-qt][perf] image cache evicted {freed} B (budget {budget} B)"); + } + } + // 1b. Files the database does not know (a crash mid-store, a lost db): + // never evicted by the LRU, so they are swept here — anything under + // an hour old is left alone in case its store is still in flight. + if let Some(cache) = cache() { + if let Ok(guard) = cache.lock() { + match guard.sweep_orphans(std::time::Duration::from_secs(3_600)) { + Ok((files, bytes)) if files > 0 => { + log::info!("[qbz-qt][perf] image cache swept {files} orphan files ({bytes} B)"); + } + Ok(_) => {} + Err(e) => log::warn!("[qbz-qt] image cache orphan sweep failed: {e}"), + } } } // 2. This module's OWN derivative directory: orphan sweep, then byte cap. diff --git a/crates/qbz-qt/src/foryou_qt.rs b/crates/qbz-qt/src/foryou_qt.rs index 202ebb11d..f8f29f697 100644 --- a/crates/qbz-qt/src/foryou_qt.rs +++ b/crates/qbz-qt/src/foryou_qt.rs @@ -1048,6 +1048,7 @@ fn to_row(track: &Track) -> TrackRow { let bit_depth = track.maximum_bit_depth; let sample_rate = track.maximum_sampling_rate; TrackRow { + featured: Vec::new(), id: track.id.to_string(), title, artist: track diff --git a/crates/qbz-qt/src/hotkeys_bridge.rs b/crates/qbz-qt/src/hotkeys_bridge.rs index 3306c0723..1bf80f991 100644 --- a/crates/qbz-qt/src/hotkeys_bridge.rs +++ b/crates/qbz-qt/src/hotkeys_bridge.rs @@ -245,16 +245,36 @@ fn select_all_active() -> bool { true } -/// §1.3 seek math, verbatim from keybindings.rs:572-581: -/// `clamp(npElapsedSecs ± d, 0, npDurationSecs) / npDurationSecs`, same 1 Hz -/// base (the now_playing model is fed by the poll pump — immersive D14). -pub(crate) fn seek_relative(delta: i32) { - let (pos, duration) = crate::now_playing::position(); +/// §1.3 seek math (`clamp(npElapsedSecs ± d, 0, npDurationSecs) / +/// npDurationSecs`) plus the clamp every seekbar applies on click/drag and the +/// keyboard path never had: not past the buffered edge of a stream. +pub(crate) fn relative_seek_fraction( + pos: i32, + duration: i32, + delta: i32, + seekable_max: f32, +) -> Option { if duration <= 0 { - return; + return None; } let target = (pos + delta).clamp(0, duration); - crate::transport_seek(target as f32 / duration as f32); + let frac = target as f32 / duration as f32; + Some(if seekable_max > 0.0 { + frac.min(seekable_max) + } else { + frac + }) +} + +/// Same 1 Hz base as the seekbars (the now_playing model is fed by the poll +/// pump — immersive D14). Shared by the hotkeys and the ±10 s buttons. +pub(crate) fn seek_relative(delta: i32) { + let (pos, duration) = crate::now_playing::position(); + if let Some(frac) = + relative_seek_fraction(pos, duration, delta, crate::now_playing::seekable_max()) + { + crate::transport_seek(frac); + } } /// Keyboard volume step — the same 0.05 the player bars' +/- steppers use. @@ -572,6 +592,19 @@ impl qbz_hotkeys::QbzHotkeys { mod tests { use super::*; + #[test] + fn relative_seek_clamps_to_the_track_and_to_the_buffered_edge() { + use super::relative_seek_fraction as f; + assert_eq!(f(10, 100, 10, 1.0), Some(0.2)); + assert_eq!(f(5, 100, -10, 1.0), Some(0.0)); + assert_eq!(f(95, 100, 10, 1.0), Some(1.0)); + // A stream with only half the track buffered: never past the edge. + assert_eq!(f(45, 100, 10, 0.5), Some(0.5)); + // No seek lock published yet (0.0) means "no limit". + assert_eq!(f(95, 100, 10, 0.0), Some(1.0)); + assert_eq!(f(10, 0, 10, 1.0), None); + } + #[test] fn groups_default_is_full_shape() { // trap 15: the construction-seeded default parses and carries all diff --git a/crates/qbz-qt/src/icon_tint_qt.rs b/crates/qbz-qt/src/icon_tint_qt.rs index 33e8c90bb..6afc8f9d5 100644 --- a/crates/qbz-qt/src/icon_tint_qt.rs +++ b/crates/qbz-qt/src/icon_tint_qt.rs @@ -183,6 +183,7 @@ const MASTERS: &[(&str, &str)] = &[ ("cloud-upload", include_str!("../qml/assets/icons/primary/cloud-upload.svg")), ("compass", include_str!("../qml/assets/icons/primary/compass.svg")), ("copy", include_str!("../qml/assets/icons/primary/copy.svg")), + ("database", include_str!("../qml/assets/icons/primary/database.svg")), ("disc-3", include_str!("../qml/assets/icons/primary/disc-3.svg")), ("disc", include_str!("../qml/assets/icons/primary/disc.svg")), ("disc-folder", include_str!("../qml/assets/icons/primary/disc-folder.svg")), @@ -252,6 +253,7 @@ const MASTERS: &[(&str, &str)] = &[ ("music-note-slider", include_str!("../qml/assets/icons/primary/music-note-slider.svg")), ("music", include_str!("../qml/assets/icons/primary/music.svg")), ("network", include_str!("../qml/assets/icons/primary/network.svg")), + ("paintbrush-vertical", include_str!("../qml/assets/icons/primary/paintbrush-vertical.svg")), ("panel-left", include_str!("../qml/assets/icons/primary/panel-left.svg")), ("panel-right-close", include_str!("../qml/assets/icons/primary/panel-right-close.svg")), ("panel-right-open", include_str!("../qml/assets/icons/primary/panel-right-open.svg")), @@ -280,7 +282,9 @@ const MASTERS: &[(&str, &str)] = &[ ("shopping-bag", include_str!("../qml/assets/icons/primary/shopping-bag.svg")), ("shuffle", include_str!("../qml/assets/icons/primary/shuffle.svg")), ("skip-back", include_str!("../qml/assets/icons/primary/skip-back.svg")), + ("skip-back-10", include_str!("../qml/assets/icons/primary/skip-back-10.svg")), ("skip-forward", include_str!("../qml/assets/icons/primary/skip-forward.svg")), + ("skip-forward-10", include_str!("../qml/assets/icons/primary/skip-forward-10.svg")), ("sliders-horizontal", include_str!("../qml/assets/icons/primary/sliders-horizontal.svg")), ("smartphone", include_str!("../qml/assets/icons/primary/smartphone.svg")), ("speaker", include_str!("../qml/assets/icons/primary/speaker.svg")), @@ -306,6 +310,7 @@ const MASTERS: &[(&str, &str)] = &[ ("trash-list", include_str!("../qml/assets/icons/primary/trash-list.svg")), ("triangle-alert", include_str!("../qml/assets/icons/primary/triangle-alert.svg")), ("turntable", include_str!("../qml/assets/icons/primary/turntable.svg")), + ("unplug", include_str!("../qml/assets/icons/primary/unplug.svg")), ("user-plus", include_str!("../qml/assets/icons/primary/user-plus.svg")), ("user", include_str!("../qml/assets/icons/primary/user.svg")), ("volume-2", include_str!("../qml/assets/icons/primary/volume-2.svg")), diff --git a/crates/qbz-qt/src/label_qt.rs b/crates/qbz-qt/src/label_qt.rs index cf2d0f8cf..9bf345f5f 100644 --- a/crates/qbz-qt/src/label_qt.rs +++ b/crates/qbz-qt/src/label_qt.rs @@ -1358,6 +1358,7 @@ fn parse_top_track(index: usize, raw: &Value) -> TrackRow { raw.get("release_date_stream").and_then(|v| v.as_str()), ); TrackRow { + featured: Vec::new(), is_favorite: id .parse::() .map(crate::fav_cache_qt::contains_track) diff --git a/crates/qbz-qt/src/local_playlist_qt.rs b/crates/qbz-qt/src/local_playlist_qt.rs index f97b20259..15f21e699 100644 --- a/crates/qbz-qt/src/local_playlist_qt.rs +++ b/crates/qbz-qt/src/local_playlist_qt.rs @@ -806,6 +806,7 @@ pub(crate) fn row_to_display(item: &RowItem) -> (PlaylistTrackRow, Option { let art = artwork_path.clone().unwrap_or_default(); let row = PlaylistTrackRow { + featured: Vec::new(), id: track_id.to_string(), playlist_track_id: *track_id, title: title.clone(), @@ -880,6 +881,7 @@ pub(crate) fn row_to_display(item: &RowItem) -> (PlaylistTrackRow, Option (PlaylistTrackRow, Option (PlaylistTrackRow, Option ( PlaylistTrackRow { + featured: Vec::new(), id: format!("{kind}:{reference}"), title: qbz_i18n::t("Unavailable track"), source: (*kind).to_string(), diff --git a/crates/qbz-qt/src/main.rs b/crates/qbz-qt/src/main.rs index d631b9e97..ebbc99e9c 100644 --- a/crates/qbz-qt/src/main.rs +++ b/crates/qbz-qt/src/main.rs @@ -139,6 +139,7 @@ mod kiosk_nav_qt; mod tray_bridge; // The kiosk profile itself (the same contract, §8): env/pref resolution, the // live Kiosk <-> Desktop toggle, and the boot decisions that follow from it. +mod ab_loop_qt; mod artwork_qt; mod atmosphere_qt; mod kiosk_profile_qt; @@ -2578,6 +2579,19 @@ pub(crate) fn transport_seek(frac: f32) { spawn(async move { playback_qt::seek_frac(&runtime, frac).await }); } +pub(crate) fn transport_seek_by(delta_secs: i32) { + hotkeys_bridge::seek_relative(delta_secs); +} + +pub(crate) fn ab_loop_mark() { + let runtime = app(); + spawn(async move { ab_loop_qt::mark(runtime).await }); +} + +pub(crate) fn ab_loop_clear() { + ab_loop_qt::clear(); +} + pub(crate) fn transport_set_volume(volume: f32) { // Local model first (instant UI), then the engine. now_playing::set_volume(volume); diff --git a/crates/qbz-qt/src/now_playing.rs b/crates/qbz-qt/src/now_playing.rs index 703d87e43..174fc7cd1 100644 --- a/crates/qbz-qt/src/now_playing.rs +++ b/crates/qbz-qt/src/now_playing.rs @@ -198,6 +198,7 @@ pub fn publish_current() { publish(&snapshot); // The layers-glyph preference (see `publish_show_context_icon`). publish_show_context_icon(); + publish_show_skip_ten(); // Seed the two output LEDs + the volume-lock flag at shell entry too, so // the stamp is correct before the first track ever plays (the bridge // defaults are the unlit SYST/DEFAULT pair). @@ -260,6 +261,13 @@ pub fn publish_show_context_icon() { crate::player_bridge::ui(move |mut b| b.as_mut().set_show_context_icon(show)); } +/// The ±10 s buttons preference (ui_prefs `show_skip_ten`), re-published on +/// shell entry and from the Settings toggle. +pub fn publish_show_skip_ten() { + let show = crate::settings_qt::pref_bool("show_skip_ten", false); + crate::player_bridge::ui(move |mut b| b.as_mut().set_show_skip_ten(show)); +} + // --- Pure-UI toggles (mutate + republish) -------------------------------- pub fn set_volume(volume: f32) { @@ -296,6 +304,11 @@ pub(crate) fn position() -> (i32, i32) { with_model(|m| (m.elapsed_secs, m.duration_secs)).0 } +/// The published seek lock (`np_seekable_max`, 0.0 = not yet published). +pub(crate) fn seekable_max() -> f32 { + with_model(|m| m.seekable_max).0 +} + /// (artist_id, title) of the current track — the read the immersive /// Suggestions loader makes off the Slint `NowPlayingState` /// (`main.rs:16699-16702`: the panel only has the track id, the seed artist diff --git a/crates/qbz-qt/src/playback_qt.rs b/crates/qbz-qt/src/playback_qt.rs index 74496b5ef..6369221c4 100644 --- a/crates/qbz-qt/src/playback_qt.rs +++ b/crates/qbz-qt/src/playback_qt.rs @@ -3603,6 +3603,19 @@ fn auto_skip_unavailable<'a>( }) } +/// The LOCAL tail of `seek_frac` (no cast / QConnect routing): the A-B loop's +/// jump, which is only ever armed for local playback. +pub(crate) async fn seek_local_secs(runtime: &Arc>, target: u64) { + let Some(_transport_action) = begin_transport_action() else { + return; + }; + if let Err(e) = runtime.core().seek(target) { + log::warn!("[qbz-qt] seek failed: {e}"); + return; + } + crate::media_controls_qt::push_seeked(target); +} + pub async fn seek_frac(runtime: &Arc>, frac: f32) { let Some(_transport_action) = begin_transport_action() else { return; @@ -3677,6 +3690,7 @@ pub async fn seek_frac(runtime: &Arc>, frac: f32) { return; } let target = (frac.clamp(0.0, 1.0) * event.duration as f32) as u64; + crate::ab_loop_qt::on_manual_seek(target); if let Err(e) = runtime.core().seek(target) { log::warn!("[qbz-qt] seek failed: {e}"); return; @@ -4697,6 +4711,7 @@ pub fn start_poll_loop(runtime: Arc>) { qbz_app::session_persist::capture_and_save(&runtime).await; } last_track_id = track_id; + crate::ab_loop_qt::on_track_changed(track_id); // The engine may have reached this track through a GAPLESS // hand-off, in which case the arming guard still names the // track that just ended. Clear it so the NEW current track can diff --git a/crates/qbz-qt/src/player_bridge.rs b/crates/qbz-qt/src/player_bridge.rs index 78c668755..d77fa7b48 100644 --- a/crates/qbz-qt/src/player_bridge.rs +++ b/crates/qbz-qt/src/player_bridge.rs @@ -157,6 +157,15 @@ pub mod qbz_player { // "Show track playing context" pref (Playback settings) — feeds the // SongCard layers icon. #[qproperty(bool, show_context_icon)] + // "Show 10-second skip buttons" (Appearance > Player & Visuals) — + // ui_prefs `show_skip_ten`, mirrored here so TransportControls reads + // one property on every bar. + #[qproperty(bool, show_skip_ten)] + // A-B loop (ab_loop_qt): 0 none / 1 A armed / 2 looping, plus the two + // marks in whole seconds for the seekbar. + #[qproperty(i32, ab_state)] + #[qproperty(i32, ab_start_secs)] + #[qproperty(i32, ab_end_secs)] type QbzPlayer = super::QbzPlayerRust; /// Registers this object's Qt-thread hop (Main.qml boots EVERY @@ -181,6 +190,15 @@ pub mod qbz_player { fn previous(self: Pin<&mut QbzPlayer>); #[qinvokable] fn seek(self: Pin<&mut QbzPlayer>, frac: f32); + /// Relative seek in whole seconds (the ±10 s buttons); clamps to the + /// track and to the buffered edge like the seekbars do. + #[qinvokable] + fn seek_by(self: Pin<&mut QbzPlayer>, delta_secs: i32); + /// A-B loop verb: arm A, then B, then clear (see ab_loop_qt). + #[qinvokable] + fn ab_mark(self: Pin<&mut QbzPlayer>); + #[qinvokable] + fn ab_clear(self: Pin<&mut QbzPlayer>); #[qinvokable] fn set_volume(self: Pin<&mut QbzPlayer>, volume: f32); /// Persist the SETTLED volume (drag-end only — see QbzSlider.released). @@ -343,6 +361,10 @@ pub struct QbzPlayerRust { np_context_kind: QString, np_context_id: QString, show_context_icon: bool, + show_skip_ten: bool, + ab_state: i32, + ab_start_secs: i32, + ab_end_secs: i32, } impl Default for QbzPlayerRust { @@ -408,6 +430,10 @@ impl Default for QbzPlayerRust { // open (then it reads false). `now_playing::publish_show_context_icon` // re-publishes it on shell entry and on the Settings toggle. show_context_icon: crate::settings_qt::show_context_icon(), + show_skip_ten: crate::settings_qt::pref_bool("show_skip_ten", false), + ab_state: 0, + ab_start_secs: 0, + ab_end_secs: 0, } } } @@ -464,6 +490,18 @@ impl qbz_player::QbzPlayer { crate::transport_seek(frac); } + pub fn seek_by(self: Pin<&mut Self>, delta_secs: i32) { + crate::transport_seek_by(delta_secs); + } + + pub fn ab_mark(self: Pin<&mut Self>) { + crate::ab_loop_mark(); + } + + pub fn ab_clear(self: Pin<&mut Self>) { + crate::ab_loop_clear(); + } + pub fn persist_volume(self: Pin<&mut Self>, fraction: f32) { crate::settings_qt::save_pref("volume", serde_json::json!(fraction.clamp(0.0, 1.0))); } diff --git a/crates/qbz-qt/src/playlist_qt.rs b/crates/qbz-qt/src/playlist_qt.rs index 65d68139a..b071a8627 100644 --- a/crates/qbz-qt/src/playlist_qt.rs +++ b/crates/qbz-qt/src/playlist_qt.rs @@ -59,6 +59,9 @@ use serde::Serialize; #[derive(Clone, Default, Serialize)] pub struct PlaylistTrackRow { + /// Featured performers (see `album_qt::TrackRow::featured`); empty when none. + #[serde(rename = "featured")] + pub featured: Vec, pub id: String, /// The playlist membership row id (== catalog track id for Qobuz /// playlists — what remove_tracks_from_playlist takes). @@ -862,6 +865,7 @@ pub(crate) fn map_track(track: &Track) -> PlaylistTrackRow { .map(|p| (p.name, p.id.to_string())) .unwrap_or_default(); PlaylistTrackRow { + featured: crate::album_qt::featured_list(track.performers.as_deref(), &artist, &track.title, &[]), // Heart state at build time, from the favourite-id cache — the same // O(1) read `album_qt` / `artist_qt` / `label_qt` rows use. It was // never stamped here, so `TrackRow.qml` saw `undefined` on every diff --git a/crates/qbz-qt/src/search_qt.rs b/crates/qbz-qt/src/search_qt.rs index e97b27738..b3197ac55 100644 --- a/crates/qbz-qt/src/search_qt.rs +++ b/crates/qbz-qt/src/search_qt.rs @@ -194,6 +194,9 @@ pub struct CardRow { #[derive(Clone, Default, Serialize)] pub struct TrackRow { + /// Featured performers (see `album_qt::TrackRow::featured`); empty when none. + #[serde(rename = "featured")] + pub featured: Vec, pub id: String, pub title: String, pub artist: String, @@ -404,6 +407,7 @@ fn map_track(track: &Track) -> TrackRow { .map(|p| (p.name, p.id.to_string())) .unwrap_or_default(); TrackRow { + featured: crate::album_qt::featured_list(track.performers.as_deref(), &artist, &track.title, &[]), // Same story as `map_album`: the field was declared (line 186) and // never stamped, so every search track row drew the empty heart and // the first click sent `favorite/delete` on a track the user had diff --git a/crates/qbz-qt/src/settings_qt.rs b/crates/qbz-qt/src/settings_qt.rs index 393268112..eae98ec73 100644 --- a/crates/qbz-qt/src/settings_qt.rs +++ b/crates/qbz-qt/src/settings_qt.rs @@ -2196,6 +2196,8 @@ pub struct SettingsDoc { pub library_track_artwork: bool, #[serde(rename = "localLibraryTrackArtwork")] pub local_library_track_artwork: bool, + #[serde(rename = "showFeaturedArtists")] + pub show_featured_artists: bool, #[serde(rename = "playIndicatorAnimation")] pub play_indicator_animation: bool, #[serde(rename = "seekbarWaveform")] @@ -2218,6 +2220,8 @@ pub struct SettingsDoc { pub wc_position_index: i32, #[serde(rename = "showWindowControls")] pub show_window_controls: bool, + #[serde(rename = "showSkipTen")] + pub show_skip_ten: bool, #[serde(rename = "showVolumeSteppers")] pub show_volume_steppers: bool, #[serde(rename = "miniDefaultViews")] @@ -2739,6 +2743,7 @@ pub async fn publish_snapshot() { library_track_artwork: pref_bool("library_track_artwork", false), local_library_track_artwork: pref_bool("local_library_track_artwork", false), play_indicator_animation: pref_bool("play_indicator_animation", false), + show_featured_artists: pref_bool("show_featured_artists", true), seekbar_waveform: seekbar_waveform(), invert_swipe_navigation: pref_bool("invert_swipe_navigation", false), in_app_toasts: pref_bool("in_app_toasts", true), @@ -2750,6 +2755,7 @@ pub async fn publish_snapshot() { wc_position_index: index_of(WC_POSITION_VALUES, &pref_str("wc_position", "right"), 1), show_window_controls: pref_bool("show_window_controls", true), show_volume_steppers: pref_bool("show_volume_steppers", false), + show_skip_ten: pref_bool("show_skip_ten", false), mini_default_views: MINI_VIEW_LABELS.iter().map(|l| qbz_i18n::t(l)).collect(), mini_default_view_index: index_of( MINI_VIEW_VALUES, @@ -3633,6 +3639,10 @@ pub async fn settings_bool(runtime: &Arc>, key: &str, crate::local_album_actions::publish_track_artwork(); Ok(Apply::None) } + "show-featured-artists" => { + save_pref("show_featured_artists", serde_json::json!(value)); + Ok(Apply::None) + } "play-indicator-animation" => { save_pref("play_indicator_animation", serde_json::json!(value)); Ok(Apply::None) @@ -3687,6 +3697,13 @@ pub async fn settings_bool(runtime: &Arc>, key: &str, crate::shell_bridge::ui(move |mut b| b.as_mut().set_show_window_controls(value)); Ok(Apply::None) } + "show-skip-ten" => { + save_pref("show_skip_ten", serde_json::json!(value)); + // Live mirror on the domain bridge (the §5.6 pattern): the bar + // reads QbzPlayer.showSkipTen, not the settings document. + crate::player_bridge::ui(move |mut b| b.as_mut().set_show_skip_ten(value)); + Ok(Apply::None) + } "show-volume-steppers" => { save_pref("show_volume_steppers", serde_json::json!(value)); Ok(Apply::None) @@ -4230,6 +4247,14 @@ pub async fn settings_select(runtime: &Arc>, key: &st }; save_pref("startup_page", serde_json::json!(v)); } + "image-cache-max" => { + let Some(mb) = offline::IMAGE_CACHE_MB.get(index) else { + return; + }; + save_pref("image_cache_max_mb", serde_json::json!(mb)); + // A smaller budget applies right away, not at the next boot. + crate::artwork_qt::trim_shared_now(); + } "genre-filters-position" => { let Some(v) = LOCAL_GENRE_FILTER_POSITION_VALUES.get(index) else { return; @@ -4516,6 +4541,7 @@ pub async fn settings_string(key: &str, value: String) { "plex-clear-cache" => library::plex_clear_cache().await, // --- Offline -------------------------------------------------------- "lyrics-cache-clear" => offline::clear_lyrics_cache().await, + "image-cache-clear" => offline::clear_image_cache().await, // Offline > "Check now": nudge the connectivity actor. The status it // publishes flows back through offline_fwd's forwarder, so there is // nothing to await and nothing to republish here. diff --git a/crates/qbz-qt/src/settings_qt/offline.rs b/crates/qbz-qt/src/settings_qt/offline.rs index 308ef1677..6892391c0 100644 --- a/crates/qbz-qt/src/settings_qt/offline.rs +++ b/crates/qbz-qt/src/settings_qt/offline.rs @@ -30,8 +30,23 @@ pub struct Snapshot { pub lyrics_entries: i64, #[serde(rename = "lyricsSize")] pub lyrics_size: String, + /// Shared artwork cache (`~/.cache/qbz/images`): stats line + budget. + #[serde(rename = "imageCacheLoaded")] + pub image_cache_loaded: bool, + #[serde(rename = "imageCacheFiles")] + pub image_cache_files: i64, + #[serde(rename = "imageCacheSize")] + pub image_cache_size: String, + #[serde(rename = "imageCacheSizes")] + pub image_cache_sizes: Vec, + #[serde(rename = "imageCacheSizeIndex")] + pub image_cache_size_index: i32, } +/// Budget choices for the artwork cache, in MB (index 1 = the default). +pub(crate) const IMAGE_CACHE_MB: &[u64] = &[100, 200, 500, 1000]; +const IMAGE_CACHE_LABELS: &[&str] = &["100 MB", "200 MB", "500 MB", "1 GB"]; + fn lyrics_db_path() -> Option { let uid = qbz_app::user_data::UserDataPaths::load_last_user_id()?; Some( @@ -81,6 +96,17 @@ pub fn snapshot() -> Snapshot { _ => (false, 0, String::new()), }; + let (image_cache_loaded, image_cache_files, image_cache_size) = + match crate::artwork_qt::shared_stats() { + Some((files, bytes)) => (true, files as i64, human_size(bytes)), + None => (false, 0, String::new()), + }; + let budget_mb = crate::artwork_qt::shared_budget_bytes() / (1024 * 1024); + let image_cache_size_index = IMAGE_CACHE_MB + .iter() + .position(|mb| *mb == budget_mb) + .unwrap_or(1) as i32; + Snapshot { mode_enabled: settings.manual_offline_mode, allow_immediate_scrobbling: settings.allow_immediate_scrobbling, @@ -88,9 +114,23 @@ pub fn snapshot() -> Snapshot { lyrics_loaded, lyrics_entries, lyrics_size, + image_cache_loaded, + image_cache_files, + image_cache_size, + image_cache_sizes: IMAGE_CACHE_LABELS.iter().map(|l| l.to_string()).collect(), + image_cache_size_index, } } +/// Settings > Offline > "Clear" on the artwork cache. +pub async fn clear_image_cache() { + let _ = tokio::task::spawn_blocking(|| match crate::artwork_qt::clear_shared() { + Ok(freed) => log::info!("[qbz-qt] image cache cleared ({freed} B)"), + Err(e) => log::error!("[qbz-qt] image cache clear failed: {e}"), + }) + .await; +} + pub fn set_allow_immediate_scrobbling(value: bool) -> Result<(), String> { let result = crate::offline_fwd::engine().set_allow_immediate_scrobbling(value); if result.is_ok() {