diff --git a/src/libcmd.rs b/src/libcmd.rs index 77ca813..cf79cb8 100644 --- a/src/libcmd.rs +++ b/src/libcmd.rs @@ -580,3 +580,36 @@ mod loudness_tests { assert_eq!(crate::library::parse_gain("-6.20 dB"), Some(-6.2)); } } + +#[tauri::command] +pub async fn tracks_edit(app: AppHandle, state: State<'_, AppState>, ids: Vec, meta: TagFields) -> CmdResult { + let s = state.snapshot(); + let ffmpeg = crate::engine::locate(&s.ytdlp_path, &s.ffmpeg_path).ok().and_then(|t| t.ffmpeg); + let (_, pl) = dirs(&state); + let mut done = 0; + let mut failed = Vec::new(); + for (i, id) in ids.iter().enumerate() { + let Some(t) = state.library.track(id) else { continue }; + match tagging::apply(Path::new(&t.path), &meta, "", ffmpeg.as_deref()).await { + Ok(()) => { + let _ = state.library.refresh(id, &pl); + done += 1; + } + Err(e) => failed.push(format!("{} ({e})", t.title)), + } + let _ = app.emit(LIBRARY_EVENT, serde_json::json!({ "type": "editing", "done": i + 1, "total": ids.len() })); + } + changed(&app); + if done == 0 && !failed.is_empty() { + return Err(format!("Couldn't update {}", failed.join(", "))); + } + Ok(done) +} + +#[tauri::command] +pub fn playlist_cover(app: AppHandle, state: State<'_, AppState>, name: String, path: Option) -> CmdResult<()> { + let (_, pl) = dirs(&state); + state.library.playlist_cover(&pl, &name, path.as_deref().map(Path::new)).map_err(err)?; + changed(&app); + Ok(()) +} diff --git a/src/library.rs b/src/library.rs index 01f18fd..224dab8 100644 --- a/src/library.rs +++ b/src/library.rs @@ -83,6 +83,19 @@ pub struct Playlist { pub order: Vec, pub linked: bool, pub missing: bool, + pub cover: Option, +} + +pub const COVER_NAMES: [&str; 4] = ["cover.jpg", "folder.jpg", "cover.png", "folder.png"]; + +fn folder_cover(folder: &Path) -> Option { + let file = COVER_NAMES.iter().map(|n| folder.join(n)).find(|p| p.is_file())?; + let (size, mtime) = file_stamp(&file)?; + let key = hash(&format!("{}|{size}|{mtime}", file.to_string_lossy())); + if art_dir().join(format!("{key}.jpg")).exists() { + return Some(key); + } + save_art(&key, &std::fs::read(&file).ok()?) } #[derive(Clone, Debug, Default, Serialize, Deserialize)] @@ -372,7 +385,8 @@ impl Library { let rel = |t: &Track| Path::new(&t.path).strip_prefix(&folder).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); members.sort_by_key(|t| (order.iter().position(|o| *o == rel(t)).unwrap_or(usize::MAX), rel(t).to_lowercase())); let missing = linked && !folder.is_dir(); - out.push(Playlist { name, path: folder.to_string_lossy().into_owned(), order: members.iter().map(|t| t.id.clone()).collect(), linked, missing }); + let cover = if missing { None } else { folder_cover(&folder) }; + out.push(Playlist { name, path: folder.to_string_lossy().into_owned(), order: members.iter().map(|t| t.id.clone()).collect(), linked, missing, cover }); } out.sort_by_key(|p| p.name.to_lowercase()); out @@ -793,6 +807,27 @@ impl Library { Ok(out) } + pub fn playlist_cover(&self, dir: &Path, name: &str, image: Option<&Path>) -> Result<()> { + let folder = self.folder(dir, name); + if !folder.is_dir() { + bail!("That playlist's folder can't be found."); + } + for n in COVER_NAMES { + let p = folder.join(n); + if p.is_file() { + trash::delete(&p).map_err(|e| anyhow!("Couldn't remove the old cover ({e})"))?; + } + } + if let Some(src) = image { + let img = image::open(src).context("That image couldn't be read")?; + let img = if img.width() > 1200 || img.height() > 1200 { img.thumbnail(1200, 1200) } else { img }; + let mut buf = Vec::new(); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, 90).encode_image(&img.to_rgb8()).context("Couldn't save the cover")?; + std::fs::write(folder.join("cover.jpg"), buf).context("Couldn't save the cover")?; + } + Ok(()) + } + pub fn set_gain(&self, id: &str, gain: f32) { let changed = self.tracks.write().unwrap().get_mut(id).map(|t| t.gain_db = Some(gain)).is_some(); if changed { diff --git a/src/main.rs b/src/main.rs index a071de7..2ec73f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -533,6 +533,8 @@ fn main() { libcmd::set_fullscreen, libcmd::playlist_link, libcmd::track_loudness, + libcmd::tracks_edit, + libcmd::playlist_cover, libcmd::playlist_relocate, libcmd::playlist_unlink ]) diff --git a/ui/library.js b/ui/library.js index 2c532c8..643ce2b 100644 --- a/ui/library.js +++ b/ui/library.js @@ -345,6 +345,7 @@ function trackMenu(e, t, ctx, i) { { label: "Add to queue", run: () => Player.addToQueue(many) }, "-", { label: "Add to playlist", sub: playlistItems(many) }, + { label: `Edit info for ${many.length} songs…`, run: () => editTracks(many) }, inList.length ? { label: `Remove ${inList.length} from this playlist`, run: () => removeFromPlaylist(ctx.playlist, inList) } : null, "-", { label: `Remove ${many.length} from library`, run: () => hideTracks(many) }, @@ -515,6 +516,88 @@ async function newPlaylist(tracks = []) { } } +function shared(tracks, get) { + const vals = new Set(tracks.map((t) => String(get(t) ?? "").trim())); + return vals.size === 1 ? [...vals][0] : ""; +} + +async function editTracks(tracks, opts = {}) { + if (!tracks.length) return; + const title = opts.title || `Edit ${plural(tracks.length, "song")}`; + const fields = [ + ["album", "Album", shared(tracks, (t) => t.album)], + ["albumArtist", "Album artist", shared(tracks, (t) => t.albumArtist || (opts.album ? opts.album.artist : ""))], + ["artist", "Artist", opts.album ? "" : shared(tracks, (t) => t.artist)], + ["date", "Year", shared(tracks, (t) => t.year)], + ["genre", "Genre", shared(tracks, (t) => t.genre)], + ].filter(([k]) => !(opts.album && k === "artist")); + const inputs = {}; + const grid = h("div", { class: "fields two" }, ...fields.map(([k, label, v]) => h("label", { class: `field ${k === "album" ? "full" : ""}` }, h("span", {}, label), (inputs[k] = h("input", { value: v, placeholder: v ? "" : "Mixed: leave blank to keep each song's own", spellcheck: "false" }))))); + let artwork = { kind: "keep" }; + const currentArt = shared(tracks, (t) => t.art); + const preview = h("div", { class: "edit-cover" }); + const showPreview = (src) => preview.replaceChildren(src ? h("img", { src, alt: "" }) : h("div", { class: "edit-cover-ph" }, icon("photo"))); + showPreview(currentArt ? artUrl(currentArt) : null); + const coverNote = h("p", { class: "muted small" }, currentArt ? "Current cover." : tracks.some((t) => t.art) ? "These songs have different covers." : "No cover yet."); + const coverBox = h("div", { class: "edit-cover-row" }, preview, h("div", { class: "stack" }, + h("strong", {}, "Cover art"), coverNote, + h("div", { class: "row" }, + h("button", { class: "btn small", type: "button", onclick: async () => { const p = await invoke("pick_image").catch((x) => (toast(errText(x), "err"), null)); if (p) { artwork = { kind: "file", path: p.path }; showPreview(p.dataUrl); coverNote.textContent = `New cover for all ${plural(tracks.length, "song")}.`; } } }, "Choose image…"), + h("button", { class: "btn small ghost", type: "button", onclick: () => { artwork = { kind: "none" }; showPreview(null); coverNote.textContent = "The cover will be removed from every song."; } }, "Remove")))); + const ok = await modal(title, h("div", { class: "stack" }, coverBox, grid, h("p", { class: "muted small" }, "Changes are written into each file's tags. Fields you leave untouched aren't changed.")), [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }]); + if (!ok) return; + const meta = { artwork }; + for (const [k, , v] of fields) { + const nv = inputs[k].value.trim(); + if (nv && nv !== v) meta[k] = nv; + } + if (Object.keys(meta).length === 1 && artwork.kind === "keep") return; + toast(`Updating ${plural(tracks.length, "song")}…`, ""); + try { + const n = await invoke("tracks_edit", { ids: tracks.map((t) => t.id), meta }); + toast(`Updated ${plural(n, "song")}`, "ok"); + await loadLibrary(); + if (opts.album) { + const artist = meta.albumArtist || opts.album.artist; + const key = `${lnorm(artist)}|${lnorm(meta.album || opts.album.title)}`; + if (Lib.albums.has(key)) openLib("album", key, false); + } + } catch (e) { + toast(errText(e), "err"); + } +} + +const kindWord = (a) => (albumKind(a) === "EP" ? "EP" : albumKind(a).toLowerCase()); +const editAlbum = (a) => editTracks(a.tracks, { album: a, title: `Edit ${kindWord(a)}` }); + +async function editPlaylist(p) { + const input = h("input", { class: "text wide", value: p.name, "aria-label": "Playlist name", spellcheck: "false" }); + let cover = null; + const preview = h("div", { class: "edit-cover" }); + const tracks = p.order.map((id) => Lib.byId.get(id)).filter(Boolean); + const showPreview = (src) => preview.replaceChildren(src ? h("img", { src, alt: "" }) : h("div", { class: "edit-cover-ph" }, icon("playlist"))); + showPreview(p.cover ? artUrl(p.cover) : tracks[0]?.art ? artUrl(tracks[0].art) : null); + const note = h("p", { class: "muted small" }, p.cover ? "Saved as cover.jpg in the playlist folder." : "Uses the songs' covers until you choose one."); + const body = h("div", { class: "stack" }, + h("label", { class: "field full" }, h("span", {}, "Name"), input), + h("div", { class: "edit-cover-row" }, preview, h("div", { class: "stack" }, h("strong", {}, "Playlist cover"), note, + h("div", { class: "row" }, + h("button", { class: "btn small", type: "button", onclick: async () => { const x = await invoke("pick_image").catch((e) => (toast(errText(e), "err"), null)); if (x) { cover = { path: x.path }; showPreview(x.dataUrl); note.textContent = "Saved as cover.jpg in the folder, so phones and other players show it too."; } } }, "Choose image…"), + p.cover ? h("button", { class: "btn small ghost", type: "button", onclick: () => { cover = { path: null }; showPreview(tracks[0]?.art ? artUrl(tracks[0].art) : null); note.textContent = "The cover image will go to the Recycle Bin."; } }, "Remove") : null)))); + const ok = await modal(p.linked ? "Edit linked folder" : "Edit playlist", body, [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }]); + if (!ok) return; + let name = p.name; + try { + const want = input.value.trim(); + if (want && want !== p.name) name = await invoke("playlist_rename", { from: p.name, to: want }); + if (cover) await invoke("playlist_cover", { name, path: cover.path }); + await loadLibrary(); + openLib("playlist", name, false); + } catch (e) { + toast(errText(e), "err"); + } +} + async function editInfo(t) { const fields = [["title", "Title", t.title], ["artist", "Artist", t.artist], ["album", "Album", t.album], ["albumArtist", "Album artist", t.albumArtist], ["trackNumber", "Track", t.trackNo ?? ""], ["discNumber", "Disc", t.discNo ?? ""], ["date", "Year", t.year ?? ""], ["genre", "Genre", t.genre]]; const inputs = {}; @@ -645,7 +728,7 @@ function albumView(root, key) { h("h1", { class: "hero-title" }, a.title), h("button", { class: "link hero-artist", onclick: () => openLib("artist", lnorm(a.artist)) }, a.artist), h("p", { class: "view-sub" }, `${plural(a.tracks.length, "song")} · ${fmtLong(a.duration)}`), - h("div", { class: "row" }, ...playBtns(a.tracks), h("button", { class: "btn ghost", onclick: (e) => menuAt(e.clientX, e.clientY, playlistItems(a.tracks)()) }, icon("playlist-add"), "Add to playlist")))) + h("div", { class: "row" }, ...playBtns(a.tracks), h("button", { class: "btn ghost", onclick: (e) => menuAt(e.clientX, e.clientY, playlistItems(a.tracks)()) }, icon("playlist-add"), "Add to playlist"), h("button", { class: "btn ghost", onclick: () => editAlbum(a) }, icon("pencil"), "Edit")))) ); if (Lib.back.length) root.firstChild.prepend(h("button", { class: "icon-btn back on-hero", "aria-label": "Back", onclick: libBack }, icon("arrow-left"))); const ctx = { hideAlbum: true, hideArtist: !multiArtist, showArtistFor: (t) => lnorm(primaryArtist(t.artist)) !== lnorm(a.artist), numbers: (t, i) => t.trackNo || i + 1 }; @@ -741,7 +824,7 @@ function playlistView(root, name) { root.append( h("header", { class: "hero" }, h("div", { class: "hero-bg", style: tracks[0]?.art ? `background-image:url("${artUrl(tracks[0].art)}")` : "" }), - mosaic(tracks), + p.cover ? cover(p.cover, "hero-cover", p.name) : mosaic(tracks), h("div", { class: "hero-meta" }, h("div", { class: "kind-line" }, h("span", { class: "kind-btn", style: "cursor:default" }, icon(p.linked ? "link" : "folder"), p.linked ? "Your folder" : "Playlist folder")), title, @@ -749,6 +832,7 @@ function playlistView(root, name) { h("button", { class: "link path", title: "Open this folder", onclick: () => invoke("reveal", { path: p.path }) }, p.path), h("div", { class: "row" }, ...playBtns(tracks), h("button", { class: "btn ghost", onclick: async () => { try { const n = await invoke("playlist_add_files", { name: p.name }); if (n) toast(`Added ${plural(n, "song")}`, "ok"); } catch (e) { toast(errText(e), "err"); } } }, icon("plus"), "Add files…"), + h("button", { class: "btn ghost", onclick: () => editPlaylist(p) }, icon("pencil"), "Edit"), p.linked ? h("button", { class: "btn ghost", onclick: () => unlinkFolder(p.name) }, icon("x"), "Remove from Atmosphere") : h("button", { class: "btn ghost danger", onclick: async () => { if (await confirmBox(`Delete “${p.name}”?`, "The playlist folder goes to your Recycle Bin or Trash. Songs in your library aren't touched.", "Delete")) { await invoke("playlist_delete", { name: p.name }).catch((e) => toast(errText(e), "err")); openLib("songs", null, false); } } }, icon("trash"), "Delete")))) @@ -773,7 +857,7 @@ function trackCard(t) { function playlistCard(p) { const tracks = p.order.map((id) => Lib.byId.get(id)).filter(Boolean); const arts = [...new Set(tracks.map((t) => t.art).filter(Boolean))].slice(0, 4); - const art = arts.length >= 4 ? h("div", { class: "tile-img tile-mosaic" }, ...arts.map((k) => cover(k, ""))) : arts.length ? cover(arts[0], "tile-img", p.name) : h("div", { class: "tile-img ph" }, icon(p.linked ? "folder" : "playlist")); + const art = p.cover ? cover(p.cover, "tile-img", p.name) : arts.length >= 4 ? h("div", { class: "tile-img tile-mosaic" }, ...arts.map((k) => cover(k, ""))) : arts.length ? cover(arts[0], "tile-img", p.name) : h("div", { class: "tile-img ph" }, icon(p.linked ? "folder" : "playlist")); return h("div", { class: "card-tile", role: "button", tabindex: "0", "data-playlist": p.name, onclick: () => openLib("playlist", p.name), onkeydown: (e) => { if (e.key === "Enter") openLib("playlist", p.name); } }, h("div", { class: "tile-art" }, art, tracks.length ? h("button", { class: "tile-play", "aria-label": `Play ${p.name}`, onclick: (e) => { e.stopPropagation(); playList(tracks); } }, icon("player-play-filled")) : null), h("div", { class: "tile-title" }, p.name), @@ -1000,6 +1084,7 @@ function albumMenu(e, a) { "-", { label: "Add to playlist", sub: playlistItems(a.tracks) }, { label: "Go to artist", run: () => openLib("artist", lnorm(a.artist)) }, + { label: `Edit ${kindWord(a)}…`, run: () => editAlbum(a) }, "-", { label: "Remove album from library", run: () => hideTracks(a.tracks) }, { label: "Delete album from device…", danger: true, run: () => deleteTracks(a.tracks) }, @@ -1017,19 +1102,6 @@ function artistMenu(e, ar) { ]); } -async function renamePlaylist(name) { - const input = h("input", { class: "text wide", value: name, "aria-label": "Playlist name" }); - const ok = await modal("Rename playlist", input, [{ label: "Cancel", value: false }, { label: "Rename", value: true, primary: true }]); - const to = input.value.trim(); - if (!ok || !to || to === name) return; - try { - const n = await invoke("playlist_rename", { from: name, to }); - if (Lib.route.name === "playlist" && Lib.route.id === name) Lib.route = { name: "playlist", id: n }; - } catch (err) { - toast(errText(err), "err"); - } -} - function playlistMenu(e, name) { const p = (Lib.data?.playlists || []).find((x) => x.name === name); if (!p) return; @@ -1047,7 +1119,7 @@ function playlistMenu(e, name) { { label: "Shuffle", disabled: !tracks.length, run: () => playList(tracks, Math.floor(Math.random() * tracks.length), true) }, "-", { label: "Add files…", run: () => invoke("playlist_add_files", { name }).catch((err) => toast(errText(err), "err")) }, - { label: "Rename in Atmosphere…", run: () => renamePlaylist(name) }, + { label: "Edit…", run: () => editPlaylist(p) }, { label: "Show in folder", run: () => invoke("reveal", { path: p.path }) }, { label: "Locate a different folder…", run: () => relocateFolder(name) }, "-", @@ -1059,7 +1131,7 @@ function playlistMenu(e, name) { { label: "Shuffle", disabled: !tracks.length, run: () => playList(tracks, Math.floor(Math.random() * tracks.length), true) }, "-", { label: "Add files…", run: () => invoke("playlist_add_files", { name }).catch((err) => toast(errText(err), "err")) }, - { label: "Rename…", run: () => renamePlaylist(name) }, + { label: "Edit…", run: () => editPlaylist(p) }, { label: "Show in folder", run: () => invoke("reveal", { path: p.path }) }, "-", { label: "Delete playlist…", danger: true, run: async () => { if (await confirmBox(`Delete “${name}”?`, "The playlist folder goes to your Recycle Bin or Trash. Songs in your library aren't touched.", "Delete")) invoke("playlist_delete", { name }).catch((err) => toast(errText(err), "err")); } }, diff --git a/ui/styles.css b/ui/styles.css index e9c00b2..8c3cf54 100644 --- a/ui/styles.css +++ b/ui/styles.css @@ -1108,3 +1108,11 @@ body.mini-mode > *:not(#mini):not(.toasts):not(.modal-wrap):not(script) { displa .qs-sub { font-size: 12px; color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .qs-keys { font-size: 11px; color: var(--text-3); opacity: 0; white-space: nowrap; } .qs-item.sel .qs-keys { opacity: 1; } + +/* edit dialogs */ +.edit-cover-row { display: grid; grid-template-columns: 112px minmax(0, 1fr); gap: var(--s4); align-items: center; } +.edit-cover { width: 112px; height: 112px; border-radius: 10px; overflow: hidden; background: var(--surface-2, var(--surface)); border: 1px solid var(--hairline); } +.edit-cover img { width: 100%; height: 100%; object-fit: cover; display: block; } +.edit-cover-ph { width: 100%; height: 100%; display: grid; place-items: center; color: var(--text-3); } +.edit-cover-ph .i svg { width: 32px; height: 32px; } +.fields input::placeholder { color: var(--text-3); font-size: 12px; }