diff --git a/CLAUDE.md b/CLAUDE.md index 3ae9615..8df6cb6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,6 +92,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~ | `TUNAL_SETTINGS=<0-4> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 | | `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- --screenshot --size 1200x760` (`XDG_CONFIG_HOME=`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 | | `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | folder appearance dialog for `` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- ` sets `Icon` in `/.directory` and prints the old values | S015 | +| `TUNAL_TAGS=editor\|lookup\|mapping\|apply:: TUNAL_TAGS_SYNC=1 TUNAL_MUSICBRAINZ= XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | tag editor / lookup / mapping over a folder; `apply` also writes the tags (scratch copies only); mock = a local server for both services | S021 | Don't assume a tool exists: check first. When your plan creates a tool, add its row here. diff --git a/Cargo.lock b/Cargo.lock index 862c899..73caba9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5537,6 +5537,7 @@ checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" name = "tunal" version = "0.1.0" dependencies = [ + "image", "jiff", "png", "serde", @@ -5547,6 +5548,7 @@ dependencies = [ "tunal-devices", "tunal-dirmeta", "tunal-elevate", + "tunal-tags", "tunal-theme", "tunal-thumbs", "zbus", diff --git a/Plans/07 Tag editor/S021-tag-editor-ui.md b/Plans/07 Tag editor/S021-tag-editor-ui.md index 1dc10d6..4d72f78 100644 --- a/Plans/07 Tag editor/S021-tag-editor-ui.md +++ b/Plans/07 Tag editor/S021-tag-editor-ui.md @@ -10,11 +10,11 @@ Edit tags of one or many audio files, look up metadata and covers, and embed the crates/tunal-tags API; crates/tunal/src/{actions.rs,menus.rs}; crates/tunal/ui/components/{dialog,text-field,list-row}.slint. ## Steps -- [ ] 'Edit tags' action on audio files (single and multi) added to the registry and default menus. -- [ ] Editor: fields with 'Keep' placeholder for mixed values, cover area (current, replace from file, remove, drop an image), save off-thread with progress. -- [ ] Lookup: search prefilled from tags → candidate releases (title, artist, date, country, track count, cover) → file ↔ track mapping (auto, editable) → preview of changes → apply and embed cover. -- [ ] Errors (offline, rate limited, not found) shown plainly. -- [ ] PROGRESS entry, INDEX line, commit `S021: …` +- [x] 'Edit tags' action on audio files (single and multi) added to the registry and default menus. +- [x] Editor: fields with 'Keep' placeholder for mixed values, cover area (current, replace from file, remove, drop an image), save off-thread with progress. +- [x] Lookup: search prefilled from tags → candidate releases (title, artist, date, country, track count, cover) → file ↔ track mapping (auto, editable) → preview of changes → apply and embed cover. +- [x] Errors (offline, rate limited, not found) shown plainly. +- [x] PROGRESS entry, INDEX line, commit `S021: …` ## End criteria - `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass. diff --git a/Plans/INDEX.md b/Plans/INDEX.md index a02e386..6338194 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -46,7 +46,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v - [x] [S019 — Tag model with lofty](07%20Tag%20editor/S019-tag-model.md) · Sonnet medium - [x] [S020 — MusicBrainz and Cover Art Archive client](07%20Tag%20editor/S020-musicbrainz-client.md) · Sonnet high -- [ ] [S021 — Tag editor UI](07%20Tag%20editor/S021-tag-editor-ui.md) · Opus medium +- [x] [S021 — Tag editor UI](07%20Tag%20editor/S021-tag-editor-ui.md) · Opus medium ## 08 Audio player diff --git a/crates/tunal-tags/src/io.rs b/crates/tunal-tags/src/io.rs index 13218e7..4b9c756 100644 --- a/crates/tunal-tags/src/io.rs +++ b/crates/tunal-tags/src/io.rs @@ -114,6 +114,12 @@ pub fn read(path: &Path) -> Result { .unwrap_or_default()) } +/// The playing time of a file in milliseconds, when lofty can tell. +pub fn duration_ms(path: &Path) -> Option { + let tagged = open(path).ok()?; + u32::try_from(tagged.properties().duration().as_millis()).ok() +} + /// Reads many files and merges them. Files that fail are returned with their error and left out. pub fn read_set(paths: &[PathBuf]) -> (TagSet, Vec<(PathBuf, Error)>) { let mut tracks = Vec::new(); diff --git a/crates/tunal-tags/src/lib.rs b/crates/tunal-tags/src/lib.rs index b564230..f911fad 100644 --- a/crates/tunal-tags/src/lib.rs +++ b/crates/tunal-tags/src/lib.rs @@ -8,7 +8,7 @@ mod mb; mod model; pub use http::{Client, NetError}; -pub use io::{Error, read, read_set, write, write_many}; +pub use io::{Error, duration_ms, read, read_set, write, write_many}; pub use matching::{FileInfo, match_tracks}; pub use mb::{RecordingHit, Release, ReleaseHit, Track}; pub use model::{Cover, CoverEdit, Edit, Merged, TagEdit, TagSet, TrackTags}; diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml index e40bd15..89866a5 100644 --- a/crates/tunal/Cargo.toml +++ b/crates/tunal/Cargo.toml @@ -14,6 +14,8 @@ tunal-elevate = { path = "../tunal-elevate" } tunal-devices = { path = "../tunal-devices" } tunal-dirmeta = { path = "../tunal-dirmeta" } tunal-thumbs = { path = "../tunal-thumbs" } +tunal-tags = { path = "../tunal-tags" } +image.workspace = true jiff.workspace = true serde.workspace = true zbus.workspace = true diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs index d365f9f..7c8b4cb 100644 --- a/crates/tunal/src/actions.rs +++ b/crates/tunal/src/actions.rs @@ -17,6 +17,7 @@ use crate::open::Opener; use crate::properties::Properties; use crate::shell::Shell; use crate::shell::pane::Pane; +use crate::tags_bridge::{self, Tags}; use crate::{MainWindow, MenuEntry, MenuItem}; /// Every action, by stable id (the context menu editor refers to these). @@ -37,6 +38,7 @@ pub enum Action { OpenWith, Properties, Appearance, + EditTags, } enum Shortcut { @@ -45,7 +47,7 @@ enum Shortcut { } impl Action { - pub const ALL: [Action; 15] = [ + pub const ALL: [Action; 16] = [ Self::Cut, Self::Copy, Self::Paste, @@ -61,6 +63,7 @@ impl Action { Self::OpenWith, Self::Properties, Self::Appearance, + Self::EditTags, ]; pub fn id(self) -> &'static str { @@ -80,6 +83,7 @@ impl Action { Self::OpenWith => "open-with", Self::Properties => "properties", Self::Appearance => "appearance", + Self::EditTags => "edit-tags", } } @@ -104,6 +108,7 @@ impl Action { Self::OpenWith => "Open with…", Self::Properties => "Properties", Self::Appearance => "Folder appearance…", + Self::EditTags => "Edit tags…", } } @@ -125,6 +130,7 @@ impl Action { Self::OpenWith => "\u{e5c3}", Self::Properties => "\u{e88e}", Self::Appearance => "\u{e40a}", + Self::EditTags => "\u{e892}", } } @@ -145,7 +151,8 @@ impl Action { | Self::Open | Self::OpenWith | Self::Properties - | Self::Appearance => { + | Self::Appearance + | Self::EditTags => { return None; } }) @@ -196,6 +203,7 @@ impl Action { Self::Open | Self::OpenWith => files && ctx.selected > 0, Self::Properties => true, Self::Appearance => files && ctx.selected <= 1, + Self::EditTags => files && ctx.audio, } } } @@ -209,6 +217,8 @@ pub struct Context { pub can_trash: bool, /// The clipboard holds something to paste. pub paste: bool, + /// Every selected entry is a local audio file. + pub audio: bool, } #[derive(Default)] @@ -231,6 +241,7 @@ pub struct Actions { opener: Rc, properties: Rc, appearance: Rc, + tags: Rc, } impl Actions { @@ -239,6 +250,7 @@ impl Actions { let opener = Opener::attach(ui, locations.clone(), bridge.clone()); let properties = Properties::attach(ui, locations.clone()); let appearance = Appearance::attach(ui, bridge.elevation()); + let tags = Tags::attach(ui, bridge.clone()); let actions = Rc::new_cyclic(|me| Self { me: me.clone(), ui: ui.as_weak(), @@ -251,6 +263,7 @@ impl Actions { opener, properties, appearance, + tags, }); let me = actions.me.clone(); let shell_weak = Rc::downgrade(shell); @@ -265,10 +278,23 @@ impl Actions { me.appearance_saved(dir, remembered); } }); + let shell_weak = Rc::downgrade(shell); + actions.tags.on_written(move || { + if let Some(shell) = shell_weak.upgrade() { + for pane in shell.panes() { + pane.model.refresh(); + } + } + }); actions.bind(ui); actions } + /// Screenshots: opens the tag editor or lookup (see `TUNAL_TAGS` in main.rs). + pub fn debug_tags(&self, spec: &str) { + self.tags.debug_open(spec); + } + /// Runs a file job (drag and drop). pub fn submit(&self, kind: JobKind) { self.bridge.submit(kind); @@ -294,8 +320,12 @@ impl Actions { .and_then(|d| self.locations.resolve(&d).ok()) .map(|l| l.capabilities()) .unwrap_or_default(); + let selected = pane.model.selected_uris(); Context { - selected: pane.model.selected_uris().len(), + audio: !selected.is_empty() + && !pane.model.selection_is_dir() + && selected.iter().all(tags_bridge::is_audio), + selected: selected.len(), in_trash: pane.dir().is_some_and(|d| d.scheme() == tunal_core::TRASH), writable: caps.write, can_trash: caps.trash, @@ -508,6 +538,13 @@ impl Actions { } return; } + Action::EditTags => { + let files: Vec<_> = uris.iter().filter_map(|u| u.to_path()).collect(); + if !files.is_empty() { + self.tags.edit(files); + } + return; + } Action::Settings => { if let Some(ui) = self.ui.upgrade() { ui.invoke_show_settings(0); diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs index 2074630..f288512 100644 --- a/crates/tunal/src/main.rs +++ b/crates/tunal/src/main.rs @@ -13,6 +13,7 @@ mod screenshot; mod settings; mod shapes; mod shell; +mod tags_bridge; mod theme_bridge; mod thumbs_bridge; @@ -99,6 +100,11 @@ fn window( if std::env::var_os("TUNAL_APPEARANCE").is_some() { shell.run_action(actions::Action::Appearance); } + // `TUNAL_TAGS=editor|lookup|mapping::…` opens the tag editor or the lookup + // (screenshots; `TUNAL_TAGS_SYNC=1` runs its work in place, `TUNAL_MUSICBRAINZ=` is a mock). + if let Ok(spec) = std::env::var("TUNAL_TAGS") { + shell.debug_tags(&spec); + } Ok((ui, shell)) } diff --git a/crates/tunal/src/menus.rs b/crates/tunal/src/menus.rs index e419c1f..f9501bc 100644 --- a/crates/tunal/src/menus.rs +++ b/crates/tunal/src/menus.rs @@ -45,6 +45,7 @@ impl Context { Self::File => &[ "open", "open-with", + "edit-tags", "-", "cut", "copy", @@ -76,6 +77,7 @@ impl Context { "properties", ], Self::Multiple => &[ + "edit-tags", "cut", "copy", "-", diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs index d843c1e..5208f74 100644 --- a/crates/tunal/src/shell/mod.rs +++ b/crates/tunal/src/shell/mod.rs @@ -451,6 +451,12 @@ impl Shell { /// Tab bar selection, toolbar, breadcrumb, sort menu, sidebar and status bar. /// Runs an action as if chosen from a menu (screenshot hooks). + pub(crate) fn debug_tags(&self, spec: &str) { + if let Some(actions) = self.actions.get() { + actions.debug_tags(spec); + } + } + pub(crate) fn run_action(&self, action: crate::actions::Action) { if let Some(actions) = self.actions.get() { actions.run(action); diff --git a/crates/tunal/src/tags_bridge.rs b/crates/tunal/src/tags_bridge.rs new file mode 100644 index 0000000..6095da7 --- /dev/null +++ b/crates/tunal/src/tags_bridge.rs @@ -0,0 +1,1230 @@ +//! The tag editor and the online lookup: read the tags of the chosen audio files, show them +//! (mixed values as "Keep"), write the edits, and copy a MusicBrainz release's tags and cover +//! onto the files. Disk and network work runs off the UI thread; the dialogs' state lives in +//! thread-locals on the UI thread, so the closures that cross threads carry only plain data. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use slint::{ + ComponentHandle, Image, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, SharedString, VecModel, +}; +use tunal_core::Uri; +use tunal_tags::{ + Client, Cover, CoverEdit, Edit, FileInfo, Merged, Release, ReleaseHit, TagEdit, TagSet, + TrackTags, +}; + +use crate::dnd::parse_uri_list; +use crate::jobs_bridge::Bridge; +use crate::{MainWindow, MapRow, ReleaseRow, TagEditorData, TagField, TagLookupData}; + +/// Extensions lofty reads and writes. +const AUDIO: [&str; 14] = [ + "mp3", "flac", "ogg", "oga", "opus", "m4a", "m4b", "mp4", "aac", "wav", "wv", "ape", "mpc", + "aif", +]; + +/// Releases the search lists, and how many get a cover (each costs a request). +const MAX_RELEASES: u32 = 8; +const COVERED_RELEASES: usize = 6; +/// Covers shown in the dialogs are scaled down to this. +const SHOWN_COVER: u32 = 256; +const MAX_COVER_BYTES: u64 = 16 * 1024 * 1024; + +/// An audio file we can edit: local, with a known extension. +pub fn is_audio(uri: &Uri) -> bool { + uri.to_path().is_some_and(|p| { + p.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| AUDIO.iter().any(|a| e.eq_ignore_ascii_case(a))) + }) +} + +/// The editor's text fields, in the order the dialog lays them out. +const LABELS: [&str; 12] = [ + "Title", + "Artist", + "Album", + "Album artist", + "Genre", + "Composer", + "Date", + "Track no.", + "Track total", + "Disc no.", + "Disc total", + "Comment", +]; + +struct Editor { + files: Vec, + tracks: Vec, + set: TagSet, + /// What each field showed first, and what it shows now. + initial: Vec, + texts: Vec, + cover: CoverEdit, + /// The cover the files have now, scaled for display. + shown: Option>, +} + +struct Lookup { + files: Vec, + tracks: Vec, + artist: String, + album: String, + hits: Vec, + covers: Vec>, + selected: Option, + release: Option, + assign: Vec>, + cover: Option, + embed: bool, + /// Bumped by every search and every step: a late answer for an earlier one is dropped. + serial: Arc, +} + +thread_local! { + static EDITOR: RefCell> = const { RefCell::new(None) }; + static LOOKUP: RefCell> = const { RefCell::new(None) }; +} + +type Written = Box; + +pub struct Tags { + ui: slint::Weak, + bridge: Rc, + client: Client, + written: RefCell, +} + +/// Runs `work` on a thread and `done` on the UI thread with its result. Screenshots have no +/// event loop, so `TUNAL_TAGS_SYNC` runs both in place. +fn spawn( + ui: &slint::Weak, + work: impl FnOnce() -> T + Send + 'static, + done: impl FnOnce(&MainWindow, T) + Send + 'static, +) { + if std::env::var_os("TUNAL_TAGS_SYNC").is_some() { + if let Some(ui) = ui.upgrade() { + done(&ui, work()); + } + return; + } + let ui = ui.clone(); + std::thread::spawn(move || { + let result = work(); + let _ = ui.upgrade_in_event_loop(move |ui| done(&ui, result)); + }); +} + +/// A cover scaled for display (decoded off the UI thread: pictures can be large). +fn buffer(data: &[u8]) -> Option> { + let image = image::load_from_memory(data) + .ok()? + .thumbnail(SHOWN_COVER, SHOWN_COVER) + .to_rgba8(); + Some(SharedPixelBuffer::clone_from_slice( + image.as_raw(), + image.width(), + image.height(), + )) +} + +fn picture(buffer: Option<&SharedPixelBuffer>) -> Image { + buffer.cloned().map(Image::from_rgba8).unwrap_or_default() +} + +fn name_of(path: &Path) -> String { + path.file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn plural(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +/// The text a merged field starts with, and whether the files differ. +fn text_of(field: &Merged) -> (String, bool) { + match field { + Merged::Same(Some(v)) => (v.to_string(), false), + Merged::Same(None) => (String::new(), false), + Merged::Mixed => (String::new(), true), + } +} + +/// The field `i` of `set` (see `LABELS`). +fn field_text(set: &TagSet, i: usize) -> (String, bool) { + match i { + 0 => text_of(&set.title), + 1 => text_of(&set.artist), + 2 => text_of(&set.album), + 3 => text_of(&set.album_artist), + 4 => text_of(&set.genre), + 5 => text_of(&set.composer), + 6 => text_of(&set.date), + 7 => text_of(&set.track_no), + 8 => text_of(&set.track_total), + 9 => text_of(&set.disc_no), + 10 => text_of(&set.disc_total), + _ => text_of(&set.comment), + } +} + +/// An edit for text: nothing when it still shows what it started with, else set or clear. +fn text_edit(initial: &str, now: &str) -> Edit { + let now = now.trim(); + if now == initial { + Edit::Keep + } else if now.is_empty() { + Edit::Clear + } else { + Edit::Set(now.to_owned()) + } +} + +fn number_edit(initial: &str, now: &str) -> Result, ()> { + let now = now.trim(); + if now == initial { + Ok(Edit::Keep) + } else if now.is_empty() { + Ok(Edit::Clear) + } else { + now.parse().map(Edit::Set).map_err(|_| ()) + } +} + +/// The edit the editor's fields and cover amount to; `Err(i)` names a number that isn't one. +fn build_edit(editor: &Editor) -> Result { + let text = |i: usize| text_edit(&editor.initial[i], &editor.texts[i]); + let number = |i: usize| number_edit(&editor.initial[i], &editor.texts[i]).map_err(|()| i); + Ok(TagEdit { + title: text(0), + artist: text(1), + album: text(2), + album_artist: text(3), + genre: text(4), + composer: text(5), + date: text(6), + track_no: number(7)?, + track_total: number(8)?, + disc_no: number(9)?, + disc_total: number(10)?, + comment: text(11), + cover: editor.cover.clone(), + ..TagEdit::default() + }) +} + +fn cover_from_file(path: &Path) -> Result { + let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", name_of(path)))?; + if !meta.is_file() || meta.len() > MAX_COVER_BYTES { + return Err(format!("{} isn't a usable image file", name_of(path))); + } + let data = std::fs::read(path).map_err(|e| format!("{}: {e}", name_of(path)))?; + let mime = if data.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if data.starts_with(&[0x89, b'P', b'N', b'G']) { + "image/png" + } else { + return Err("The cover must be a JPEG or PNG image.".into()); + }; + Ok(Cover { + mime: mime.into(), + data, + }) +} + +impl Tags { + pub fn attach(ui: &MainWindow, bridge: Rc) -> Rc { + // `TUNAL_MUSICBRAINZ=` points both services at a mock (smoke runs). + let client = match std::env::var("TUNAL_MUSICBRAINZ") { + Ok(base) => Client::with_bases(&base, &base), + Err(_) => Client::new(), + }; + let me = Rc::new(Self { + ui: ui.as_weak(), + bridge, + client, + written: RefCell::new(Box::new(|| {})), + }); + me.bind(ui); + me + } + + /// Runs after tags were written to files (panes list again to show new covers). + pub fn on_written(&self, f: impl Fn() + 'static) { + *self.written.borrow_mut() = Box::new(f); + } + + fn bind(self: &Rc, ui: &MainWindow) { + macro_rules! on { + ($register:ident, $method:ident $(, $arg:ident)*) => {{ + let me = Rc::downgrade(self); + ui.$register(move |$($arg),*| { + if let Some(me) = me.upgrade() { + me.$method($($arg),*); + } + }); + }}; + } + on!(on_tag_editor_saved, save); + on!(on_tag_editor_lookup, open_lookup); + on!(on_tag_field_changed, field_changed, i, text); + on!(on_tag_cover_path, cover_path, path); + on!(on_tag_cover_dropped, cover_dropped, data); + on!(on_tag_cover_removed, cover_removed); + on!(on_tag_cover_reset, cover_reset); + on!(on_tag_artist_edited, artist_edited, text); + on!(on_tag_album_edited, album_edited, text); + on!(on_tag_search, search); + on!(on_tag_release_picked, release_picked, i); + on!(on_tag_next, next); + on!(on_tag_back, back); + on!(on_tag_lookup_cancelled, lookup_cancelled); + on!(on_tag_map_step, map_step, row, delta); + on!(on_tag_embed_toggled, embed_toggled, on); + on!(on_tag_apply, apply); + on!(on_tags_written, written_message, message); + } + + /// Tags were written: close the dialogs, say so, and let the panes list again. + fn written_message(&self, message: SharedString) { + if let Some(ui) = self.ui.upgrade() { + ui.invoke_close_tag_editor(); + ui.invoke_close_tag_lookup(); + } + self.bridge.notify(message.to_string()); + (self.written.borrow())(); + } + + // ---- editor ------------------------------------------------------------------------- + + /// Reads the files and opens the editor on them. + pub fn edit(&self, files: Vec) { + let paths = files; + spawn( + &self.ui, + move || { + let tracks: Vec<(PathBuf, Result)> = paths + .into_iter() + .map(|p| { + let tags = tunal_tags::read(&p).map_err(|e| e.to_string()); + (p, tags) + }) + .collect(); + let first_cover = tracks + .iter() + .find_map(|(_, t)| t.as_ref().ok().and_then(|t| t.cover.as_ref())) + .and_then(|c| buffer(&c.data)); + (tracks, first_cover) + }, + move |ui, (read, first_cover)| { + let mut files = Vec::new(); + let mut tracks = Vec::new(); + let mut failed = Vec::new(); + for (path, result) in read { + match result { + Ok(t) => { + files.push(path); + tracks.push(t); + } + Err(e) => failed.push(format!("{}: {e}", name_of(&path))), + } + } + open_editor(ui, files, tracks, failed, first_cover); + }, + ); + } + + fn field_changed(&self, i: i32, text: SharedString) { + EDITOR.with(|e| { + if let Some(editor) = e.borrow_mut().as_mut() + && let Some(slot) = usize::try_from(i) + .ok() + .and_then(|i| editor.texts.get_mut(i)) + { + *slot = text.to_string(); + } + }); + } + + fn set_cover(&self, cover: Result) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let mut data = ui.get_tag_editor(); + match cover { + Ok(cover) => { + data.error = "".into(); + data.cover = picture(buffer(&cover.data).as_ref()); + data.has_cover = true; + data.cover_note = "New cover".into(); + EDITOR.with(|e| { + if let Some(editor) = e.borrow_mut().as_mut() { + editor.cover = CoverEdit::Set(cover); + } + }); + } + Err(message) => data.error = message.into(), + } + ui.set_tag_editor(data); + } + + fn cover_path(&self, path: SharedString) { + let path = path.trim(); + if path.is_empty() { + return; + } + let path = Path::new(path); + if !path.is_absolute() { + self.set_cover(Err("Use the full path of the image.".into())); + return; + } + self.set_cover(cover_from_file(path)); + } + + fn cover_dropped(&self, data: slint::DataTransfer) { + let text = data.plain_text().unwrap_or_default(); + let file = parse_uri_list(&text).into_iter().find_map(|u| u.to_path()); + match file { + Some(path) => self.set_cover(cover_from_file(&path)), + None => self.set_cover(Err("Drop an image file from a folder here.".into())), + } + } + + fn cover_removed(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + EDITOR.with(|e| { + if let Some(editor) = e.borrow_mut().as_mut() { + editor.cover = CoverEdit::Remove; + } + }); + let mut data = ui.get_tag_editor(); + data.has_cover = false; + data.cover = Image::default(); + data.cover_note = "Cover will be removed".into(); + ui.set_tag_editor(data); + } + + fn cover_reset(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let mut data = ui.get_tag_editor(); + EDITOR.with(|e| { + if let Some(editor) = e.borrow_mut().as_mut() { + editor.cover = CoverEdit::Keep; + data.has_cover = editor.shown.is_some(); + data.cover = picture(editor.shown.as_ref()); + data.cover_note = cover_note(&editor.set).into(); + } + }); + data.cover_path = "".into(); + data.error = "".into(); + ui.set_tag_editor(data); + } + + fn save(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let built = EDITOR.with(|e| { + e.borrow() + .as_ref() + .map(|editor| (build_edit(editor), editor.files.clone())) + }); + let Some((edit, files)) = built else { + return; + }; + let edit = match edit { + Ok(edit) => edit, + Err(i) => { + let fields = ui.get_tag_editor().fields; + if let Some(mut field) = fields.row_data(i) { + field.error = "Use a whole number".into(); + fields.set_row_data(i, field); + } + return; + } + }; + if edit.is_empty() { + ui.invoke_close_tag_editor(); + return; + } + let mut data = ui.get_tag_editor(); + data.saving = true; + data.progress = 0.0; + data.error = "".into(); + ui.set_tag_editor(data); + let total = files.len(); + let jobs = files.into_iter().map(|f| (f, edit.clone())).collect(); + write_all( + &self.ui, + jobs, + move |ui, done| { + let mut data = ui.get_tag_editor(); + data.progress = done as f32 / total as f32; + ui.set_tag_editor(data); + }, + |ui, failures| { + if failures.is_empty() { + ui.invoke_tags_written("Tags saved".into()); + } else { + let mut data = ui.get_tag_editor(); + data.saving = false; + data.error = failure_text(&failures).into(); + ui.set_tag_editor(data); + } + }, + ); + } + + // ---- lookup ------------------------------------------------------------------------- + + /// From the editor: the files, their current tags and what the fields show now. + fn open_lookup(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let Some((files, tracks, texts)) = EDITOR.with(|e| { + e.borrow() + .as_ref() + .map(|ed| (ed.files.clone(), ed.tracks.clone(), ed.texts.clone())) + }) else { + return; + }; + let first = |f: fn(&TrackTags) -> &Option| { + tracks.iter().find_map(|t| f(t).clone()).unwrap_or_default() + }; + let pick = |text: &str, fallback: String| { + if text.trim().is_empty() { + fallback + } else { + text.trim().to_owned() + } + }; + let album_artist = pick(&texts[3], first(|t| &t.album_artist)); + let artist = pick(&album_artist, pick(&texts[1], first(|t| &t.artist))); + let album = pick(&texts[2], first(|t| &t.album)); + ui.invoke_close_tag_editor(); + self.lookup(files, tracks, artist, album); + } + + /// Opens the lookup on `files` with the search fields filled in. + pub fn lookup( + &self, + files: Vec, + tracks: Vec, + artist: String, + album: String, + ) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + LOOKUP.with(|l| { + *l.borrow_mut() = Some(Lookup { + files, + tracks, + artist: artist.clone(), + album: album.clone(), + hits: Vec::new(), + covers: Vec::new(), + selected: None, + release: None, + assign: Vec::new(), + cover: None, + embed: true, + serial: Arc::new(AtomicU64::new(0)), + }); + }); + ui.set_tag_lookup(TagLookupData { + step: 0, + busy: false, + status: "".into(), + failed: false, + artist: artist.into(), + album: album.into(), + results: ModelRc::new(VecModel::default()), + selected: -1, + release: "".into(), + mapping: ModelRc::new(VecModel::default()), + summary: "".into(), + embed_cover: true, + cover: Image::default(), + has_cover: false, + }); + ui.invoke_show_tag_lookup(); + } + + fn artist_edited(&self, text: SharedString) { + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.artist = text.to_string(); + } + }); + } + + fn album_edited(&self, text: SharedString) { + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.album = text.to_string(); + } + }); + } + + fn lookup_cancelled(&self) { + LOOKUP.with(|l| { + if let Some(l) = l.borrow().as_ref() { + l.serial.fetch_add(1, Ordering::Relaxed); + } + }); + if let Some(ui) = self.ui.upgrade() { + ui.invoke_close_tag_lookup(); + } + } + + fn set_status(ui: &MainWindow, busy: bool, failed: bool, status: &str) { + let mut data = ui.get_tag_lookup(); + data.busy = busy; + data.failed = failed; + data.status = status.into(); + ui.set_tag_lookup(data); + } + + fn search(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let Some((artist, album, files, serial)) = LOOKUP.with(|l| { + l.borrow().as_ref().map(|l| { + let serial = l.serial.fetch_add(1, Ordering::Relaxed) + 1; + ( + l.artist.trim().to_owned(), + l.album.trim().to_owned(), + l.files.len(), + serial, + ) + }) + }) else { + return; + }; + if artist.is_empty() && album.is_empty() { + Self::set_status( + &ui, + false, + true, + "Type an artist or an album to search for.", + ); + return; + } + Self::set_status(&ui, true, false, "Searching MusicBrainz…"); + let client = self.client.clone(); + let latest = LOOKUP.with(|l| l.borrow().as_ref().map(|l| l.serial.clone())); + let Some(latest) = latest else { + return; + }; + let covers_client = self.client.clone(); + let weak = self.ui.clone(); + spawn( + &self.ui, + move || { + let found = client.search_releases( + (!artist.is_empty()).then_some(artist.as_str()), + (!album.is_empty()).then_some(album.as_str()), + None, + MAX_RELEASES, + ); + found.map(|mut hits| { + // Releases with as many tracks as files come first. + hits.sort_by_key(|h| std::cmp::Reverse(h.track_count == Some(files as u32))); + hits + }) + }, + move |ui, found| { + if LOOKUP.with(|l| { + l.borrow() + .as_ref() + .map(|l| l.serial.load(Ordering::Relaxed)) + }) != Some(serial) + { + return; + } + match found { + Err(e) => Self::set_status(ui, false, true, &network_message(&e.to_string())), + Ok(hits) if hits.is_empty() => Self::set_status( + ui, + false, + true, + "Nothing found. Check the spelling, or search with fewer words.", + ), + Ok(hits) => { + show_results(ui, hits, serial); + fetch_covers(&weak, covers_client, latest, serial); + } + } + }, + ); + } + + fn release_picked(&self, i: i32) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.selected = usize::try_from(i).ok().filter(|&i| i < l.hits.len()); + } + }); + let mut data = ui.get_tag_lookup(); + data.selected = i; + ui.set_tag_lookup(data); + } + + fn next(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let Some((hit, cached, tracks, files, serial)) = LOOKUP.with(|l| { + let mut l = l.borrow_mut(); + let l = l.as_mut()?; + let i = l.selected?; + let serial = l.serial.fetch_add(1, Ordering::Relaxed) + 1; + Some(( + l.hits[i].clone(), + l.covers.get(i).cloned().flatten(), + l.tracks.clone(), + l.files.clone(), + serial, + )) + }) else { + Self::set_status(&ui, false, true, "Pick a release first."); + return; + }; + Self::set_status(&ui, true, false, "Fetching the track list…"); + let client = self.client.clone(); + spawn( + &self.ui, + move || { + let release = client.release(&hit.id)?; + let Some(release) = release else { + return Ok(None); + }; + let cover = match cached { + Some(c) => Some(c), + None => client.front_cover(&release.id).ok().flatten(), + }; + let shown = cover.as_ref().and_then(|c| buffer(&c.data)); + let infos: Vec = files + .iter() + .zip(&tracks) + .map(|(path, t)| FileInfo { + disc: t.disc_no, + track: t.track_no, + title: t.title.clone(), + duration_ms: tunal_tags::duration_ms(path), + }) + .collect(); + let assign = tunal_tags::match_tracks(&infos, &release); + Ok::<_, tunal_tags::NetError>(Some((release, cover, shown, assign))) + }, + move |ui, result| { + if LOOKUP.with(|l| { + l.borrow() + .as_ref() + .map(|l| l.serial.load(Ordering::Relaxed)) + }) != Some(serial) + { + return; + } + match result { + Err(e) => Self::set_status(ui, false, true, &network_message(&e.to_string())), + Ok(None) => Self::set_status( + ui, + false, + true, + "MusicBrainz no longer has that release. Pick another.", + ), + Ok(Some((release, cover, shown, assign))) => { + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.release = Some(release); + l.cover = cover; + l.assign = assign; + } + }); + show_mapping(ui, shown); + } + } + }, + ); + } + + fn back(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let step = ui.get_tag_lookup().step; + let mut data = ui.get_tag_lookup(); + data.step = (step - 1).max(0); + data.status = "".into(); + data.failed = false; + ui.set_tag_lookup(data); + } + + fn map_step(&self, row: i32, delta: i32) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let Ok(row) = usize::try_from(row) else { + return; + }; + LOOKUP.with(|l| { + let mut l = l.borrow_mut(); + let Some(l) = l.as_mut() else { + return; + }; + let Some(release) = &l.release else { + return; + }; + let n = release.tracks.len() as i32; + let taken: Vec = l + .assign + .iter() + .enumerate() + .filter(|&(i, _)| i != row) + .filter_map(|(_, t)| *t) + .collect(); + // Slot 0 is "no track"; tracks another file already has are skipped. + let mut slot = l + .assign + .get(row) + .copied() + .flatten() + .map_or(0, |t| t as i32 + 1); + for _ in 0..=n { + slot = (slot + delta).rem_euclid(n + 1); + if slot == 0 || !taken.contains(&(slot as usize - 1)) { + break; + } + } + if let Some(a) = l.assign.get_mut(row) { + *a = (slot > 0).then(|| slot as usize - 1); + } + }); + refresh_mapping(&ui); + } + + fn embed_toggled(&self, on: bool) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.embed = on; + } + }); + let mut data = ui.get_tag_lookup(); + data.embed_cover = on; + ui.set_tag_lookup(data); + } + + fn apply(&self) { + let Some(ui) = self.ui.upgrade() else { + return; + }; + let work = LOOKUP.with(|l| { + let l = l.borrow(); + let l = l.as_ref()?; + let release = l.release.as_ref()?; + let jobs: Vec<(PathBuf, TagEdit)> = l + .files + .iter() + .zip(&l.assign) + .filter_map(|(path, t)| { + let track = release.tracks.get((*t)?)?; + let cover = if l.embed { l.cover.clone() } else { None }; + Some((path.clone(), release_edit(release, track, cover))) + }) + .collect(); + Some(jobs) + }); + let Some(jobs) = work else { + return; + }; + if jobs.is_empty() { + Self::set_status(&ui, false, true, "No file is matched to a track."); + return; + } + Self::set_status(&ui, true, false, "Writing tags…"); + let total = jobs.len(); + write_all( + &self.ui, + jobs, + move |ui, done| { + Self::set_status(ui, true, false, &format!("Writing tags… {done} of {total}")); + }, + move |ui, failures| { + if failures.is_empty() { + let message = format!("Tags updated on {}", plural(total, "file", "files")); + ui.invoke_tags_written(message.into()); + } else { + Self::set_status(ui, false, true, &failure_text(&failures)); + } + }, + ); + } + + /// Screenshots: `editor|lookup|mapping|apply` and the files to open them on. + pub fn debug_open(&self, spec: &str) { + let mut parts = spec.split(':'); + let kind = parts.next().unwrap_or_default().to_owned(); + let files: Vec = parts.map(PathBuf::from).collect(); + match kind.as_str() { + "editor" => self.edit(files), + _ => { + let tracks = files + .iter() + .map(|f| tunal_tags::read(f).unwrap_or_default()) + .collect(); + let (artist, album) = ("The Testers".to_owned(), "Mock Album".to_owned()); + self.lookup(files, tracks, artist, album); + self.search(); + if kind == "mapping" || kind == "apply" { + self.release_picked(0); + self.next(); + } + if kind == "apply" { + self.apply(); + } + } + } + } +} + +fn network_message(error: &str) -> String { + if error.contains("503") || error.contains("429") { + "MusicBrainz is busy. Wait a moment and try again.".into() + } else if error.starts_with("network error") { + "Couldn't reach MusicBrainz. Check your connection and try again.".into() + } else { + format!("MusicBrainz answered something unexpected ({error}).") + } +} + +fn cover_note(set: &TagSet) -> &'static str { + match &set.cover { + Merged::Same(Some(_)) => "Current cover", + Merged::Same(None) => "No cover", + Merged::Mixed => "Covers differ", + } +} + +/// Fills the editor and shows it. +fn open_editor( + ui: &MainWindow, + files: Vec, + tracks: Vec, + failed: Vec, + shown: Option>, +) { + let set = TagSet::merge(&tracks); + let mut initial = Vec::new(); + let mut fields = Vec::new(); + for (i, label) in LABELS.iter().enumerate() { + let (value, mixed) = field_text(&set, i); + initial.push(value.clone()); + fields.push(TagField { + label: (*label).into(), + value: value.into(), + mixed, + error: "".into(), + }); + } + let single_cover = matches!(set.cover, Merged::Same(Some(_))); + let shown = if single_cover { shown } else { None }; + let subtitle = match files.as_slice() { + [only] => name_of(only), + _ => plural(files.len(), "file", "files"), + }; + ui.set_tag_editor(TagEditorData { + subtitle: subtitle.into(), + fields: ModelRc::new(VecModel::from(fields)), + cover: picture(shown.as_ref()), + has_cover: shown.is_some(), + cover_note: cover_note(&set).into(), + cover_path: "".into(), + error: if failed.is_empty() { + "".into() + } else { + format!("Couldn't read: {}", failed.join("; ")).into() + }, + saving: false, + progress: 0.0, + }); + EDITOR.with(|e| { + *e.borrow_mut() = Some(Editor { + files, + tracks, + set, + texts: initial.clone(), + initial, + cover: CoverEdit::Keep, + shown, + }); + }); + ui.invoke_show_tag_editor(); +} + +/// Writes each job's edit on a thread, reporting after every file; `done` gets the failures. +fn write_all( + ui: &slint::Weak, + jobs: Vec<(PathBuf, TagEdit)>, + progress: impl Fn(&MainWindow, usize) + Clone + Send + 'static, + done: impl FnOnce(&MainWindow, Vec) + Send + 'static, +) { + let sync = std::env::var_os("TUNAL_TAGS_SYNC").is_some(); + let weak = ui.clone(); + let run = move || { + let mut failures = Vec::new(); + for (i, (path, edit)) in jobs.iter().enumerate() { + if let Err(e) = tunal_tags::write(path, edit) { + failures.push(format!("{}: {e}", name_of(path))); + } + if !sync { + let progress = progress.clone(); + let _ = weak.upgrade_in_event_loop(move |ui| progress(&ui, i + 1)); + } + } + if sync { + if let Some(ui) = weak.upgrade() { + done(&ui, failures); + } + } else { + let _ = weak.upgrade_in_event_loop(move |ui| done(&ui, failures)); + } + }; + if sync { + run(); + } else { + std::thread::spawn(run); + } +} + +fn failure_text(failures: &[String]) -> String { + format!( + "{} failed. {}", + plural(failures.len(), "file", "files"), + failures.join("; ") + ) +} + +/// The edit a release's track makes on its file. +fn release_edit(release: &Release, track: &tunal_tags::Track, cover: Option) -> TagEdit { + fn set(value: &str) -> Edit { + if value.is_empty() { + Edit::Keep + } else { + Edit::Set(value.to_owned()) + } + } + fn first(ids: &[String]) -> Edit { + ids.first().map_or(Edit::Keep, |id| set(id)) + } + TagEdit { + title: set(&track.title), + artist: set(&track.artist), + album: set(&release.title), + album_artist: set(&release.artist), + track_no: Edit::Set(track.position), + track_total: Edit::Set(track.disc_track_count), + disc_no: Edit::Set(track.disc), + disc_total: Edit::Set(release.disc_total), + date: release.date.as_deref().map_or(Edit::Keep, set), + genre: release.genres.first().map_or(Edit::Keep, |g| set(g)), + mb_recording_id: set(&track.recording_id), + mb_track_id: set(&track.track_id), + mb_release_id: set(&release.id), + mb_release_group_id: release.release_group_id.as_deref().map_or(Edit::Keep, set), + mb_artist_id: first(&track.artist_ids), + mb_release_artist_id: first(&release.artist_ids), + cover: cover.map_or(CoverEdit::Keep, CoverEdit::Set), + ..TagEdit::default() + } +} + +/// Step 1: the releases found. +fn show_results(ui: &MainWindow, hits: Vec, serial: u64) { + let rows: Vec = hits + .iter() + .map(|h| { + let mut parts = vec![h.artist.clone()]; + parts.extend(h.date.clone()); + parts.extend(h.country.clone()); + parts.extend(h.track_count.map(|n| plural(n as usize, "track", "tracks"))); + ReleaseRow { + title: h.title.clone().into(), + detail: parts.join(" · ").into(), + cover: Image::default(), + has_cover: false, + } + }) + .collect(); + let count = hits.len(); + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() { + l.covers = vec![None; count]; + l.hits = hits; + l.selected = Some(0); + } + }); + let mut data = ui.get_tag_lookup(); + data.step = 1; + data.busy = false; + data.failed = false; + data.status = "".into(); + data.results = ModelRc::new(VecModel::from(rows)); + data.selected = 0; + ui.set_tag_lookup(data); + let _ = serial; +} + +/// Fetches the first releases' covers one after another (the rate limit spaces them) and +/// puts each into its row. Stops when the dialog moved on. +fn fetch_covers(ui: &slint::Weak, client: Client, latest: Arc, serial: u64) { + let ids: Vec = LOOKUP.with(|l| { + l.borrow() + .as_ref() + .map(|l| l.hits.iter().map(|h| h.id.clone()).collect()) + .unwrap_or_default() + }); + let sync = std::env::var_os("TUNAL_TAGS_SYNC").is_some(); + let ui = ui.clone(); + let run = move || { + for (i, id) in ids.into_iter().enumerate().take(COVERED_RELEASES) { + if latest.load(Ordering::Relaxed) != serial { + return; + } + let Some(cover) = client.front_cover(&id).ok().flatten() else { + continue; + }; + let shown = buffer(&cover.data); + let put = move |ui: &MainWindow| { + if LOOKUP.with(|l| { + l.borrow() + .as_ref() + .map(|l| l.serial.load(Ordering::Relaxed)) + != Some(serial) + }) { + return; + } + LOOKUP.with(|l| { + if let Some(l) = l.borrow_mut().as_mut() + && let Some(slot) = l.covers.get_mut(i) + { + *slot = Some(cover); + } + }); + let results = ui.get_tag_lookup().results; + if let Some(mut row) = results.row_data(i) { + row.cover = picture(shown.as_ref()); + row.has_cover = shown.is_some(); + results.set_row_data(i, row); + } + }; + if sync { + if let Some(ui) = ui.upgrade() { + put(&ui); + } + } else { + let _ = ui.upgrade_in_event_loop(move |ui| put(&ui)); + } + } + }; + if sync { + run(); + } else { + std::thread::spawn(run); + } +} + +fn track_label(release: &Release, track: usize) -> String { + let t = &release.tracks[track]; + if release.disc_total > 1 { + format!("{}-{} {}", t.disc, t.position, t.title) + } else { + format!("{} {}", t.position, t.title) + } +} + +/// Step 2: the files and the tracks they get. +fn show_mapping(ui: &MainWindow, shown: Option>) { + let (title, has_cover) = LOOKUP.with(|l| { + let l = l.borrow(); + let l = l.as_ref(); + ( + l.and_then(|l| l.release.as_ref()) + .map(|r| format!("{} — {}", r.title, r.artist)) + .unwrap_or_default(), + l.is_some_and(|l| l.cover.is_some()), + ) + }); + let mut data = ui.get_tag_lookup(); + data.step = 2; + data.busy = false; + data.failed = false; + data.status = "".into(); + data.release = title.into(); + data.cover = picture(shown.as_ref()); + data.has_cover = has_cover && shown.is_some(); + data.embed_cover = LOOKUP.with(|l| l.borrow().as_ref().is_none_or(|l| l.embed)); + data.mapping = ModelRc::new(VecModel::default()); + ui.set_tag_lookup(data); + refresh_mapping(ui); +} + +/// Rebuilds the mapping rows and the summary from the assignment. +fn refresh_mapping(ui: &MainWindow) { + let (rows, summary) = LOOKUP.with(|l| { + let l = l.borrow(); + let Some(l) = l.as_ref() else { + return (Vec::new(), String::new()); + }; + let Some(release) = &l.release else { + return (Vec::new(), String::new()); + }; + let rows: Vec = l + .files + .iter() + .zip(&l.tracks) + .zip(&l.assign) + .map(|((path, tags), t)| MapRow { + file: name_of(path).into(), + old_title: tags.title.clone().unwrap_or_default().into(), + track: t.map(|t| track_label(release, t)).unwrap_or_default().into(), + matched: t.is_some(), + }) + .collect(); + let matched = l.assign.iter().flatten().count(); + let mut summary = format!( + "Sets title, artist, album, album artist, track and disc numbers, date, genre and MusicBrainz ids on {} of {}.", + matched, + plural(l.files.len(), "file", "files") + ); + if matched < l.files.len() { + summary.push_str(" The others stay as they are."); + } + (rows, summary) + }); + let mut data = ui.get_tag_lookup(); + data.mapping = ModelRc::new(VecModel::from(rows)); + data.summary = summary.into(); + ui.set_tag_lookup(data); +} diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint index 027991b..c130ea8 100644 --- a/crates/tunal/ui/app.slint +++ b/crates/tunal/ui/app.slint @@ -23,12 +23,14 @@ import { ErrorsDialog } from "dialogs/errors.slint"; import { PropertiesDialog, PropertiesInfo, PropRow } from "dialogs/properties.slint"; import { OpenWithDialog, AppRow } from "dialogs/open-with.slint"; import { FolderAppearanceDialog, IconChoice } from "dialogs/folder-appearance.slint"; +import { TagEditorDialog, TagEditorData, TagField } from "dialogs/tag-editor.slint"; +import { TagLookupDialog, TagLookupData, ReleaseRow, MapRow } from "dialogs/tag-lookup.slint"; import { SettingsDialog, SettingsData, EditRow } from "dialogs/settings.slint"; import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slint"; export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow } export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow } -export { PropertiesInfo, PropRow, AppRow, IconChoice, Dnd, DropAction, DropTarget } +export { PropertiesInfo, PropRow, AppRow, IconChoice, Dnd, DropAction, DropTarget, TagEditorData, TagField, TagLookupData, ReleaseRow, MapRow } export { Gallery, GalleryPage } from "gallery.slint"; // The window: sidebar, tab bar, toolbar with the breadcrumb, the panes of the current tab @@ -137,6 +139,29 @@ export component MainWindow inherits Window { callback appearance-saved(bool); callback appearance-done(bool); + // Tag editor and lookup (tags_bridge.rs). + in-out property tag-editor; + callback tag-editor-saved(); + callback tag-editor-lookup(); + callback tag-field-changed(int, string); + callback tag-cover-path(string); + callback tag-cover-dropped(data-transfer); + callback tag-cover-removed(); + callback tag-cover-reset(); + in-out property tag-lookup; + callback tag-artist-edited(string); + callback tag-album-edited(string); + callback tag-search(); + callback tag-release-picked(int); + callback tag-next(); + callback tag-back(); + callback tag-lookup-cancelled(); + callback tag-map-step(int, int); + callback tag-embed-toggled(bool); + callback tag-apply(); + // Tags were written to the files; the argument is the message for a toast. + callback tags-written(string); + // Properties (properties.rs) and Open with (open.rs). in property properties; callback properties-closed(); @@ -236,6 +261,22 @@ export component MainWindow inherits Window { appearance-dialog.close(); } + public function show-tag-editor() { + tag-editor-dialog.show(); + } + + public function close-tag-editor() { + tag-editor-dialog.close(); + } + + public function show-tag-lookup() { + tag-lookup-dialog.show(); + } + + public function close-tag-lookup() { + tag-lookup-dialog.close(); + } + public function show-open-with() { open-with-dialog.show(); } @@ -720,6 +761,69 @@ export component MainWindow inherits Window { } } + tag-editor-dialog := TagEditorDialog { + width: 100%; + height: 100%; + data <=> root.tag-editor; + saved => { + root.tag-editor-saved(); + } + lookup => { + root.tag-editor-lookup(); + } + field-changed(i, text) => { + root.tag-field-changed(i, text); + } + cover-path-accepted(path) => { + root.tag-cover-path(path); + } + cover-dropped(data) => { + root.tag-cover-dropped(data); + } + cover-removed => { + root.tag-cover-removed(); + } + cover-reset => { + root.tag-cover-reset(); + } + } + + tag-lookup-dialog := TagLookupDialog { + width: 100%; + height: 100%; + data <=> root.tag-lookup; + artist-edited(text) => { + root.tag-artist-edited(text); + } + album-edited(text) => { + root.tag-album-edited(text); + } + search => { + root.tag-search(); + } + release-picked(i) => { + root.tag-release-picked(i); + } + next => { + root.tag-next(); + } + back => { + root.tag-back(); + } + cancelled => { + root.tag-lookup-cancelled(); + } + map-step(row, delta) => { + root.tag-map-step(row, delta); + } + embed-toggled(on) => { + root.tag-embed-toggled(on); + } + apply => { + root.tag-apply(); + } + } + errors-dialog := ErrorsDialog { width: 100%; height: 100%; diff --git a/crates/tunal/ui/dialogs/tag-editor.slint b/crates/tunal/ui/dialogs/tag-editor.slint new file mode 100644 index 0000000..aeb5d43 --- /dev/null +++ b/crates/tunal/ui/dialogs/tag-editor.slint @@ -0,0 +1,348 @@ +import { ScrollView } from "std-widgets.slint"; +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icons } from "../components/icon.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { IconButton } from "../components/icon-button.slint"; +import { TextField } from "../components/text-field.slint"; +import { Shape, ShapeKind } from "../components/shape.slint"; + +// One text field of the editor. `mixed` fields start empty with "Keep" as their placeholder: +// the files differ, and leaving the field alone leaves each file as it is. +export struct TagField { + label: string, + value: string, + mixed: bool, + error: string, +} + +export struct TagEditorData { + // "3 files" or the name of the one file. + subtitle: string, + fields: [TagField], + cover: image, + has-cover: bool, + // "Keep", "New cover", "Removed", "Covers differ". + cover-note: string, + cover-path: string, + error: string, + saving: bool, + progress: float, +} + +// A tag field; `changed` reports the text for Rust, which keeps the values. +component TagInput { + in property field; + callback changed(string); + public function focus-input() { + input.focus-input(); + } + + horizontal-stretch: 1; + min-width: 0; + preferred-height: input.preferred-height; + + input := TextField { + width: 100%; + label: root.field.label; + text: root.field.value; + placeholder: root.field.mixed ? "Keep" : ""; + error: root.field.error; + edited(text) => { + root.changed(text); + } + } +} + +// The front cover: a picture or a placeholder, and a drop target for an image file. +component CoverBox { + in property source; + in property has-image; + callback dropped(data-transfer); + + width: 128px; + height: 128px; + + Rectangle { + background: Theme.surface-container-highest; + border-radius: Theme.corner-md; + clip: true; + + if root.has-image: Image { + width: 100%; + height: 100%; + source: root.source; + image-fit: cover; + } + + if !root.has-image: Shape { + size: 64px; + x: (parent.width - self.width) / 2; + y: (parent.height - self.height) / 2; + shape: ShapeKind.clover; + fill: Theme.tertiary-container; + glyph: Icons.music-note; + glyph-color: Theme.on-tertiary-container; + } + } + + drop := DropArea { + can-drop(event) => { + event.proposed-action + } + dropped(event) => { + root.dropped(event.data); + event.proposed-action + } + } + + // While an image is dragged over it. + Rectangle { + border-radius: Theme.corner-md; + border-width: 2px; + border-color: Theme.primary; + background: Theme.primary.with-alpha(Theme.state-drag); + opacity: drop.has-drag ? 1 : 0; + animate opacity { + duration: Motion.time(Motion.short3); + easing: Motion.standard; + } + } +} + +// Edits the tags of one or many files. `saved` runs on Save and `lookup` on "Look up online"; +// the owner closes the dialog, or sets `error`. +export component TagEditorDialog inherits Dialog { + glyph: Icons.audio; + in-out property data; + callback saved(); + callback lookup(); + callback field-changed(int, string); + callback cover-path-accepted(string); + callback cover-dropped(data-transfer); + callback cover-removed(); + callback cover-reset(); + + title: "Edit tags"; + body: root.data.subtitle; + dialog-width: 680px; + actions: [ + { text: "Cancel", kind: ButtonKind.text }, + { text: "Look up online", kind: ButtonKind.tonal }, + { text: root.data.saving ? "Saving…" : "Save", kind: ButtonKind.filled } + ]; + default-action: 2; + cancel-action: 0; + content-focus: true; + focus-content => { + title-field.focus-input(); + } + action(i) => { + if root.data.saving { + return; + } + if i == 0 { + root.close(); + } else if i == 1 { + root.lookup(); + } else { + root.saved(); + } + } + + // The fields scroll when the window is too short for all of them. + Rectangle { + height: min(fields.preferred-height, max(160px, root.height - 300px)); + + ScrollView { + fields := VerticalLayout { + spacing: Theme.space-1; + + HorizontalLayout { + spacing: Theme.space-4; + + VerticalLayout { + spacing: Theme.space-1; + alignment: start; + + CoverBox { + source: root.data.cover; + has-image: root.data.has-cover; + dropped(data) => { + root.cover-dropped(data); + } + } + + HorizontalLayout { + alignment: center; + + IconButton { + icon: Icons.delete; + size: 32px; + icon-size: 20px; + tooltip: "Remove the cover"; + clicked => { + root.cover-removed(); + } + } + + IconButton { + icon: Icons.restore; + size: 32px; + icon-size: 20px; + tooltip: "Undo cover changes"; + clicked => { + root.cover-reset(); + } + } + } + + Text { + text: root.data.cover-note; + horizontal-alignment: center; + color: Theme.on-surface-variant; + font-size: Theme.label-medium.size; + font-weight: Theme.label-medium.weight; + overflow: elide; + } + } + + VerticalLayout { + horizontal-stretch: 1; + alignment: start; + + title-field := TagInput { + field: root.data.fields[0]; + changed(text) => { + root.field-changed(0, text); + } + } + + TextField { + label: "Cover image (full path, then Enter) or drop one on the cover"; + placeholder: "/path/to/cover.jpg"; + text <=> root.data.cover-path; + accepted(text) => { + root.cover-path-accepted(text); + } + } + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + TagInput { + field: root.data.fields[1]; + changed(text) => { + root.field-changed(1, text); + } + } + + TagInput { + field: root.data.fields[2]; + changed(text) => { + root.field-changed(2, text); + } + } + + TagInput { + field: root.data.fields[3]; + changed(text) => { + root.field-changed(3, text); + } + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + TagInput { + field: root.data.fields[4]; + changed(text) => { + root.field-changed(4, text); + } + } + + TagInput { + field: root.data.fields[5]; + changed(text) => { + root.field-changed(5, text); + } + } + + TagInput { + field: root.data.fields[6]; + changed(text) => { + root.field-changed(6, text); + } + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + TagInput { + field: root.data.fields[7]; + changed(text) => { + root.field-changed(7, text); + } + } + + TagInput { + field: root.data.fields[8]; + changed(text) => { + root.field-changed(8, text); + } + } + + TagInput { + field: root.data.fields[9]; + changed(text) => { + root.field-changed(9, text); + } + } + + TagInput { + field: root.data.fields[10]; + changed(text) => { + root.field-changed(10, text); + } + } + } + + TagInput { + field: root.data.fields[11]; + changed(text) => { + root.field-changed(11, text); + } + } + } + } + } + + if root.data.saving: Rectangle { + height: 4px; + border-radius: Theme.corner-full(4px); + background: Theme.surface-container-highest; + + Rectangle { + x: 0; + width: parent.width * root.data.progress; + border-radius: parent.border-radius; + background: Theme.primary; + animate width { + duration: Motion.time(Motion.short4); + easing: Motion.standard; + } + } + } + + if root.data.error != "": Text { + text: root.data.error; + color: Theme.error; + font-size: Theme.body-small.size; + wrap: word-wrap; + } +} diff --git a/crates/tunal/ui/dialogs/tag-lookup.slint b/crates/tunal/ui/dialogs/tag-lookup.slint new file mode 100644 index 0000000..ed7bce1 --- /dev/null +++ b/crates/tunal/ui/dialogs/tag-lookup.slint @@ -0,0 +1,271 @@ +import { ListView } from "std-widgets.slint"; +import { Theme } from "../theme.slint"; +import { Motion } from "../motion.slint"; +import { Icons } from "../components/icon.slint"; +import { Dialog } from "../components/dialog.slint"; +import { ButtonKind } from "../components/button.slint"; +import { IconButton } from "../components/icon-button.slint"; +import { ListRow } from "../components/list-row.slint"; +import { Switch } from "../components/switch.slint"; +import { TextField } from "../components/text-field.slint"; + +// A release found by the search. +export struct ReleaseRow { + title: string, + // "Artist · 2020 · XW · 12 tracks". + detail: string, + cover: image, + has-cover: bool, +} + +// One file and the release track it gets. `old-title` is what the file has now. +export struct MapRow { + file: string, + old-title: string, + track: string, + matched: bool, +} + +export struct TagLookupData { + // 0 search, 1 pick a release, 2 match files to tracks. + step: int, + busy: bool, + // A plain line under the fields: progress, or why nothing came back. + status: string, + failed: bool, + artist: string, + album: string, + results: [ReleaseRow], + selected: int, + // The chosen release, for the last step. + release: string, + mapping: [MapRow], + summary: string, + embed-cover: bool, + cover: image, + has-cover: bool, +} + +// Looks a release up on MusicBrainz and copies its tags and cover to the files. The owner +// closes the dialog; `apply` runs on the last step. +export component TagLookupDialog inherits Dialog { + glyph: Icons.search; + in-out property data; + callback artist-edited(string); + callback album-edited(string); + callback search(); + callback release-picked(int); + callback next(); + callback back(); + callback cancelled(); + callback map-step(int, int); + callback embed-toggled(bool); + callback apply(); + + title: "Look up tags"; + body: root.data.step == 0 ? "Search MusicBrainz for the album these files belong to." + : root.data.step == 1 ? "Pick the release." + : root.data.release; + dialog-width: 640px; + actions: root.data.step == 0 + ? [{ text: "Cancel", kind: ButtonKind.text }, { text: "Search", kind: ButtonKind.filled }] + : root.data.step == 1 + ? [{ text: "Back", kind: ButtonKind.text }, { text: "Continue", kind: ButtonKind.filled }] + : [{ text: "Back", kind: ButtonKind.text }, { text: "Apply", kind: ButtonKind.filled }]; + default-action: 1; + cancel-action: 0; + content-focus: root.data.step == 0; + // The artist field (inside the first step) takes the focus when this changes. + property focus-request; + focus-content => { + root.focus-request += 1; + } + action(i) => { + if root.data.busy { + return; + } + if i == 0 { + if root.data.step == 0 { + root.cancelled(); + } else { + root.back(); + } + } else if root.data.step == 0 { + root.search(); + } else if root.data.step == 1 { + root.next(); + } else { + root.apply(); + } + } + + if root.data.step == 0: VerticalLayout { + artist-field := TextField { + property request: root.focus-request; + + changed request => { + self.focus-input(); + } + label: "Artist"; + text: root.data.artist; + edited(text) => { + root.artist-edited(text); + } + accepted => { + root.search(); + } + } + + TextField { + label: "Album"; + text: root.data.album; + edited(text) => { + root.album-edited(text); + } + accepted => { + root.search(); + } + } + } + + if root.data.step == 1: VerticalLayout { + spacing: Theme.space-1; + + for item[i] in root.data.results: ListRow { + icon: Icons.audio; + title: item.title; + supporting: item.detail; + shaped: true; + shape-size: 44px; + picture: item.cover; + has-picture: item.has-cover; + selected: i == root.data.selected; + clicked => { + root.release-picked(i); + } + } + } + + if root.data.step == 2: VerticalLayout { + spacing: Theme.space-2; + + Rectangle { + height: min(root.data.mapping.length * 52px + 4px, 280px); + + ListView { + for row[i] in root.data.mapping: Rectangle { + height: 52px; + + HorizontalLayout { + spacing: Theme.space-2; + padding-right: Theme.space-2; + + VerticalLayout { + horizontal-stretch: 1; + alignment: center; + + Text { + text: row.file; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + overflow: elide; + } + + Text { + text: row.old-title == "" ? "No title yet" : row.old-title; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + overflow: elide; + } + } + + VerticalLayout { + alignment: center; + + IconButton { + icon: Icons.arrow-back; + size: 32px; + icon-size: 20px; + tooltip: "Previous track"; + clicked => { + root.map-step(i, -1); + } + } + } + + Text { + width: 220px; + text: row.matched ? row.track : "Keep this file as it is"; + color: row.matched ? Theme.primary : Theme.on-surface-variant; + font-size: Theme.body-medium.size; + font-weight: Theme.label-large.weight; + vertical-alignment: center; + overflow: elide; + } + + VerticalLayout { + alignment: center; + + IconButton { + icon: Icons.arrow-forward; + size: 32px; + icon-size: 20px; + tooltip: "Next track"; + clicked => { + root.map-step(i, 1); + } + } + } + } + } + } + } + + HorizontalLayout { + spacing: Theme.space-3; + + Text { + horizontal-stretch: 1; + text: root.data.has-cover ? "Embed the release cover" : "No cover found for this release"; + color: Theme.on-surface; + font-size: Theme.body-medium.size; + font-weight: Theme.body-medium.weight; + vertical-alignment: center; + } + + if root.data.has-cover: Image { + width: 40px; + height: 40px; + source: root.data.cover; + image-fit: cover; + } + + Switch { + enabled: root.data.has-cover; + checked: root.data.embed-cover && root.data.has-cover; + accessible-label: "Embed the release cover"; + clicked => { + root.embed-toggled(!root.data.embed-cover); + } + } + } + + Text { + text: root.data.summary; + color: Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + wrap: word-wrap; + } + } + + if root.data.status != "": Text { + text: root.data.status; + color: root.data.failed ? Theme.error : Theme.on-surface-variant; + font-size: Theme.body-small.size; + font-weight: Theme.body-small.weight; + wrap: word-wrap; + } +} diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d87f137..95123a1 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -193,6 +193,13 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Not done: real phone, hotplug events, MTP events, permission message (S036). Breadcrumb shows the serial and storage hex, not names. Long transfers hold the device lock (listing waits). - Later: device/storage names in breadcrumb; cancel a running GetObject (MTP Cancel request); free space in the sidebar tooltip. +## S021 — Tag editor UI +- Done: action `edit-tags` ("Edit tags…", enabled when every selected entry is a local audio file; in the File and Several-items default menus; a saved `menus.toml` keeps its own layout). `tags_bridge.rs` (`Tags`), `ui/dialogs/tag-editor.slint` (`TagEditorDialog`), `tag-lookup.slint` (`TagLookupDialog`). Editor: 12 text fields (title, artist, album, album artist, genre, composer, date, track/disc no. and total, comment), mixed ones empty with "Keep"; an untouched field stays Keep, emptied = Clear, typed = Set (numbers checked); cover box (current/new/removed, remove + undo, image path field, drop an image file on it); Save writes off-thread with a progress bar, failed files listed and the dialog stays open; fields scroll when the window is short. "Look up online" → search (prefilled from the fields/tags; releases with as many tracks as files first) → releases with title, artist, date, country, track count and cover (first 6, fetched one by one) → files ↔ tracks (`match_tracks`, arrows to change, a track used twice is skipped, "Keep this file as it is") + embed-cover switch + summary → Apply writes title/artist/album/album artist/track+disc numbers and totals/date/first genre/MusicBrainz ids/cover on matched files. Errors (offline, busy, nothing found, release gone) as plain lines. Panes list again after a write. `tunal-tags::duration_ms(path)` added for matching. +- Tools (CLAUDE.md §5): `TUNAL_TAGS=editor|lookup|mapping|apply::…` with `TUNAL_TAGS_SYNC=1` (work in place) and `TUNAL_MUSICBRAINZ=` (mock for both services). +- Verified: workspace build, clippy -D warnings, fmt --check, literal grep empty; screenshots light + dark of the multi-file editor, lookup results (cover shown) and mapping, against a scratchpad python mock; `apply` on scratch mp3s fixed album, set totals/date/genre/ids and replaced the cover (read back with the `tags` example). Real music and real MusicBrainz untouched. +- Not done: no live window (typing, drop, clicks, progress bar motion, scrolling); no file chooser for the cover (path field or drop); a mixed field can't be cleared on purpose (only set); lookup apply doesn't offer per-field choice; offline/busy messages not seen live. +- Later: file chooser; per-field "clear" for mixed values; recording search by title when no album; lookup for one file with no album tag uses the file name. + ## Later - (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034. -