diff --git a/crates/Cargo.lock b/crates/Cargo.lock index 090024269..8c06d552f 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -1331,18 +1331,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-text" -version = "20.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9d2790b5c08465d49f8dc05c8bcae9fea467855947db39b0f8145c091aaced5" -dependencies = [ - "core-foundation 0.9.4", - "core-graphics 0.23.2", - "foreign-types 0.5.0", - "libc", -] - [[package]] name = "core_maths" version = "0.1.1" @@ -1817,18 +1805,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" -[[package]] -name = "dwrote" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02" -dependencies = [ - "lazy_static", - "libc", - "winapi", - "wio", -] - [[package]] name = "ebur128" version = "0.1.10" @@ -2105,12 +2081,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "float-ord" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" - [[package]] name = "flume" version = "0.11.1" @@ -2140,31 +2110,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "font-kit" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c7e611d49285d4c4b2e1727b72cf05353558885cc5252f93707b845dfcaf3d3" -dependencies = [ - "bitflags 2.11.0", - "byteorder", - "core-foundation 0.9.4", - "core-graphics 0.23.2", - "core-text", - "dirs 6.0.0", - "dwrote", - "float-ord", - "freetype-sys", - "lazy_static", - "libc", - "log", - "pathfinder_geometry", - "pathfinder_simd", - "walkdir", - "winapi", - "yeslogic-fontconfig-sys", -] - [[package]] name = "font-types" version = "0.11.3" @@ -2259,17 +2204,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "freetype-sys" -version = "0.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" -dependencies = [ - "cc", - "libc", - "pkg-config", -] - [[package]] name = "fs_extra" version = "1.3.0" @@ -4209,32 +4143,6 @@ dependencies = [ "windows-sys 0.60.2", ] -[[package]] -name = "mupdf" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a60c91abaf541e5291ca470efcb7d80d0ad834dcca7fa8f8576aa789a9813b1" -dependencies = [ - "bitflags 2.11.0", - "font-kit", - "mupdf-sys", - "once_cell", - "zerocopy", -] - -[[package]] -name = "mupdf-sys" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "182cb40642a37e5980a03285664c2c100f5dbde781165c137fd49ff9c06fd5c5" -dependencies = [ - "bindgen", - "cc", - "pkg-config", - "regex", - "zerocopy", -] - [[package]] name = "naga" version = "28.0.0" @@ -5104,25 +5012,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" -[[package]] -name = "pathfinder_geometry" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b7e7b4ea703700ce73ebf128e1450eb69c3a8329199ffbfb9b2a0418e5ad3" -dependencies = [ - "log", - "pathfinder_simd", -] - -[[package]] -name = "pathfinder_simd" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4500030c302e4af1d423f36f3b958d1aecb6c04184356ed5a833bf6b60435777" -dependencies = [ - "rustc_version", -] - [[package]] name = "percent-encoding" version = "2.3.2" @@ -5526,7 +5415,6 @@ dependencies = [ "open", "qbz-app", "qbz-audio", - "qbz-booklet", "qbz-cache", "qbz-cast", "qbz-core", @@ -5614,14 +5502,6 @@ dependencies = [ "zbus 4.4.0", ] -[[package]] -name = "qbz-booklet" -version = "0.1.0" -dependencies = [ - "log", - "mupdf", -] - [[package]] name = "qbz-cache" version = "0.1.0" @@ -9627,15 +9507,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "wio" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" -dependencies = [ - "winapi", -] - [[package]] name = "wit-bindgen" version = "0.51.0" diff --git a/crates/Cargo.toml b/crates/Cargo.toml index a4346bd42..3b79da70b 100644 --- a/crates/Cargo.toml +++ b/crates/Cargo.toml @@ -32,7 +32,6 @@ members = [ "qbz-mixtape", "qbz-playlist-import", "qbz-lyrics", - "qbz-booklet", "qbz-i18n", "qbz-music-link", ] diff --git a/crates/qbz-booklet/Cargo.toml b/crates/qbz-booklet/Cargo.toml deleted file mode 100644 index 05089a2b9..000000000 --- a/crates/qbz-booklet/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "qbz-booklet" -version = "0.1.0" -edition = "2021" -description = "Album booklet (PDF) rasterization for QBZ — MuPDF page render to PNG (headless, frontend-agnostic)" -authors = ["blitzkriegfc"] - -[dependencies] -log = { workspace = true } - -# PDF rendering with MuPDF engine (high-quality rasterization for the booklet -# viewer). This stanza is a VERBATIM port of src-tauri/Cargo.toml — the Tauri -# booklet viewer was the proven, working build, and there were cross-distro -# rendering/build issues that the feature flags below fix. Do NOT "simplify". -# -# NOTE: On Linux, use sys-lib-* for zlib/harfbuzz/freetype to avoid symbol -# conflicts with GTK/GdkPixbuf. But NOT libjpeg — Ubuntu ships libjpeg8 while -# Debian/Fedora ship libjpeg62-turbo. Let mupdf vendor its own libjpeg to avoid -# cross-distro breakage (GitHub #161, #162). -# On macOS, let mupdf vendor everything (no GTK conflicts, and system libs -# don't support x86_64 cross-compilation from Apple Silicon). -mupdf = { version = "0.6", default-features = false, features = ["system-fonts"] } - -[target.'cfg(target_os = "linux")'.dependencies] -mupdf = { version = "0.6", features = ["sys-lib-zlib", "sys-lib-harfbuzz", "sys-lib-freetype"] } diff --git a/crates/qbz-booklet/src/lib.rs b/crates/qbz-booklet/src/lib.rs deleted file mode 100644 index 362bb0655..000000000 --- a/crates/qbz-booklet/src/lib.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! Album booklet (PDF) rasterization. -//! -//! Frontend-agnostic MuPDF wrapper: open a downloaded booklet PDF, read its -//! page count + per-page sizes, and rasterize a single page to PNG bytes at a -//! given DPI/rotation. The caller owns the download + temp-file lifecycle and -//! runs these (blocking) calls off the UI thread. -//! -//! This is a faithful port of the Tauri `src-tauri/src/pdf_viewer.rs` render -//! path — the working, shipped booklet viewer. The render call deliberately -//! uses `device_rgb()` with `alpha = false` so transparent regions in the PDF -//! composite over an opaque white background instead of rendering black (the -//! rendering bug the Tauri build had to work around). - -use std::io::Cursor; -use std::path::Path; - -use mupdf::{Colorspace, Document, Matrix}; - -/// Page size in points (1/72 inch), as MuPDF reports it. -#[derive(Debug, Clone)] -pub struct PageSize { - pub width: f32, - pub height: f32, -} - -/// Metadata returned when a booklet PDF is opened. -#[derive(Debug, Clone)] -pub struct BookletInfo { - pub num_pages: u32, - pub page_sizes: Vec, -} - -/// A single rasterized page, PNG-encoded by MuPDF's own writer. -#[derive(Debug, Clone)] -pub struct RenderedPage { - /// PNG image bytes (decode with the `image` crate on the caller side). - pub png: Vec, - /// Pixel dimensions of the rendered image. - pub width: u32, - pub height: u32, -} - -/// Open a booklet PDF and read its page count + per-page sizes. -/// -/// Blocking (MuPDF). Run on a worker thread. -pub fn open_info(path: &Path) -> Result { - // Owned String so `&path_str` is `&String` (AsRef), matching the - // proven Tauri call — `&Cow` does NOT implement AsRef. - let path_str = path.to_string_lossy().to_string(); - let document = - Document::open(&path_str).map_err(|e| format!("Failed to open PDF: {e:?}"))?; - - let num_pages = document - .page_count() - .map_err(|e| format!("Failed to get page count: {e:?}"))? as u32; - - let mut page_sizes = Vec::with_capacity(num_pages as usize); - for i in 0..num_pages { - match document.load_page(i as i32) { - Ok(page) => { - let bounds = page - .bounds() - .map_err(|e| format!("Failed to get page bounds: {e:?}"))?; - page_sizes.push(PageSize { - width: bounds.width(), - height: bounds.height(), - }); - } - Err(e) => { - // Fall back to US Letter so a single bad page doesn't sink the - // whole booklet (mirrors the Tauri behaviour). - log::warn!("[qbz-booklet] failed to load page {i}: {e:?}"); - page_sizes.push(PageSize { - width: 612.0, - height: 792.0, - }); - } - } - } - - Ok(BookletInfo { - num_pages, - page_sizes, - }) -} - -/// Rasterize a single 1-based page to PNG bytes. -/// -/// `dpi` is clamped to 36..=600 (0.5x..8.33x). `rotation` is degrees (0/90/ -/// 180/270; other values are applied verbatim but only the cardinal rotations -/// get the translate correction that keeps the page in frame). The document is -/// re-opened per call so no non-`Send` MuPDF handle ever crosses threads — -/// exactly how the Tauri viewer does it. -/// -/// Blocking (MuPDF). Run on a worker thread. -pub fn render_page_png( - path: &Path, - page: u32, - dpi: u32, - rotation: u32, -) -> Result { - // Owned String so `&path_str` is `&String` (AsRef), matching the - // proven Tauri call — `&Cow` does NOT implement AsRef. - let path_str = path.to_string_lossy().to_string(); - let dpi = dpi.clamp(36, 600); - - let document = - Document::open(&path_str).map_err(|e| format!("Failed to open PDF: {e:?}"))?; - - let page_index = page.saturating_sub(1) as i32; - let pdf_page = document - .load_page(page_index) - .map_err(|e| format!("Failed to load page {page}: {e:?}"))?; - - let scale = dpi as f32 / 72.0; - - let matrix = if rotation % 360 == 0 { - Matrix::new_scale(scale, scale) - } else { - let bounds = pdf_page - .bounds() - .map_err(|e| format!("Failed to get bounds: {e:?}"))?; - let w = bounds.width() * scale; - let h = bounds.height() * scale; - - let mut m = Matrix::new_scale(scale, scale); - m.concat(Matrix::new_rotate(rotation as f32)); - match rotation % 360 { - 90 => { - m.concat(Matrix::new_translate(h, 0.0)); - } - 180 => { - m.concat(Matrix::new_translate(w, h)); - } - 270 => { - m.concat(Matrix::new_translate(0.0, w)); - } - _ => {} - }; - m - }; - - // device_rgb + alpha=false => opaque white background (the rendering - // workaround: with alpha, transparent PDF regions rasterize black). - let pixmap = pdf_page - .to_pixmap(&matrix, &Colorspace::device_rgb(), false, true) - .map_err(|e| format!("Failed to render page: {e:?}"))?; - - let width = pixmap.width() as u32; - let height = pixmap.height() as u32; - - let mut png = Vec::new(); - let mut cursor = Cursor::new(&mut png); - pixmap - .write_to(&mut cursor, mupdf::ImageFormat::PNG) - .map_err(|e| format!("Failed to encode PNG: {e:?}"))?; - - Ok(RenderedPage { png, width, height }) -} diff --git a/crates/qbz/Cargo.toml b/crates/qbz/Cargo.toml index 53473184b..9059e9e36 100644 --- a/crates/qbz/Cargo.toml +++ b/crates/qbz/Cargo.toml @@ -83,7 +83,6 @@ qbz-mixtape = { path = "../qbz-mixtape" } qbz-playlist-import = { path = "../qbz-playlist-import" } qbz-qobuz = { path = "../qbz-qobuz" } qbz-lyrics = { path = "../qbz-lyrics" } -qbz-booklet = { path = "../qbz-booklet" } # Karaoke highlight per-visual-line measurement (lyrics_measure.rs): swash is # the SAME shaper femtovg uses to raster glyphs, so an advance pass at the same # font + ppem + wght axis + letter-spacing matches the rendered wrap. Already in diff --git a/crates/qbz/src/booklet.rs b/crates/qbz/src/booklet.rs index 39c06dd12..d35000488 100644 --- a/crates/qbz/src/booklet.rs +++ b/crates/qbz/src/booklet.rs @@ -1,382 +1,55 @@ -//! Album booklet (digital liner-notes PDF) reader controller. +//! Album booklet download. //! -//! 1:1 port of Tauri's BookletViewer.svelte + `src-tauri/src/pdf_viewer.rs` -//! flow, split across the frontend-agnostic `qbz-booklet` crate (the MuPDF -//! rasterizer, ADR-006) and this thin UI-thread glue: +//! Booklets (digital liner-notes PDFs) are an occasional Qobuz "goody" — not +//! every album has one. We no longer render them in-app: the in-app MuPDF reader +//! was heavy (~20 MB of static MuPDF linked into the binary, plus a slow C build) +//! and clumsy to read. Instead the album-header booklet button downloads the PDF +//! to a user-chosen location for their own viewer. The fetch uses the app's HTTP +//! client, so it works whether the goody URL is public or session-scoped. //! -//! 1. The album controller stashes the booklet goody URL via -//! [`set_current_url`] when an album loads. -//! 2. [`open`] downloads that PDF to a temp file, reads its page count, and -//! rasterizes page 1, pushing the decoded image into `BookletState`. -//! 3. Navigation / zoom / rotate re-rasterize the current page off the UI -//! thread; [`download`] copies the temp PDF to a user-chosen location; -//! [`close`] removes the temp file and clears state. -//! -//! All network + MuPDF work runs on the tokio runtime / `spawn_blocking`; only -//! the `slint::Image` build + state writes touch the event loop. The reader's -//! mutable state lives in a `thread_local` touched exclusively on the Slint -//! event loop — every worker-thread result is funnelled back through -//! `upgrade_in_event_loop` before it reads/writes that state. +//! The `AlbumBookletModal.slint` reader UI + the `BookletState`/`BookletActions` +//! globals are now unused (left in place; remove in a UI cleanup pass that +//! recompiles qbz-ui). use std::cell::RefCell; -use std::path::{Path, PathBuf}; use std::time::Duration; use slint::ComponentHandle; -use crate::{AppWindow, BookletState}; +use crate::AppWindow; -/// Baseline render DPI at zoom 1.0. The qbz-booklet crate clamps to 36..=600, -/// so the zoom range (0.5..4.0) maps to 75..600 DPI. -const BASE_DPI: f32 = 150.0; -/// PDF download timeout, matching the Tauri viewer's client. +/// PDF download timeout (matches the former in-app reader's client). const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(30); -/// UI-thread reader state. `thread_local` because every field is only ever -/// touched on the Slint event loop (the goody URL is stashed there by -/// `album::apply_album`, and every render is kicked from a callback that hops -/// back to the event loop before reading it). -struct Reader { - /// The booklet goody URL of the open album ("" = no booklet). - url: String, - /// The downloaded temp PDF, once `open` has fetched it. - path: Option, - num_pages: u32, - /// 1-based current page. - current_page: u32, - zoom: f32, - /// Cumulative rotation in degrees (0/90/180/270). - rotation: u32, -} - -impl Reader { - const fn new() -> Self { - Self { - url: String::new(), - path: None, - num_pages: 0, - current_page: 1, - zoom: 1.0, - rotation: 0, - } - } -} - thread_local! { - static READER: RefCell = const { RefCell::new(Reader::new()) }; + /// Booklet goody URL of the currently-open album ("" = no booklet). Stashed + /// by `album::apply_album`, cleared on album reset; only ever touched on the + /// Slint event loop. + static BOOKLET_URL: RefCell = const { RefCell::new(String::new()) }; } -/// Stash the booklet goody URL for the currently-open album. Called from -/// `album::apply_album`; cleared by `clear_current_url` on album reset. +/// Stash the booklet goody URL for the currently-open album. pub fn set_current_url(url: &str) { - READER.with(|cell| cell.borrow_mut().url = url.to_string()); + BOOKLET_URL.with(|cell| *cell.borrow_mut() = url.to_string()); } -/// Clear the stashed booklet URL (album reset). Does NOT remove a downloaded -/// temp file — that is `close`'s job once the reader is actually opened. +/// Clear the stashed booklet URL (album reset). pub fn clear_current_url() { - READER.with(|cell| cell.borrow_mut().url.clear()); + BOOKLET_URL.with(|cell| cell.borrow_mut().clear()); } -/// DPI for the current zoom, pre-clamp (qbz-booklet re-clamps to 36..=600). -fn dpi_for(zoom: f32) -> u32 { - (BASE_DPI * zoom).round() as u32 -} - -/// Temp dir for downloaded booklets (mirrors Tauri's `qbz-booklets`). -fn booklet_temp_dir() -> PathBuf { - std::env::temp_dir().join("qbz-booklets") -} - -/// Open the booklet reader for the current album. No-op when no booklet URL is -/// stashed. Sets the modal open + loading, then downloads the PDF, reads its -/// page info, and renders page 1. The booklet flow is a direct PDF download -/// (no Qobuz core call), so it takes no `runtime` — unlike the other -/// media-action controllers. -pub fn open(weak: slint::Weak, handle: tokio::runtime::Handle) { - // Read the stashed URL + reset the per-open view state on the UI thread. - let url = READER.with(|cell| { - let mut r = cell.borrow_mut(); - r.current_page = 1; - r.zoom = 1.0; - r.rotation = 0; - r.path = None; - r.num_pages = 0; - r.url.clone() - }); +/// Download the current album's booklet PDF to a user-chosen location. No-op +/// when no booklet URL is stashed. Fetches with the app's HTTP client, then +/// opens a native save dialog seeded with the album title. +pub fn download_booklet(weak: slint::Weak, handle: tokio::runtime::Handle) { + let url = BOOKLET_URL.with(|cell| cell.borrow().clone()); if url.is_empty() { return; } - - let _ = weak.upgrade_in_event_loop(|w| { - // Header title = the open album's title (the modal binds - // BookletState.title; nothing in the .slint sets it). - let title = w.global::().get_title(); - let st = w.global::(); - st.set_title(title); - st.set_error(false); - st.set_error_text("".into()); - st.set_loading(true); - st.set_current_page(1); - st.set_num_pages(0); - st.set_zoom(1.0); - st.set_rotation(0); - st.set_open(true); - }); - - let render_handle = handle.clone(); - handle.spawn(async move { - match download_and_open(&url).await { - Ok((path, num_pages)) => { - // Hop back to the UI thread to record the path + page count, - // then kick the first render (which itself hops off-thread to - // rasterize, then back to paint). - let render_handle = render_handle.clone(); - let _ = weak.upgrade_in_event_loop(move |w| { - READER.with(|cell| { - let mut r = cell.borrow_mut(); - r.path = Some(path); - r.num_pages = num_pages; - }); - w.global::().set_num_pages(num_pages as i32); - render_current(w.as_weak(), render_handle); - }); - } - Err(e) => { - log::warn!("[qbz-slint] booklet open failed: {e}"); - let _ = weak.upgrade_in_event_loop(move |w| { - let st = w.global::(); - st.set_loading(false); - st.set_error(true); - st.set_error_text(e.into()); - }); - } - } - }); -} - -/// Download the PDF at `url` to a fresh temp file, then read its page count. -/// Returns the temp path + page count. Blocking MuPDF work is on -/// `spawn_blocking`. Errors are user-facing strings (shown in the modal). -async fn download_and_open(url: &str) -> Result<(PathBuf, u32), String> { - let client = reqwest::Client::builder() - .timeout(DOWNLOAD_TIMEOUT) - .build() - .map_err(|e| format!("HTTP client error: {e}"))?; - let response = client - .get(url) - .send() - .await - .map_err(|e| qbz_i18n::t_args("Failed to fetch booklet: {}", &[&e.to_string()]))?; - if !response.status().is_success() { - return Err(format!("HTTP {}", response.status())); - } - let bytes = response - .bytes() - .await - .map_err(|e| qbz_i18n::t_args("Failed to read booklet: {}", &[&e.to_string()]))?; - - let temp_dir = booklet_temp_dir(); - tokio::fs::create_dir_all(&temp_dir) - .await - .map_err(|e| qbz_i18n::t_args("Failed to create temp dir: {}", &[&e.to_string()]))?; - let path = temp_dir.join(format!("{}.pdf", uuid::Uuid::new_v4())); - tokio::fs::write(&path, &bytes) - .await - .map_err(|e| qbz_i18n::t_args("Failed to write booklet: {}", &[&e.to_string()]))?; - - let info_path = path.clone(); - let info = tokio::task::spawn_blocking(move || qbz_booklet::open_info(&info_path)) - .await - .map_err(|e| qbz_i18n::t_args("Booklet open task failed: {}", &[&e.to_string()]))??; - Ok((path, info.num_pages)) -} - -/// Rasterize the current page (off-thread) and paint it into `BookletState`. -/// Reads the page/zoom/rotation snapshot from `READER` on the UI thread, sets -/// `loading`, then hops off to MuPDF and back. No-op when no PDF is open. -fn render_current(weak: slint::Weak, handle: tokio::runtime::Handle) { - let Some((path, page, dpi, rotation, num_pages, zoom, rot)) = READER.with(|cell| { - let r = cell.borrow(); - let path = r.path.clone()?; - Some(( - path, - r.current_page, - dpi_for(r.zoom), - r.rotation, - r.num_pages, - r.zoom, - r.rotation, - )) - }) else { - return; - }; - - // Reflect the snapshot the render is for, and show the spinner. - if let Some(w) = weak.upgrade() { - let st = w.global::(); - st.set_loading(true); - st.set_current_page(page as i32); - st.set_num_pages(num_pages as i32); - st.set_zoom(zoom); - st.set_rotation(rot as i32); - } - - handle.spawn(async move { - let result = tokio::task::spawn_blocking(move || { - render_page_rgba(&path, page, dpi, rotation) - }) - .await; - match result { - Ok(Ok((pixels, width, height))) => { - let _ = weak.upgrade_in_event_loop(move |w| { - let image = crate::artwork::pixels_to_image(&pixels, width, height); - let st = w.global::(); - st.set_page_image(image); - st.set_page_pixel_width(width as i32); - st.set_page_pixel_height(height as i32); - st.set_loading(false); - st.set_error(false); - }); - } - Ok(Err(e)) => { - log::warn!("[qbz-slint] booklet render failed: {e}"); - let _ = weak.upgrade_in_event_loop(move |w| { - let st = w.global::(); - st.set_loading(false); - st.set_error(true); - st.set_error_text(e.into()); - }); - } - Err(e) => { - log::warn!("[qbz-slint] booklet render task failed: {e}"); - let _ = weak.upgrade_in_event_loop(|w| { - w.global::().set_loading(false); - }); - } - } - }); -} - -/// Rasterize one page to RGBA8 pixels. Blocking (MuPDF + PNG decode); call from -/// `spawn_blocking`. The qbz-booklet crate emits PNG bytes, decoded here with -/// the `image` crate (mirrors `album::apply_artwork`'s RGBA path). -fn render_page_rgba( - path: &Path, - page: u32, - dpi: u32, - rotation: u32, -) -> Result<(Vec, u32, u32), String> { - let rendered = qbz_booklet::render_page_png(path, page, dpi, rotation)?; - let rgba = image::load_from_memory(&rendered.png) - .map_err(|e| qbz_i18n::t_args("Failed to decode booklet page: {}", &[&e.to_string()]))? - .to_rgba8(); - let (width, height) = rgba.dimensions(); - Ok((rgba.into_raw(), width, height)) -} - -/// Advance to the next page (clamped to `num_pages`) and re-render. -pub fn next_page(weak: slint::Weak, handle: tokio::runtime::Handle) { - let changed = READER.with(|cell| { - let mut r = cell.borrow_mut(); - if r.num_pages > 0 && r.current_page < r.num_pages { - r.current_page += 1; - true - } else { - false - } - }); - if changed { - render_current(weak, handle); - } -} - -/// Step back to the previous page (clamped to 1) and re-render. -pub fn prev_page(weak: slint::Weak, handle: tokio::runtime::Handle) { - let changed = READER.with(|cell| { - let mut r = cell.borrow_mut(); - if r.current_page > 1 { - r.current_page -= 1; - true - } else { - false - } - }); - if changed { - render_current(weak, handle); - } -} - -/// Zoom in (x1.25, capped at 4.0) and re-render at the higher DPI. -pub fn zoom_in(weak: slint::Weak, handle: tokio::runtime::Handle) { - let changed = READER.with(|cell| { - let mut r = cell.borrow_mut(); - let next = (r.zoom * 1.25).min(4.0); - if (next - r.zoom).abs() > f32::EPSILON { - r.zoom = next; - true - } else { - false - } - }); - if changed { - render_current(weak, handle); - } -} - -/// Zoom out (/1.25, floored at 0.5) and re-render at the lower DPI. -pub fn zoom_out(weak: slint::Weak, handle: tokio::runtime::Handle) { - let changed = READER.with(|cell| { - let mut r = cell.borrow_mut(); - let next = (r.zoom / 1.25).max(0.5); - if (next - r.zoom).abs() > f32::EPSILON { - r.zoom = next; - true - } else { - false - } - }); - if changed { - render_current(weak, handle); - } -} - -/// Reset zoom to the fit-width baseline (1.0) and re-render. -pub fn fit_width(weak: slint::Weak, handle: tokio::runtime::Handle) { - let changed = READER.with(|cell| { - let mut r = cell.borrow_mut(); - if (r.zoom - 1.0).abs() > f32::EPSILON { - r.zoom = 1.0; - true - } else { - false - } - }); - if changed { - render_current(weak, handle); - } -} - -/// Rotate the page by 90° (cumulative, mod 360) and re-render. -pub fn rotate(weak: slint::Weak, handle: tokio::runtime::Handle) { - READER.with(|cell| { - let mut r = cell.borrow_mut(); - r.rotation = (r.rotation + 90) % 360; - }); - render_current(weak, handle); -} - -/// Save the open booklet PDF to a user-chosen location (best-effort). Opens a -/// native save dialog seeded with the album title, then copies the temp file. -pub fn download(weak: slint::Weak, handle: tokio::runtime::Handle) { - let path = READER.with(|cell| cell.borrow().path.clone()); - let Some(path) = path else { - return; - }; let default_name = weak .upgrade() .map(|w| { - let title = w.global::().get_title().to_string(); + let title = w.global::().get_title().to_string(); if title.is_empty() { "booklet.pdf".to_string() } else { @@ -386,6 +59,29 @@ pub fn download(weak: slint::Weak, handle: tokio::runtime::Handle) { .unwrap_or_else(|| "booklet.pdf".to_string()); handle.spawn(async move { + let client = match reqwest::Client::builder().timeout(DOWNLOAD_TIMEOUT).build() { + Ok(c) => c, + Err(e) => { + log::warn!("[qbz-slint] booklet HTTP client error: {e}"); + return; + } + }; + let resp = match client.get(&url).send().await.and_then(|r| r.error_for_status()) { + Ok(r) => r, + Err(e) => { + log::warn!("[qbz-slint] booklet fetch failed: {e}"); + return; + } + }; + let bytes = match resp.bytes().await { + Ok(b) => b, + Err(e) => { + log::warn!("[qbz-slint] booklet read failed: {e}"); + return; + } + }; + + // Native "save as" dialog seeded with the album title; cancel = no-op. let Some(dest) = rfd::AsyncFileDialog::new() .set_file_name(&default_name) .add_filter("PDF", &["pdf"]) @@ -394,36 +90,8 @@ pub fn download(weak: slint::Weak, handle: tokio::runtime::Handle) { else { return; }; - if let Err(e) = tokio::fs::copy(&path, dest.path()).await { - log::warn!("[qbz-slint] booklet download copy failed: {e}"); + if let Err(e) = tokio::fs::write(dest.path(), &bytes).await { + log::warn!("[qbz-slint] booklet save failed: {e}"); } }); } - -/// Close the reader: hide the modal, remove the temp PDF (best-effort), and -/// clear the per-open view state. Runs on the UI thread (the callback site). -pub fn close(window: &AppWindow) { - let st = window.global::(); - st.set_open(false); - st.set_loading(false); - st.set_error(false); - st.set_error_text("".into()); - st.set_page_image(slint::Image::default()); - st.set_page_pixel_width(0); - st.set_page_pixel_height(0); - st.set_current_page(1); - st.set_num_pages(0); - st.set_zoom(1.0); - st.set_rotation(0); - - READER.with(|cell| { - let mut r = cell.borrow_mut(); - if let Some(path) = r.path.take() { - let _ = std::fs::remove_file(&path); - } - r.num_pages = 0; - r.current_page = 1; - r.zoom = 1.0; - r.rotation = 0; - }); -} diff --git a/crates/qbz/src/main.rs b/crates/qbz/src/main.rs index 70ca800da..64687bd98 100644 --- a/crates/qbz/src/main.rs +++ b/crates/qbz/src/main.rs @@ -7735,12 +7735,12 @@ fn main() -> Result<(), Box> { ); } } - // Album booklet (digital liner-notes PDF) — opened from the - // album header booklet button. Downloads + rasterizes the goody - // PDF stashed by album::apply_album; the BookletState gate keeps - // it a no-op when the album bundles no booklet. + // Album booklet (digital liner-notes PDF) — the album-header + // booklet button DOWNLOADS the goody PDF (stashed by + // album::apply_album) to a user-chosen location. No-op when the + // album bundles no booklet (empty stashed URL). ("album", "booklet") => { - crate::booklet::open(weak.clone(), handle.clone()); + crate::booklet::download_booklet(weak.clone(), handle.clone()); } // "From the same artist" carousel "View all" — open the artist's // full Albums discography page. `id` is the artist id; reuse the @@ -10036,67 +10036,10 @@ fn main() -> Result<(), Box> { } }); - // Booklet reader controls (BookletActions) — paging / zoom / rotate - // re-rasterize the current page off-thread; close removes the temp PDF. - { - let weak = window.as_weak(); - window - .global::() - .on_close(move || { - if let Some(w) = weak.upgrade() { - crate::booklet::close(&w); - } - }); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_next_page(move || crate::booklet::next_page(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_prev_page(move || crate::booklet::prev_page(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_zoom_in(move || crate::booklet::zoom_in(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_zoom_out(move || crate::booklet::zoom_out(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_fit_width(move || crate::booklet::fit_width(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_rotate(move || crate::booklet::rotate(weak.clone(), handle.clone())); - } - { - let weak = window.as_weak(); - let handle = tokio_rt.handle().clone(); - window - .global::() - .on_download(move || crate::booklet::download(weak.clone(), handle.clone())); - } + // Booklet reader removed — the album booklet button now downloads the PDF + // (booklet::download_booklet via the ("album","booklet") media action). The + // BookletActions/BookletState globals + AlbumBookletModal.slint are unused + // now (left in place; remove in a UI cleanup pass that recompiles qbz-ui). // Artist in-page search — client-side filter over Popular Tracks // and every release-section album.