From 95df9ebc4a1567d6f6f738e8ad4602af87b91b67 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 14 Nov 2026 14:31:43 +0000 Subject: [PATCH 1/7] Open: read and parse documents off the UI thread --- apps/designcraft/src/main.rs | 1 + crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/file.rs | 2 + crates/engine/src/cmd/file/open.rs | 180 +++++++++++++++++++++------ crates/engine/src/cmd/interchange.rs | 40 +++--- crates/engine/src/lib.rs | 13 ++ crates/ui-egui/src/app.rs | 4 + crates/ui-egui/src/app/files.rs | 23 +++- crates/ui-egui/src/app/frame.rs | 2 + crates/ui-egui/src/app/opening.rs | 121 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus/run.rs | 16 ++- crates/ui-egui/src/services.rs | 4 + 13 files changed, 351 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/app/opening.rs diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 5f465e46d..82d1808f5 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -233,6 +233,7 @@ fn services() -> Services { clipboard_change: Some(Box::new(clipboard_image::change_count)), #[cfg(target_os = "macos")] pointer: Some(Box::new(pointer::screen_position)), + open_in_background: true, ..Default::default() } } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 803814d7e..8187594ab 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -390,6 +390,8 @@ pub(crate) use file::load_document_fonts; pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; +#[cfg(not(target_arch = "wasm32"))] +pub use file::{ReadDocument, read_document}; pub use layout::chapter_numbering; pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b8429f860..b55b7f5a2 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -20,6 +20,8 @@ mod snippets; pub use bytes::{DOCUMENT_SNIFF_BYTES, base64_decode, base64_encode, from_bytes, is_document, to_bytes, with_document_extension}; pub(crate) use open::load_document_fonts; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{ReadDocument, read_document}; pub use open::{RecentPreview, recent_preview}; pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement}; pub use registry::specs; diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index a2f5c709c..6bafdd701 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -70,47 +70,14 @@ pub(super) fn file_open_recent(s: &mut Session, p: &Value) -> Result { /// `file.open`: the document opens and moves to the front of File › Open Recent. pub(super) fn file_open(s: &mut Session, p: &Value) -> Result { - let r = open_path(s, p)?; - if let Some(path) = str_param(p, "path") { - s.prefs.note_recent_file(path); - } - Ok(r) -} - -fn open_path(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?; #[cfg(not(target_arch = "wasm32"))] { - let bytes = crate::io::read_file(path).map_err(EngineError::Other)?; - // The content decides first: a file's extension may be missing or wrong. The extension - // then routes files whose content isn't recognised to the reader that explains why. - let format = craft_file_formats::detect(path, &bytes); - let native = matches!( - craft_file_formats::detect("", &bytes), - Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson) - ); - let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&bytes).ok()).flatten(); - if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) { - return crate::cmd::interchange::open_idml(s, p); - } - if !native && legacy.is_none() { - return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file"))); - } - let (mut d, mut warnings) = match legacy { - Some(loaded) => loaded, - None => load_bytes(&bytes)?, + let read = match s.staged_open.take().filter(|r| r.path == path) { + Some(read) => read, + None => read_document(path, &std::sync::atomic::AtomicBool::new(false))?, }; - crate::cmd::interchange::resolve_packaged_links(&mut d, Some(std::path::Path::new(path))); - crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path))); - let links = crate::cmd::native_links::resolve(&mut d, Some(std::path::Path::new(path)), true); - let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path); - warnings.extend(font_warnings); - warnings.extend(crate::cmd::style::grep_style_warnings(&d)); - let mut st = DocState::new(d, Some(path.to_string())); - st.fonts = fonts; - let checks = crate::cmd::native_links::start(&mut st, links); - let i = s.add_document(st); - Ok(json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks})) + install_document(s, read) } #[cfg(target_arch = "wasm32")] { @@ -119,6 +86,94 @@ fn open_path(s: &mut Session, p: &Value) -> Result { } } +/// A document file read and parsed by [`read_document`], which needs no session and may run on +/// any thread. `file.open` reads its file this way and then opens what it read; one read ahead +/// of time is handed to it with [`Session::stage_open`]. +#[cfg(not(target_arch = "wasm32"))] +pub struct ReadDocument { + path: String, + content: ReadContent, +} + +#[cfg(not(target_arch = "wasm32"))] +enum ReadContent { + /// A DesignCraft document (or one with an InDesign extension), its repair warnings, and the + /// links found for the background check. + Native { doc: Box, warnings: Vec, links: crate::cmd::native_links::Opened }, + /// An IDML or InDesign file's bytes, imported when installed. + Interchange(Vec), +} + +#[cfg(not(target_arch = "wasm32"))] +impl ReadDocument { + /// The file the document was read from. + pub fn path(&self) -> &str { + &self.path + } +} + +/// Read and parse the document file at `path` for `file.open`: the slow part of +/// `file.open` (reading, unzipping and decoding the document, finding its linked files). The +/// file roots in force on the calling thread apply. When `cancel` is set between steps it stops +/// with an error. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_document(path: &str, cancel: &std::sync::atomic::AtomicBool) -> Result { + let cancelled = || cancel.load(std::sync::atomic::Ordering::Relaxed).then(|| EngineError::Other(format!("{path}: opening cancelled"))); + let bytes = crate::io::read_file(path).map_err(EngineError::Other)?; + if let Some(e) = cancelled() { + return Err(e); + } + // The content decides first: a file's extension may be missing or wrong. The extension + // then routes files whose content isn't recognised to the reader that explains why. + let format = craft_file_formats::detect(path, &bytes); + let native = + matches!(craft_file_formats::detect("", &bytes), Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::DesignCraftJson)); + let legacy = (format == Some(craft_file_formats::Format::Indd) && !native).then(|| load_bytes(&bytes).ok()).flatten(); + if format == Some(craft_file_formats::Format::Idml) || (!native && format == Some(craft_file_formats::Format::Indd) && legacy.is_none()) { + return Ok(ReadDocument { path: path.to_string(), content: ReadContent::Interchange(bytes) }); + } + if !native && legacy.is_none() { + return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file"))); + } + let (mut d, warnings) = match legacy { + Some(loaded) => loaded, + None => load_bytes(&bytes)?, + }; + drop(bytes); + if let Some(e) = cancelled() { + return Err(e); + } + let file = std::path::Path::new(path); + crate::cmd::interchange::resolve_packaged_links(&mut d, Some(file)); + crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(file)); + let links = crate::cmd::native_links::resolve(&mut d, Some(file), true); + Ok(ReadDocument { path: path.to_string(), content: ReadContent::Native { doc: Box::new(d), warnings, links } }) +} + +/// Open the document [`read_document`] read as the active document, with its fonts and the +/// background check of its linked files, and move its file to the front of File › Open Recent. +/// → what `file.open` answers. +#[cfg(not(target_arch = "wasm32"))] +fn install_document(s: &mut Session, read: ReadDocument) -> Result { + let ReadDocument { path, content } = read; + let r = match content { + ReadContent::Interchange(bytes) => crate::cmd::interchange::open_idml_file(s, bytes, &path)?, + ReadContent::Native { doc, mut warnings, links } => { + let mut d = *doc; + let (fonts, faces, font_warnings) = load_document_fonts(&mut d, &path); + warnings.extend(font_warnings); + warnings.extend(crate::cmd::style::grep_style_warnings(&d)); + let mut st = DocState::new(d, Some(path.clone())); + st.fonts = fonts; + let checks = crate::cmd::native_links::start(&mut st, links); + let i = s.add_document(st); + json!({"index": i, "documentFonts": faces, "warnings": warnings, "linkChecks": checks}) + } + }; + s.prefs.note_recent_file(&path); + Ok(r) +} + /// Load the fonts in the `Document Fonts` folder beside the document file at `path` for `d` alone /// (`d.font_scope`) → (the scope, for the document's state to hold; faces; a warning for each /// font file skipped). Nothing on the web (no folders). @@ -699,3 +754,54 @@ mod recent_tests { assert!(old.recent_files.is_empty(), "older prefs.json without the list still load"); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod read_install_tests { + use std::sync::atomic::AtomicBool; + + use serde_json::json; + + use super::read_document; + use crate::Session; + + /// A document read on another thread and staged for `file.open` (what a background open + /// does) gives the document, answer and recent files that `file.open` reading the file gives, + /// without reading the file again. + #[test] + fn a_document_read_on_another_thread_opens_as_file_open_opens_it() { + let dir = std::env::temp_dir().join(format!("dc-read-install-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let image = dir.join("photo.png"); + std::fs::write(&image, designcraft_render::Rendered { width: 40, height: 20, pixels: [200, 90, 30, 255].repeat(800) }.to_png()).unwrap(); + let path = dir.join("Brochure.designcraft").to_string_lossy().to_string(); + let mut writer = Session::new(); + writer.execute("file.new", &json!({})).unwrap(); + writer.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello"})).unwrap(); + writer.execute("file.place", &json!({"path": image.to_string_lossy(), "x": 40, "y": 260})).unwrap(); + writer.execute("file.save", &json!({"path": path})).unwrap(); + + let mut by_command = Session::new(); + let opened = by_command.execute("file.open", &json!({"path": path})).unwrap(); + + let worker_path = path.clone(); + let read = std::thread::spawn(move || read_document(&worker_path, &AtomicBool::new(false))).join().unwrap().unwrap(); + assert_eq!(read.path(), path); + let saved = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + let mut staged = Session::new(); + staged.stage_open(read); + let installed = staged.execute("file.open", &json!({"path": path})).unwrap(); + + assert_eq!(installed, opened); + assert_eq!(staged.doc().unwrap().doc, by_command.doc().unwrap().doc); + assert_eq!(staged.doc().unwrap().path, by_command.doc().unwrap().path); + assert_eq!(staged.prefs.recent_files, by_command.prefs.recent_files); + assert!(staged.execute("file.open", &json!({"path": path})).is_err(), "a staged document opens once"); + + std::fs::write(&path, saved).unwrap(); + let cancelled = read_document(&path, &AtomicBool::new(true)); + assert!(cancelled.is_err_and(|e| e.to_string().contains("cancelled"))); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 940404aa9..a33a51639 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -474,20 +474,30 @@ fn read_packaged_link(link: &str, package: Option<&std::path::Path>) -> Option<( } pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { - let (bytes, package, file, title) = if let Some(b) = str_param(p, "base64") { + if let Some(b) = str_param(p, "base64") { let name = str_param(p, "name").unwrap_or_default(); - (base64_decode(b), None, name.to_string(), without_document_extension(name).to_string()) - } else if let Some(path) = str_param(p, "path") { - #[cfg(not(target_arch = "wasm32"))] - let b = crate::io::read_file(path).map_err(EngineError::Other)?; - #[cfg(target_arch = "wasm32")] - let b: Vec = Vec::new(); - let pp = std::path::Path::new(path); - let file = pp.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string()); - (b, Some(pp.to_path_buf()), file, pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()) - } else { - return Err(bad("file.openIdml", "missing `path` or `base64`")); - }; + return import_interchange(s, base64_decode(b), None, name.to_string(), without_document_extension(name).to_string()); + } + let Some(path) = str_param(p, "path") else { return Err(bad("file.openIdml", "missing `path` or `base64`")) }; + #[cfg(not(target_arch = "wasm32"))] + let b = crate::io::read_file(path).map_err(EngineError::Other)?; + #[cfg(target_arch = "wasm32")] + let b: Vec = Vec::new(); + open_idml_file(s, b, path) +} + +/// Open the IDML or InDesign file at `path`, whose content is `bytes`: titled by its file name, +/// with the fonts in the `Document Fonts` folder beside it. +pub(crate) fn open_idml_file(s: &mut Session, bytes: Vec, path: &str) -> Result { + let pp = std::path::Path::new(path); + let file = pp.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string()); + let title = pp.file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + import_interchange(s, bytes, Some(pp), file, title) +} + +/// Import IDML or InDesign `bytes` named `file` as a new document titled `title`. `package` is +/// the file they were read from, which links resolve against and whose folder's fonts load. +fn import_interchange(s: &mut Session, bytes: Vec, package: Option<&std::path::Path>, file: String, title: String) -> Result { let mut warnings = Vec::new(); // InDesign's previews of linked graphics show while their files are missing (graphic `Self` → // preview), as InDesign shows them. One preview can stand for any number of graphics: they @@ -511,12 +521,12 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result { } else { bytes }; - let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package.as_deref(), &previews)?; + let (mut d, import_warnings, story_ids) = import_report_with_previews(&bytes, package, &previews)?; warnings.extend(import_warnings); if !title.is_empty() { d.title = title; } - let (fonts, faces, font_warnings) = match str_param(p, "path").filter(|_| str_param(p, "base64").is_none()) { + let (fonts, faces, font_warnings) = match package.and_then(std::path::Path::to_str) { Some(path) => super::file::load_document_fonts(&mut d, path), None => (None, 0, Vec::new()), }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6a50bc016..59d39dc15 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -411,6 +411,9 @@ pub struct Session { /// The selection tool (`selection` or `directSelection`) chosen last: the one Cmd borrows. pub(crate) last_selection_tool: &'static str, pub journal: Vec<(String, Value)>, + /// A document read ahead of `file.open` ([`Session::stage_open`]). + #[cfg(not(target_arch = "wasm32"))] + pub(crate) staged_open: Option, pub(crate) find_context: Option, pub clipboard: Option>, /// The x the clipboard's objects are measured from on their spread: its spine, or the left edge of @@ -486,6 +489,8 @@ impl Session { temp_tool: None, last_selection_tool: "selection", journal: vec![], + #[cfg(not(target_arch = "wasm32"))] + staged_open: None, find_context: None, clipboard: None, clipboard_origin: 0.0, @@ -563,6 +568,14 @@ impl Session { } } + /// Hand `file.open` a document [`cmd::read_document`] read: the next `file.open` of its path + /// opens it instead of reading the file, so the slow read can run on another thread. Any other + /// `file.open` drops it. + #[cfg(not(target_arch = "wasm32"))] + pub fn stage_open(&mut self, read: cmd::ReadDocument) { + self.staged_open = Some(read); + } + pub fn set_active(&mut self, i: usize) { if i < self.docs.len() && self.active != Some(i) { // The composition belongs to the document it shows in. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 45c296883..e325caaa6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -19,6 +19,8 @@ mod frame; mod ime; mod input; mod keys; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod opening; mod quit; mod screenshot; mod view; @@ -130,6 +132,8 @@ impl DesignApp { quit_without_asking: false, quitting: None, waiting_save: None, + #[cfg(not(target_arch = "wasm32"))] + opening: Vec::new(), cursors: cursors::Images::default(), live_preview: LivePreview::default(), updates_rt: updates_ui::Runtime::default(), diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 09aa13f53..54e6a006f 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -32,9 +32,28 @@ impl DesignApp { if purpose == "place" { return self.place_path(&path, false); } + self.open_document(path) + } + + /// Open the document file at `path` as `file.open` does. Chosen by the person (File › Open, + /// Open Recent, a drop, the operating system), the file is read on a worker thread where the + /// host allows it ([`crate::Services::open_in_background`]) and opens on a later frame, with + /// `Ok(Null)` now. Scripts and the control channel open it at once, so their next command + /// finds it open. + pub(crate) fn open_document(&mut self, path: String) -> Result { + #[cfg(not(target_arch = "wasm32"))] + if self.opens_in_background() { + return self.open_in_background(path); + } self.open_file("file.open", json!({"path": path})) } + /// Whether [`Self::open_document`] reads the file on a worker thread. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn opens_in_background(&self) -> bool { + self.services.open_in_background && !self.in_control + } + /// File › Place of the file at `path`, asking a multi-page PDF's Image Import Options first. /// With `append`, an image that loads the cursor queues after the ones already loaded rather /// than replacing them. @@ -376,7 +395,7 @@ impl DesignApp { && designcraft_engine::io::read_capped(path, designcraft_engine::cmd::DOCUMENT_SNIFF_BYTES) .is_ok_and(|b| designcraft_engine::cmd::is_document(&b))); if document { - return self.open_file("file.open", json!({"path": path})); + return self.open_document(path.to_string()); } // A graphic dropped on a frame that takes one fills it, as File > Place does. Text keeps // getting a frame of its own, so it never replaces the image in a graphic frame. @@ -423,7 +442,7 @@ impl DesignApp { pub(crate) fn open_os_documents(&mut self) { for path in std::mem::take(&mut self.os_documents) { - if let Err(e) = self.open_file("file.open", json!({"path": path})) { + if let Err(e) = self.open_document(path.clone()) { log::warn!("{path}: {e}"); } } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 5f8960856..609eeafe7 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -34,6 +34,8 @@ impl DesignApp { self.handle_file_dialog_answers(); self.drain_inbox(); self.open_os_documents(); + #[cfg(not(target_arch = "wasm32"))] + self.poll_opening(ctx); self.poll_link_checks(ctx); } if self.host_order_pending() { diff --git a/crates/ui-egui/src/app/opening.rs b/crates/ui-egui/src/app/opening.rs new file mode 100644 index 000000000..a7efc7e3d --- /dev/null +++ b/crates/ui-egui/src/app/opening.rs @@ -0,0 +1,121 @@ +//! Opening a document file without stopping the UI: the file is read and parsed on a worker +//! thread ([`designcraft_engine::cmd::read_document`]), and `file.open` opens what it read on a +//! later frame. A large file with embedded images takes seconds to read; the status line says +//! which file is opening, and Esc stops waiting for it. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use designcraft_engine::cmd::ReadDocument; + +use super::{DesignApp, Value, json}; + +/// A document file being read on a worker thread. +pub(crate) struct Opening { + path: String, + /// The file name, for the status line and the alert. + name: String, + cancel: Arc, + read: Receiver>, +} + +impl Drop for Opening { + /// A read nobody waits for any more stops at its next step. + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +impl DesignApp { + /// Read the file at `path` on a worker thread; [`Self::poll_opening`] opens it when it is in. + /// The same file asked for again while it is read opens once. + pub(super) fn open_in_background(&mut self, path: String) -> Result { + if self.opening.iter().any(|o| o.path == path) { + return Ok(Value::Null); + } + let name = std::path::Path::new(&path).file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned()); + let cancel = Arc::new(AtomicBool::new(false)); + let (send, read) = std::sync::mpsc::channel(); + // The file roots in force here apply on the worker too. + let roots = designcraft_engine::file_access::current(); + let wake = self.egui_ctx.clone(); + let (worker_path, worker_cancel) = (path.clone(), Arc::clone(&cancel)); + let spawned = std::thread::Builder::new().name("designcraft-open".into()).spawn(move || { + let read = designcraft_engine::file_access::confine(roots.as_ref(), || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| designcraft_engine::cmd::read_document(&worker_path, &worker_cancel))) + }); + let read = match read { + Ok(read) => read.map_err(|e| e.to_string()), + Err(_) => Err(format!("{worker_path}: the file could not be read")), + }; + // The app may have stopped waiting (Esc): nobody to tell then. + let _ = send.send(read); + if let Some(ctx) = wake { + ctx.request_repaint(); + } + }); + if let Err(e) = spawned { + log::warn!("opening {path} without a thread: {e}"); + return self.open_file("file.open", json!({"path": path})); + } + self.opening.push(Opening { path, name, cancel, read }); + self.show_opening(); + Ok(Value::Null) + } + + /// The status line while files are read: the first one still opening. + fn show_opening(&mut self) { + if let Some(name) = self.opening.first().map(|o| o.name.clone()) { + self.status(crate::i18n::tr(&self.ui.language, "Opening {name}…").replace("{name}", &name)); + } + } + + /// Open the files whose reads are done, in the order they were asked for, and stop waiting + /// for all of them on Esc. Repaints at a low rate while reads run, so the status line stays. + pub(crate) fn poll_opening(&mut self, ctx: &egui::Context) { + if self.opening.is_empty() { + return; + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + // Dropping them tells their workers to stop. + self.opening.clear(); + self.status(crate::i18n::tr(&self.ui.language, "Opening cancelled")); + return; + } + let mut done = Vec::new(); + for o in std::mem::take(&mut self.opening) { + match o.read.try_recv() { + Ok(read) => done.push((o, read)), + Err(TryRecvError::Empty) => self.opening.push(o), + Err(TryRecvError::Disconnected) => { + let lost = format!("{}: the file could not be read", o.path); + done.push((o, Err(lost))); + } + } + } + for (o, read) in done { + // The status line said the file was opening; what the open reports replaces it. + self.status(String::new()); + let params = json!({"path": o.path}); + match read { + Ok(read) => { + self.session.stage_open(read); + let _ = self.open_named_file("file.open", params, o.name.clone()); + } + Err(e) => { + let alert = json!({"title": "Can't Open the File", "file": o.name, "message": e}); + self.status(e); + self.ui.dialog = Some(crate::dialogs::Dialog::new("alert", alert)); + } + } + } + if self.opening.is_empty() { + return; + } + if self.ui.status.is_empty() { + self.show_opening(); + } + ctx.request_repaint_after(std::time::Duration::from_millis(250)); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0896eb19c..e9f6c05df 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -315,6 +315,9 @@ pub struct DesignApp { /// A save asked for while the open-time checks of the document's linked files run: it runs /// once they are done, so the first save already writes the links they confirm. pub(crate) waiting_save: Option, + /// Document files being read on worker threads, in the order they were asked for. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) opening: Vec, /// The tool cursor bitmaps handed to the OS. pub cursors: cursors::Images, /// A panel's live preview (a slider being dragged), committed when it is let go. diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ee571d398..aab78ed1b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -150,12 +150,16 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option { let index = p.get("index").cloned().unwrap_or(Value::Null); - let name = index - .as_u64() - .and_then(|i| usize::try_from(i).ok()) - .and_then(|i| app.session.prefs.recent_files.get(i)) - .map(|path| recent_label(path)) - .unwrap_or_default(); + let path = index.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| app.session.prefs.recent_files.get(i)).cloned(); + // Read in the background, a file still there opens as File › Open opens it; + // `file.openRecent` explains a missing one. + #[cfg(not(target_arch = "wasm32"))] + if app.opens_in_background() + && let Some(path) = path.as_ref().filter(|p| designcraft_engine::io::is_file(p)) + { + return Some(app.open_document(path.clone())); + } + let name = path.as_deref().map(recent_label).unwrap_or_default(); app.open_named_file("file.openRecent", json!({"index": index}), name) } "app.placeDialog" => match (p.get("path").and_then(Value::as_str), p.get("paths").and_then(Value::as_array)) { diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index eebdafbdf..8fe521a6f 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -88,4 +88,8 @@ pub struct Services { /// pointer events fills no frame: an image loads the place cursor, and other files land in the /// middle of the view (`canvas::drop_point`). pub pointer: Option, + /// Documents the person opens (File › Open, Open Recent, a drop, the operating system) are + /// read on a worker thread while the UI keeps running, with "Opening …" in the status line. + /// Off: they open within the command, as scripts' opens always do. + pub open_in_background: bool, } From d2efad58fda521f6789b9ca7ee0a509c4fc95b1b Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 14 Nov 2026 14:46:41 +0000 Subject: [PATCH 2/7] Open: compare documents read on a thread without their process-local data keys --- crates/engine/src/cmd/file/open.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 6bafdd701..506a8639c 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -794,7 +794,11 @@ mod read_install_tests { let installed = staged.execute("file.open", &json!({"path": path})).unwrap(); assert_eq!(installed, opened); - assert_eq!(staged.doc().unwrap().doc, by_command.doc().unwrap().doc); + // Asset data keys are process-wide counters, so compare the saved form and the data apart. + let (a, b) = (&staged.doc().unwrap().doc, &by_command.doc().unwrap().doc); + assert_eq!(serde_json::to_value(a).unwrap(), serde_json::to_value(b).unwrap()); + let data = |d: &designcraft_doc::Document| d.assets.values().map(|x| (x.id, x.data.is_linked(), x.data.len())).collect::>(); + assert_eq!(data(a), data(b)); assert_eq!(staged.doc().unwrap().path, by_command.doc().unwrap().path); assert_eq!(staged.prefs.recent_files, by_command.prefs.recent_files); assert!(staged.execute("file.open", &json!({"path": path})).is_err(), "a staged document opens once"); From 63138e56421514040330243d9d9d0b58ea4e1f96 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 11:36:54 -0500 Subject: [PATCH 3/7] mcp: add protocol transcript tests for initialize, cancel, and batch (#3071) --- crates/mcp/src/tests.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6bfce8e4e..d95078c1b 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -842,3 +842,29 @@ fn serve_accepts_ping_at_legacy_eof_limit() { assert_eq!(response["id"], 52); assert_eq!(response["result"], json!({})); } + +#[test] +fn stdio_cancel_and_batch_transcript() { + let input = concat!( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n", + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n", + "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":1,\"reason\":\"client\"}}\n", + "[]\n", + "[{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":9}}]\n", + "[{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"},{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}]\n", + "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\",\"params\":{}}\n" + ); + let mut s = server(); + let mut out = Vec::new(); + s.serve(input.as_bytes(), &mut out).unwrap(); + assert!(s.is_initialized()); + + let replies: Vec = std::str::from_utf8(&out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 4, "{replies:?}"); + assert_eq!(replies[0]["id"], 1); + assert_eq!(replies[0]["result"]["serverInfo"]["name"], "designcraft"); + assert_eq!(replies[1]["id"], Value::Null); + assert_eq!(replies[1]["error"]["code"], -32600); + assert_eq!(replies[2], json!([{"jsonrpc": "2.0", "id": 2, "result": {}}])); + assert_eq!(replies[3], json!({"jsonrpc": "2.0", "id": 3, "result": {}})); +} From 4000591c6681d01386b9576f9a050b8460e6f2e3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 20 Nov 2026 12:52:22 -0500 Subject: [PATCH 4/7] render, images: align JPEG export guards and add export/probe parity tests (storytold/craft-libs#778) (#3073) --- crates/images/src/tests.rs | 10 ++++++++++ crates/render/src/lib.rs | 20 ++++++++++++++------ crates/render/src/tests.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 604b3a81e..03d026e3d 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -1379,3 +1379,13 @@ fn png_from_rgba_parity_and_guards() { assert_eq!(png_from_rgba(2, 0, vec![]), None); assert_eq!(png_from_rgba(2, 2, vec![0; 12]), None); } + +#[test] +fn tiff_exif_orientation_and_progressive_jpeg_probes() { + let tiff = tiff_bytes_with_orientation((300, 1), (150, 1), 2, 6); + assert_eq!(raster_resolution(&tiff), Some((150.0, 300.0))); + + let prog = progressive_jpeg(16, 8, 3); + assert_eq!(pixel_size(&prog), Some((16, 8))); + assert!(decode_bytes_per_pixel(&prog) >= 8); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 693c5bc62..2e97737d4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -72,18 +72,24 @@ impl Rendered { } out } - /// PNG bytes (empty, with the error logged, if the image can't be encoded). - pub fn to_png(&self) -> Vec { + fn straight_rgba_padded(&self, label: &str) -> Option> { if self.width == 0 || self.height == 0 { - return Vec::new(); + return None; } let Some(len) = (self.width as usize).checked_mul(self.height as usize).and_then(|n| n.checked_mul(4)) else { - log::error!("PNG encode: {}×{} image is too large", self.width, self.height); - return Vec::new(); + log::error!("{label}: {}×{} image is too large", self.width, self.height); + return None; }; let mut px = self.to_straight(); // `pixels` is public: a mismatched buffer is padded or cut to the stated size. px.resize(len, 0); + Some(px) + } + /// PNG bytes (empty, with the error logged, if the image can't be encoded). + pub fn to_png(&self) -> Vec { + let Some(px) = self.straight_rgba_padded("PNG encode") else { + return Vec::new(); + }; let Ok(img) = craft_image_codecs::Image::from_u8(self.width, self.height, craft_image_codecs::ChannelLayout::Rgba, px) else { log::error!("PNG encode: {}×{} image is too large", self.width, self.height); return Vec::new(); @@ -97,7 +103,9 @@ impl Rendered { } } pub fn to_jpeg(&self, quality: u8) -> Vec { - let rgba = self.to_straight(); + let Some(rgba) = self.straight_rgba_padded("JPEG encode") else { + return Vec::new(); + }; let rgb: Vec = rgba .as_chunks::<4>() .0 diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 399c13623..288c77520 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -138,6 +138,41 @@ fn to_png_parity_color_alpha_no_icc_no_phys_and_zero_guard() { assert!(Rendered { width: 4, height: 0, pixels: vec![] }.to_png().is_empty()); } +#[test] +fn to_jpeg_parity_white_backdrop_quality_no_icc_no_density_and_guards() { + let rendered = Rendered { + width: 2, + height: 2, + pixels: vec![ + 128, 0, 0, 128, // premultiplied half-alpha red over white -> ~[255, 127, 127] + 0, 0, 0, 0, // transparent -> white [255, 255, 255] + 10, 20, 30, 255, // opaque dark + 0, 255, 0, 255, // opaque green + ], + }; + let jpeg = rendered.to_jpeg(95); + let decoded = craft_image_codecs::decode(&jpeg).expect("valid JPEG"); + assert_eq!(decoded.dimensions(), (2, 2)); + assert_eq!(decoded.layout(), craft_image_codecs::ChannelLayout::Rgb); + assert_eq!(decoded.sample_type(), craft_image_codecs::SampleType::U8); + assert_eq!(decoded.icc, None); + assert_eq!(decoded.meta.dpi, None); + assert_eq!(designcraft_images::raster_resolution(&jpeg), None); + + // Quality clamping (0 -> 1, 200 -> 100) produces valid JPEGs and respects quality ordering. + let low = rendered.to_jpeg(0); + let high = rendered.to_jpeg(200); + assert_eq!(craft_image_codecs::decode(&low).expect("clamped low").dimensions(), (2, 2)); + assert_eq!(craft_image_codecs::decode(&high).expect("clamped high").dimensions(), (2, 2)); + + // Mismatched short buffer survives like to_png, and zero dimensions return empty. + let short = Rendered { width: 4, height: 4, pixels: vec![255; 10] }.to_jpeg(90); + assert_eq!(craft_image_codecs::decode(&short).expect("short buffer").dimensions(), (4, 4)); + assert!(Rendered { width: 0, height: 0, pixels: vec![] }.to_jpeg(90).is_empty()); + assert!(Rendered { width: 0, height: 4, pixels: vec![] }.to_jpeg(90).is_empty()); + assert!(Rendered { width: 4, height: 0, pixels: vec![] }.to_jpeg(90).is_empty()); +} + #[test] fn proof_view_simulates_the_target() { use designcraft_color::cms::{ProofSetup, ProofTarget}; From 0fc7a7894c82243b08ca8cc3fd2766c404f3899c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 12:14:16 -0500 Subject: [PATCH 5/7] images: replace local JPEG EXIF and PNG pHYs scans with shared readers (craft-libs#785) (#3101) * images: use shared JPEG EXIF and PNG pHYs readers (craft-libs#785) * images: repin craft-libs and use png_probe::pixels_per_meter (craft-libs#785) * Cargo: patch vendored vello/linesweeper from craft-libs * xtask: update pdf-deps craft-libs rev to c60e7a20 --- Cargo.lock | 182 ++++++++++++++++---------------- Cargo.toml | 78 +++++++------- crates/images/Cargo.toml | 1 + crates/images/src/resolution.rs | 68 ++---------- crates/images/src/tests.rs | 87 +++++++++++++++ xtask/src/pdf_deps.rs | 4 +- 6 files changed, 231 insertions(+), 189 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f7b3c3677..c96d538bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1083,7 +1083,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "rustix 1.1.5", ] @@ -1091,12 +1091,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "md-5", "rayon", @@ -1105,12 +1105,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "thiserror 2.0.21", ] @@ -1118,7 +1118,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "rayon", ] @@ -1126,7 +1126,7 @@ dependencies = [ [[package]] name = "craft-designcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-document-bundle", "craft-eps", @@ -1138,7 +1138,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1151,14 +1151,14 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-document-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "serde_json", "thiserror 2.0.21", "zip 9.1.1", @@ -1167,7 +1167,7 @@ dependencies = [ [[package]] name = "craft-docx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "base64 0.23.1", "chrono", @@ -1176,7 +1176,7 @@ dependencies = [ "craft-offcrypto", "craft-opc", "craft-wordmodel", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "log", "quick-xml 0.41.0", "thiserror 2.0.21", @@ -1187,9 +1187,10 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "chrono", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "kurbo", "log", "serde", @@ -1198,27 +1199,27 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-epub" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "thiserror 2.0.21", ] [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-eps", - "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-idml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "craft-svg", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "serde", "serde_json", ] @@ -1226,12 +1227,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1251,16 +1252,6 @@ dependencies = [ "writeable", ] -[[package]] -name = "craft-idml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" -dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "thiserror 2.0.21", -] - [[package]] name = "craft-idml" version = "0.1.0" @@ -1271,10 +1262,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-idml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "thiserror 2.0.21", +] + [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-dds", "craft-jpeg", @@ -1301,7 +1302,7 @@ dependencies = [ [[package]] name = "craft-indd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "indd", ] @@ -1309,7 +1310,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "thiserror 2.0.21", ] @@ -1317,7 +1318,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-i18n", "craft-ui", @@ -1329,16 +1330,17 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "roxmltree 0.21.2", "serde", ] [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "serde_json", ] @@ -1346,7 +1348,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "brotli-decompressor 6.3.1", "chrono", @@ -1358,7 +1360,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "chrono", "craft-codepage", @@ -1368,12 +1370,12 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "aes", "base64 0.23.1", "craft-cfb", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "getrandom 0.3.4", "hmac", "sha1 0.11.0", @@ -1385,10 +1387,10 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "log", "thiserror 2.0.21", ] @@ -1396,7 +1398,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "bytemuck", "craft-svg", @@ -1412,11 +1414,11 @@ dependencies = [ [[package]] name = "craft-pptx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-drawingml", "craft-opc", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "kurbo", "log", "serde", @@ -1427,7 +1429,7 @@ dependencies = [ [[package]] name = "craft-prepress" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-cms", "craft-pdf", @@ -1440,7 +1442,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-winprint-gdi", "log", @@ -1454,7 +1456,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-eps", "kurbo", @@ -1467,7 +1469,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "encoding_rs", "flate2", @@ -1478,7 +1480,7 @@ dependencies = [ [[package]] name = "craft-rtf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-codepage", "encoding_rs", @@ -1487,15 +1489,15 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-image-codecs", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "data-url", "flate2", "gif", @@ -1513,7 +1515,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "serde", "thiserror 2.0.21", @@ -1522,7 +1524,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1543,7 +1545,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "chrono", "dunce", @@ -1570,7 +1572,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "egui", "objc2 0.6.5", @@ -1589,7 +1591,7 @@ dependencies = [ [[package]] name = "craft-wordmodel" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "base64 0.23.1", "craft-math", @@ -1603,22 +1605,12 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "craft-drawingml", "craft-opc", "craft-sheet", - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3)", - "thiserror 2.0.21", -] - -[[package]] -name = "craft-xml" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" -dependencies = [ - "quick-xml 0.41.0", - "serde", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1)", "thiserror 2.0.21", ] @@ -1632,10 +1624,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d#b92907f69d6599b91ac76fb8377ac407c8ac956d" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1645,7 +1647,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b92907f69d6599b91ac76fb8377ac407c8ac956d#b92907f69d6599b91ac76fb8377ac407c8ac956d" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2001,6 +2003,7 @@ dependencies = [ "craft-file-formats", "craft-image-codecs", "craft-jpeg", + "craft-metadata", "craft-ps", "craft-psd", "craft-svg", @@ -3246,7 +3249,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "bytemuck", "hayro-interpret", @@ -3266,7 +3269,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "brotli", "hayro-postscript", @@ -3275,7 +3278,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3293,7 +3296,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3311,12 +3314,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "flate2", "hayro-ccitt", @@ -3951,7 +3954,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=3dff4793f1a5bd1f99a4fe3280d48f515158dff3#3dff4793f1a5bd1f99a4fe3280d48f515158dff3" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4060,8 +4063,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "arrayvec", "kurbo", @@ -7318,8 +7320,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "bytemuck", "fearless_simd", @@ -7368,8 +7369,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" +source = "git+https://github.com/storytold/craft-libs?rev=c60e7a20063313b80a994075adb4f797b24ab4f1#c60e7a20063313b80a994075adb4f797b24ab4f1" dependencies = [ "bytemuck", "glifo 0.1.1", diff --git a/Cargo.toml b/Cargo.toml index 5fc382d6d..4d5a059fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,36 +12,37 @@ repository = "https://github.com/storytold/designcraft" [workspace.dependencies] # Shared RFC 4648 encoding; document decoding policies remain local. -craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } # Shared JSON-RPC 2.0 / MCP server framing and lifecycle. -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } # Shared reader and writer; publish the immutable revision before this consumer. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0", default-features = false } -craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0", features = ["read"] } -craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", default-features = false } +craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["read"] } +craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "b92907f69d6599b91ac76fb8377ac407c8ac956d", version = "=0.1.0" } -craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0", features = ["tree-render", "tree-text"] } +craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["tree-render", "tree-text"] } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b92907f69d6599b91ac76fb8377ac407c8ac956d", version = "=0.1.0" } -craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +craft-pptx = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } # Shared keyboard bindings: chords, overrides, conflicts, egui dispatch, the Keyboard Shortcuts dialog. -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0", features = ["egui", "ui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["egui", "ui"] } # Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch. -craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0", features = ["flatten"] } +craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0", features = ["flatten"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["egui"] } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } @@ -99,20 +100,20 @@ qrcodegen = "1.8" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } # Which paths stored in documents may be followed (craft-libs). -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } # Atomic file replacement for saves and exports (craft-libs). -craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-atomic = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } # File › Print through the system print spooler (craft-libs). -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } # ICC colour management: working spaces, transforms, black point compensation (craft-libs). -craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-cms = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } # ui # Shared frontend components; keep this dependency above the engine boundary. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["serde"] } # The application bar as the window's title bar (craft-libs). -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", features = ["egui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", features = ["egui"] } egui = "0.37" # Resizable table columns (About ▸ Contributors / Models); no image loaders. egui_extras = { version = "0.37", default-features = false } @@ -122,7 +123,7 @@ egui_kittest = "0.37" web-time = "1" rfd = "0.17" # Native file and message dialogs that never block the event loop (craft-libs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } raw-window-handle = "0.6" arboard = { version = "3.6", default-features = false } @@ -156,16 +157,19 @@ debug = 0 # Opt-in cancelable macOS termination on the pinned winit 0.30 line. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.8.2" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.8.2" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # The hayro crates from craft-libs' vendor/ directory (pdfcraft's, plus the plate mode and decode # limits craft-pdf and craft-prepress need); same revision as craft-pdf. -hayro = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.7.1" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.7.0" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.3.0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3", version = "=0.1.0" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.1" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.3.0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/crates/images/Cargo.toml b/crates/images/Cargo.toml index 77841b5ea..090b20724 100644 --- a/crates/images/Cargo.toml +++ b/crates/images/Cargo.toml @@ -23,6 +23,7 @@ craft-image-codecs = { workspace = true } craft-psd = { workspace = true } craft-file-formats = { workspace = true } craft-jpeg = { workspace = true } +craft-metadata = { workspace = true } [dev-dependencies] image = { workspace = true, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index 2faafd5c4..9045ab116 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -2,10 +2,9 @@ //! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide). //! Delegates container resolution probes to `craft-image-codecs` (`file_resolution`, which reads //! JPEG Photoshop ResolutionInfo -> XMP -> EXIF -> JFIF, PNG eXIf, WebP EXIF, and classic TIFF; -//! plus `exif_resolution` and `bmp_probe::pixels_per_meter`) and PSD `ResolutionInfo` to -//! [`crate::psd`]. PNG `pHYs` is read locally in `f64` before falling back to `file_resolution` -//! for `eXIf`. GIF and files without (usable) metadata report nothing and keep the -//! pixel-is-a-point size. +//! plus `exif_resolution`, `png_probe::pixels_per_meter`, and `bmp_probe::pixels_per_meter`), +//! JPEG EXIF orientation to `craft-metadata`, and PSD `ResolutionInfo` to [`crate::psd`]. GIF and +//! files without (usable) metadata report nothing and keep the pixel-is-a-point size. /// Dots per inch in x and y, when the file carries usable resolution metadata. pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { @@ -43,65 +42,16 @@ fn orientation(bytes: &[u8]) -> u16 { 1 } -/// EXIF orientation from a JPEG's APP1 `"Exif\0\0"` segment before the first scan. +/// EXIF orientation from a JPEG's first APP1 `"Exif\0\0"` segment before the first scan. fn jpeg_orientation(bytes: &[u8]) -> u16 { - let mut i = 2usize; - while i + 4 <= bytes.len() { - if bytes[i] != 0xFF { - break; - } - let marker = bytes[i + 1]; - if marker == 0xFF { - i += 1; - continue; - } - if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 { - i += 2; - continue; - } - if marker == 0xDA || marker == 0xD9 { - break; - } - let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize; - if len < 2 || i + 2 + len > bytes.len() { - break; - } - let seg = &bytes[i + 4..i + 2 + len]; - if marker == 0xE1 - && let Some(exif) = seg.strip_prefix(b"Exif\0\0") - { - return craft_image_codecs::exif_orientation(exif); - } - i += 2 + len; - } - 1 + craft_metadata::jpeg_segments(bytes).exif.as_deref().map_or(1, craft_image_codecs::exif_orientation) } -/// The pHYs chunk: pixels-per-unit in x and y plus the unit (1 = meter -> dpi, in f64). +/// PNG `pHYs` pixels-per-metre via the shared probe: meters -> dpi in `f64` (preserving exact +/// placement DPI without `dpi_of_ppm` snapping). fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { - let mut pos = 8; - loop { - let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; - let kind = bytes.get(pos + 4..pos + 8)?; - if kind == b"pHYs" { - if len != 9 { - return None; - } - let data = bytes.get(pos + 8..pos + 8 + 13)?; - let (x, y) = (u32::from_be_bytes(data[0..4].try_into().ok()?), u32::from_be_bytes(data[4..8].try_into().ok()?)); - if data[8] == 1 && x > 0 && y > 0 { - return Some((x as f64 * 0.0254, y as f64 * 0.0254)); - } - return None; - } - if kind == b"IEND" || kind == b"IDAT" { - return None; - } - pos = pos.checked_add(8)?.checked_add(len)?.checked_add(4)?; - if pos >= bytes.len() { - return None; - } - } + let (x, y) = craft_image_codecs::png_probe::pixels_per_meter(bytes)?; + Some((f64::from(x) * 0.0254, f64::from(y) * 0.0254)) } /// A parsed density is usable when both axes are finite, positive and below the absurdity cap diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 03d026e3d..e57a8b6a6 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -1389,3 +1389,90 @@ fn tiff_exif_orientation_and_progressive_jpeg_probes() { assert_eq!(pixel_size(&prog), Some((16, 8))); assert!(decode_bytes_per_pixel(&prog) >= 8); } + +#[test] +fn jpeg_orientation_keeps_first_exif_app1_segment() { + let mut first_wins = exif_app(&tiff_bytes_with_orientation((300, 1), (150, 1), 2, 6)); + first_wins.extend_from_slice(&exif_app(&tiff_bytes_with_orientation((300, 1), (150, 1), 2, 1))); + assert_eq!(raster_resolution(&jpeg_with(&first_wins)), Some((150.0, 300.0))); + + let mut upright_first = exif_app(&tiff_bytes_with_orientation((300, 1), (150, 1), 2, 1)); + upright_first.extend_from_slice(&exif_app(&tiff_bytes_with_orientation((300, 1), (150, 1), 2, 6))); + assert_eq!(raster_resolution(&jpeg_with(&upright_first)), Some((300.0, 150.0))); +} + +#[test] +fn png_phys_exif_fallback_orientation_swap_and_shared_chunk_limit() { + fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec { + let mut out = (data.len() as u32).to_be_bytes().to_vec(); + out.extend_from_slice(kind); + out.extend_from_slice(data); + let mut crc_input = kind.to_vec(); + crc_input.extend_from_slice(data); + out.extend_from_slice(&crc32(&crc_input).to_be_bytes()); + out + } + fn png_with_chunks(width: u32, height: u32, extra: &[Vec]) -> Vec { + let img = image::RgbaImage::from_pixel(width, height, image::Rgba([0, 0, 0, 255])); + let mut base = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut base), image::ImageFormat::Png).unwrap(); + let mut out = base[..33].to_vec(); + for c in extra { + out.extend_from_slice(c); + } + out.extend_from_slice(&base[33..]); + out + } + fn phys_data(x: u32, y: u32, unit: u8) -> Vec { + let mut d = x.to_be_bytes().to_vec(); + d.extend_from_slice(&y.to_be_bytes()); + d.push(unit); + d + } + + // Independent pHYs axes (144 x 72 ppi) and exact placement size (#1648 parity), plus exact unsnapped f64 DPI. + let asym = png_with_chunks(144, 72, &[png_chunk(b"pHYs", &phys_data(5669, 2835, 1))]); + let (ax, ay) = raster_resolution(&asym).unwrap(); + assert!((ax - 5669.0 * 0.0254).abs() < 1e-12 && (ay - 2835.0 * 0.0254).abs() < 1e-12, "{ax} x {ay}"); + let (nw, nh) = natural_size(&asym).unwrap(); + assert!((nw - 144.0 * 72.0 / (5669.0 * 0.0254)).abs() < 1e-9 && (nh - 72.0 * 72.0 / (2835.0 * 0.0254)).abs() < 1e-9, "{nw} x {nh}"); + + let exact_330 = png_with_chunks(330, 510, &[png_chunk(b"pHYs", &phys_data(1181, 1181, 1))]); + let (ew, eh) = natural_size(&exact_330).unwrap(); + assert!((ew - 330.0 * 72.0 / (1181.0 * 0.0254)).abs() < 1e-9 && (eh - 510.0 * 72.0 / (1181.0 * 0.0254)).abs() < 1e-9, "{ew} x {eh}"); + + // Unitless or zero pHYs without eXIf falls back to 1 px = 1 pt. + for bad in [phys_data(5669, 5669, 0), phys_data(0, 5669, 1)] { + let png = png_with_chunks(144, 72, &[png_chunk(b"pHYs", &bad)]); + assert_eq!(raster_resolution(&png), None); + assert_eq!(natural_size(&png), Some((144.0, 72.0))); + } + + // eXIf fallback when pHYs is absent or unusable; pHYs wins when valid. + let exif_300 = tiff_bytes((300, 1), (300, 1), Some(2)); + let only_exif = png_with_chunks(4, 4, &[png_chunk(b"eXIf", &exif_300)]); + assert_eq!(raster_resolution(&only_exif), Some((300.0, 300.0))); + let unitless_plus_exif = png_with_chunks(4, 4, &[png_chunk(b"pHYs", &phys_data(5669, 5669, 0)), png_chunk(b"eXIf", &exif_300)]); + assert_eq!(raster_resolution(&unitless_plus_exif), Some((300.0, 300.0))); + let phys_wins = png_with_chunks(4, 4, &[png_chunk(b"pHYs", &phys_data(5906, 5906, 1)), png_chunk(b"eXIf", &exif_300)]); + assert_eq!(raster_resolution(&phys_wins), Some((5906.0 * 0.0254, 5906.0 * 0.0254))); + + // Orientation 6 swaps pHYs axes. + let rotated = png_with_chunks( + 4, + 4, + &[png_chunk(b"pHYs", &phys_data(11811, 5906, 1)), png_chunk(b"eXIf", &tiff_bytes_with_orientation((300, 1), (150, 1), 2, 6))], + ); + assert_eq!(raster_resolution(&rotated), Some((5906.0 * 0.0254, 11811.0 * 0.0254))); + + // Shared resolution_probe chunk limit (MAX_CHUNKS = 4096, counting IHDR as chunk 0). + let phys = png_chunk(b"pHYs", &phys_data(11811, 11811, 1)); + let text = png_chunk(b"tEXt", b"k\x00v"); + let mut at_limit = vec![text.clone(); 4094]; + at_limit.push(phys.clone()); + assert_eq!(raster_resolution(&png_with_chunks(1, 1, &at_limit)), Some((11811.0 * 0.0254, 11811.0 * 0.0254))); + + let mut past_limit = vec![text; 4095]; + past_limit.push(phys); + assert_eq!(raster_resolution(&png_with_chunks(1, 1, &past_limit)), None); +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 368abbd7d..0329e0f7f 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,8 +5,8 @@ use std::process::Command; use serde_json::Value; const REPO: &str = "https://github.com/storytold/craft-libs"; -const REV: &str = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3"; -const COMMIT: &str = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3"; +const REV: &str = "c60e7a20063313b80a994075adb4f797b24ab4f1"; +const COMMIT: &str = "c60e7a20063313b80a994075adb4f797b24ab4f1"; const PACKAGES: &[(&str, &str)] = &[ ("craft-pdf", "0.1.0"), ("krilla", "0.8.2"), From d7401b647be1fe91dbaa4e06c57f7a1e210b6b02 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 12:36:17 -0500 Subject: [PATCH 6/7] images: restore strict JPEG APP1 EXIF scan (craft-libs#785) (#3105) --- Cargo.lock | 1 - Cargo.toml | 1 - crates/images/Cargo.toml | 1 - crates/images/src/resolution.rs | 38 +++++++++++++++++++++++++++++---- crates/images/src/tests.rs | 22 +++++++++++++++++++ 5 files changed, 56 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c96d538bf..486db4e08 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2003,7 +2003,6 @@ dependencies = [ "craft-file-formats", "craft-image-codecs", "craft-jpeg", - "craft-metadata", "craft-ps", "craft-psd", "craft-svg", diff --git a/Cargo.toml b/Cargo.toml index 4d5a059fc..cf544a6bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,6 @@ craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "c60e craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "c60e7a20063313b80a994075adb4f797b24ab4f1", version = "=0.1.0" } diff --git a/crates/images/Cargo.toml b/crates/images/Cargo.toml index 090b20724..77841b5ea 100644 --- a/crates/images/Cargo.toml +++ b/crates/images/Cargo.toml @@ -23,7 +23,6 @@ craft-image-codecs = { workspace = true } craft-psd = { workspace = true } craft-file-formats = { workspace = true } craft-jpeg = { workspace = true } -craft-metadata = { workspace = true } [dev-dependencies] image = { workspace = true, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index 9045ab116..d20d4a940 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -2,9 +2,10 @@ //! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide). //! Delegates container resolution probes to `craft-image-codecs` (`file_resolution`, which reads //! JPEG Photoshop ResolutionInfo -> XMP -> EXIF -> JFIF, PNG eXIf, WebP EXIF, and classic TIFF; -//! plus `exif_resolution`, `png_probe::pixels_per_meter`, and `bmp_probe::pixels_per_meter`), -//! JPEG EXIF orientation to `craft-metadata`, and PSD `ResolutionInfo` to [`crate::psd`]. GIF and -//! files without (usable) metadata report nothing and keep the pixel-is-a-point size. +//! plus `exif_resolution`, `png_probe::pixels_per_meter`, and `bmp_probe::pixels_per_meter`) and +//! PSD `ResolutionInfo` to [`crate::psd`]. JPEG EXIF orientation keeps the strict local APP1 scan +//! (`"Exif\0\0"` with complete segment bounds). GIF and files without (usable) metadata report +//! nothing and keep the pixel-is-a-point size. /// Dots per inch in x and y, when the file carries usable resolution metadata. pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { @@ -44,7 +45,36 @@ fn orientation(bytes: &[u8]) -> u16 { /// EXIF orientation from a JPEG's first APP1 `"Exif\0\0"` segment before the first scan. fn jpeg_orientation(bytes: &[u8]) -> u16 { - craft_metadata::jpeg_segments(bytes).exif.as_deref().map_or(1, craft_image_codecs::exif_orientation) + let mut i = 2usize; + while i + 4 <= bytes.len() { + if bytes[i] != 0xFF { + break; + } + let marker = bytes[i + 1]; + if marker == 0xFF { + i += 1; + continue; + } + if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 { + i += 2; + continue; + } + if marker == 0xDA || marker == 0xD9 { + break; + } + let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize; + if len < 2 || i + 2 + len > bytes.len() { + break; + } + let seg = &bytes[i + 4..i + 2 + len]; + if marker == 0xE1 + && let Some(exif) = seg.strip_prefix(b"Exif\0\0") + { + return craft_image_codecs::exif_orientation(exif); + } + i += 2 + len; + } + 1 } /// PNG `pHYs` pixels-per-metre via the shared probe: meters -> dpi in `f64` (preserving exact diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index e57a8b6a6..c5fd13ca2 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -1401,6 +1401,28 @@ fn jpeg_orientation_keeps_first_exif_app1_segment() { assert_eq!(raster_resolution(&jpeg_with(&upright_first)), Some((300.0, 150.0))); } +#[test] +fn jpeg_orientation_requires_exact_exif_prefix_and_complete_app1() { + let tiff_rot6 = tiff_bytes_with_orientation((300, 1), (150, 1), 2, 6); + + // Looser prefix ("Exif\0\x01" instead of "Exif\0\0") must not be treated as EXIF. + let mut looser_payload = b"Exif\0\x01".to_vec(); + looser_payload.extend_from_slice(&tiff_rot6); + let mut looser_seg = vec![0xFF, 0xE1]; + looser_seg.extend_from_slice(&((looser_payload.len() + 2) as u16).to_be_bytes()); + looser_seg.extend_from_slice(&looser_payload); + let mut with_looser = jfif_app(1, 300, 150); + with_looser.extend_from_slice(&looser_seg); + assert_eq!(raster_resolution(&jpeg_with(&with_looser)), Some((300.0, 150.0))); + + // Truncated APP1 segment (declared length past end of file) must be ignored. + let mut truncated = vec![0xFF, 0xD8]; + truncated.extend_from_slice(&jfif_app(1, 300, 150)); + truncated.extend_from_slice(&exif_app(&tiff_rot6)); + truncated.pop(); + assert_eq!(raster_resolution(&truncated), Some((300.0, 150.0))); +} + #[test] fn png_phys_exif_fallback_orientation_swap_and_shared_chunk_limit() { fn png_chunk(kind: &[u8; 4], data: &[u8]) -> Vec { From a6d82e9a3c65507b19c788cc4395ece38adb2f7d Mon Sep 17 00:00:00 2001 From: TS-Ca Date: Sat, 21 Nov 2026 19:00:28 +0100 Subject: [PATCH 7/7] Images: decode TIFF screen and link proxies at a reduced size (#2381) (#3016) * Images: decode TIFF screen and link proxies at a reduced size (#2381) Stream placed TIFFs a strip or tile row at a time through craft_image_codecs::TiffBands into 1/2, 1/4 or 1/8 RGBA buffers (512 MiB per band, 1 GiB reduced output) with alpha-weighted box averaging and embedded ICC / working-CMYK display conversion. Wire reduced TIFF sizes and estimates into designcraft-render's screen mip cache (clamping oversized rasters to reduced levels when zooming in so decode_full does not poison the cache entry) and linked-file proxy generation. * Images: round up in finest_level and cover 512 MiB single-strip cap (#2381) Match the reduced decoder's round-up dimensions (`div_ceil(2)`) when selecting `finest_level` so odd oversized widths such as 131071x128 pick a level whose decoded buffer fits `Pixmap` and the 1 GiB RGBA cap before cropping. Replace the truncated header-only single-strip assertion with a complete zlib-compressed single-strip CMYK TIFF above the 512 MiB band limit. * Images: count orientation/float/Lab in reduced TIFF estimate and lighten tests (#2381) * Images: include partial-cell map bound in reduced TIFF peak estimate (#2381) --------- Co-authored-by: TS-Ca <358700769+thib-cal@users.noreply.github.com> --- ROADMAP.md | 1 + contributors/people.toml | 4 + crates/images/src/lib.rs | 30 ++- crates/images/src/tests.rs | 338 ++++++++++++++++++++++++++++++ crates/images/src/tiff_reduced.rs | 294 ++++++++++++++++++++++++++ crates/render/src/decode.rs | 2 +- crates/render/src/images.rs | 184 +++++++++++++--- crates/render/src/proxy.rs | 14 +- 8 files changed, 832 insertions(+), 35 deletions(-) create mode 100644 crates/images/src/tiff_reduced.rs diff --git a/ROADMAP.md b/ROADMAP.md index f0f5dc5d0..6f1735a5e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -431,6 +431,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-11-19** · A placed TIFF drawn at a half, a quarter or an eighth of its pixel size or less (or past the 1 GiB full-size RGBA cap, #2381) is decoded a band at a time (`TiffBands`) into that reduced size, so large print TIFFs draw on the canvas, in page thumbnails and in linked-file proxies without a full-size decode. No readiness percentage change. - **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. - **2026-11-04** · Interface Language › Português (Brasil) translates the whole interface: 996 strings the catalog lacked (tool names, window and guide commands, Keyboard Shortcuts sets, panel docking, Edit › Menus paths, the Japanese typesetting dialogs, special characters, Load Styles, Data Merge, Preflight, font replacement, the Package summary, OpenType features, page presets, About) and File › New's unit names, and a path is "demarcador" throughout. `cargo xtask i18n-report` counts 2,936 of 2,939 strings for pt-BR (1,933 before); only the Control panel's `IT`, `VA` and `Y:` captions stay English, as in every language. No readiness percentage change. diff --git a/contributors/people.toml b/contributors/people.toml index ea38d2b4a..bf35bff30 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -97,3 +97,7 @@ sync_github_name = true [people.gmrmad1] real_name = "Madhav Agarwal" + +[people.thib-cal] +display_name = "TS-Ca" +sync_github_name = true diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 10a894a26..c58061d91 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -12,6 +12,7 @@ mod eps; mod jpeg; mod psd; mod resolution; +mod tiff_reduced; mod tone; pub use craft_ps::read::is_eps; pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size}; @@ -382,7 +383,7 @@ pub fn too_large_to_decode(bytes: &[u8]) -> bool { } /// Whether a `w` × `h` raster takes more than [`MAX_RGBA_BYTES`] as RGBA. -fn over_rgba_budget(w: u32, h: u32) -> bool { +pub(crate) fn over_rgba_budget(w: u32, h: u32) -> bool { u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES } @@ -513,6 +514,17 @@ pub fn reduced_jpeg_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usiz jpeg::reduced_estimate(bytes, shrink) } +/// Whether [`decode_rgba_reduced`] handles this format (JPEGs and TIFFs). +pub fn supports_reduced_decode(bytes: &[u8]) -> bool { + bytes.starts_with(&[0xFF, 0xD8]) || tiff_reduced::is_tiff(bytes) +} + +/// Dimensions and estimated peak bytes for an image decoded at `1/2^shrink`, without decoding its +/// pixels. `None` when [`decode_rgba_reduced`] cannot handle the image. +pub fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { + if tiff_reduced::is_tiff(bytes) { tiff_reduced::reduced_estimate(bytes, shrink) } else { jpeg::reduced_estimate(bytes, shrink) } +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. @@ -541,13 +553,17 @@ pub(crate) fn embedded_icc(bytes: &[u8]) -> Option> { /// The largest `shrink` [`decode_rgba_reduced`] takes: 3, an eighth of each side. pub const MAX_REDUCED_SHRINK: u8 = jpeg::MAX_SHRINK; -/// [`decode_rgba`] of a JPEG at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each -/// side rounded up), read from its compressed blocks without a full-size decode. The embedded ICC -/// profile is applied as [`decode_rgba`] applies it. `None` where only a full decode applies: other -/// formats, CMYK, 12-bit and lossless JPEGs, files whose size [`pixel_size`] cannot read, and files -/// [`decode_rgba`] refuses as too large. +/// [`decode_rgba`] at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each side +/// rounded up), read without a full-size decode. The embedded ICC profile (and working CMYK space +/// for CMYK TIFFs) is applied as [`decode_rgba`] applies it. `None` where only a full decode +/// applies: other formats, CMYK/12-bit/lossless JPEGs, non-CMYK separated TIFFs (`InkSet` 2), +/// files whose size [`pixel_size`] cannot read, JPEGs whose full size is over the full decode's +/// limit, and TIFFs whose reduced output or strip/tile band exceeds budget. pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option { use colour::{DisplayColour, Pixels, to_display_rgba}; + if tiff_reduced::is_tiff(bytes) { + return tiff_reduced::decode_reduced(bytes, shrink); + } // The size check must have a size to check: a header only the JPEG decoder reads is refused. pixel_size(bytes)?; if too_large_to_decode(bytes) { @@ -572,7 +588,7 @@ pub struct CmykRaster { } /// The TIFF page that decoding opens; `None` for other formats. -fn default_tiff_page(bytes: &[u8]) -> Option { +pub(crate) fn default_tiff_page(bytes: &[u8]) -> Option { let mut info = craft_image_codecs::tiff_info(bytes).ok()?; let page = info.default_page()?; (page < info.pages.len()).then(|| info.pages.swap_remove(page)) diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index c5fd13ca2..f13e9716f 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -1146,6 +1146,344 @@ fn reduced_decoding_refuses_progressive_jpegs_whose_full_size_coefficients_are_o assert_eq!(gray.dimensions(), (1_280, 550)); } +/// PackBits-compressed run of `len` identical bytes (`val`). +fn packbits_repeat(len: usize, val: u8) -> Vec { + let mut out = Vec::with_capacity((len / 128 + 1) * 2); + let mut left = len; + while left >= 128 { + out.push(129); + out.push(val); + left -= 128; + } + if left > 1 { + out.push((1 - left as isize) as u8); + out.push(val); + } else if left == 1 { + out.push(0); + out.push(val); + } + out +} + +/// Minimal little-endian single-IFD TIFF builder supporting multiple strips, arbitrary `RowsPerStrip`, +/// `Compression`, `InkSet` (tag 332), and `ExtraSamples` (tag 338). +#[allow(clippy::too_many_arguments)] +fn custom_striped_tiff( + w: u32, + h: u32, + rows_per_strip: u32, + photometric: u16, + compression: u16, + spp: u16, + strips: &[&[u8]], + extra_sample: Option, + ink_set: Option, +) -> Vec { + custom_striped_tiff_with(w, h, rows_per_strip, photometric, compression, spp, 8, None, None, strips, extra_sample, ink_set) +} + +#[allow(clippy::too_many_arguments)] +fn custom_striped_tiff_with( + w: u32, + h: u32, + rows_per_strip: u32, + photometric: u16, + compression: u16, + spp: u16, + bps: u16, + sample_format: Option, + orientation: Option, + strips: &[&[u8]], + extra_sample: Option, + ink_set: Option, +) -> Vec { + let n_strips = strips.len(); + assert_eq!(n_strips as u32, h.div_ceil(rows_per_strip)); + let mut entries: Vec<(u16, u16, u32, u32)> = vec![ + (256, 4, 1, w), + (257, 4, 1, h), + (258, 3, u32::from(spp), if spp == 1 { u32::from(bps) } else { 0 }), + (259, 3, 1, u32::from(compression)), + (262, 3, 1, u32::from(photometric)), + (273, 4, n_strips as u32, 0), + (277, 3, 1, u32::from(spp)), + (278, 4, 1, rows_per_strip), + (279, 4, n_strips as u32, 0), + ]; + if let Some(orient) = orientation { + entries.push((274, 3, 1, u32::from(orient))); + } + if let Some(set) = ink_set { + entries.push((332, 3, 1, u32::from(set))); + } + if let Some(es) = extra_sample { + entries.push((338, 3, 1, u32::from(es))); + } + if let Some(fmt) = sample_format { + entries.push((339, 3, 1, u32::from(fmt))); + } + entries.sort_by_key(|e| e.0); + + let ifd_start = 8usize; + let ifd_len = 2 + entries.len() * 12 + 4; + let mut extra_data_off = ifd_start + ifd_len; + let bps_off = extra_data_off; + if spp > 1 { + extra_data_off += usize::from(spp) * 2; + } + let offsets_off = extra_data_off; + if n_strips > 1 { + extra_data_off += n_strips * 4; + } + let counts_off = extra_data_off; + if n_strips > 1 { + extra_data_off += n_strips * 4; + } + + let mut data_off = extra_data_off; + let mut strip_offsets = Vec::with_capacity(n_strips); + let mut strip_counts = Vec::with_capacity(n_strips); + for s in strips { + strip_offsets.push(u32::try_from(data_off).unwrap()); + strip_counts.push(u32::try_from(s.len()).unwrap()); + data_off += s.len(); + } + + for (tag, _, _, val) in &mut entries { + match *tag { + 258 if spp > 1 => *val = bps_off as u32, + 273 => *val = if n_strips == 1 { strip_offsets[0] } else { offsets_off as u32 }, + 279 => *val = if n_strips == 1 { strip_counts[0] } else { counts_off as u32 }, + _ => {} + } + } + + let mut out = Vec::with_capacity(data_off); + out.extend(b"II*\0"); + out.extend(8u32.to_le_bytes()); + out.extend((entries.len() as u16).to_le_bytes()); + for (tag, kind, count, val) in entries { + out.extend(tag.to_le_bytes()); + out.extend(kind.to_le_bytes()); + out.extend(count.to_le_bytes()); + out.extend(val.to_le_bytes()); + } + out.extend(0u32.to_le_bytes()); + if spp > 1 { + for _ in 0..spp { + out.extend(bps.to_le_bytes()); + } + } + if n_strips > 1 { + for o in strip_offsets { + out.extend(o.to_le_bytes()); + } + for c in strip_counts { + out.extend(c.to_le_bytes()); + } + } + for s in strips { + out.extend_from_slice(s); + } + out +} + +#[test] +fn reduced_tiffs_decode_rgb_cmyk_alpha_and_cross_strip_boundaries() { + // 33 × 25 RGB gradient split across 9 strips of 3 rows each (every 8×8 cell crosses strip joins). + let (w, h, rps) = (33u32, 25u32, 3u32); + let mut strips_owned: Vec> = Vec::new(); + for y0 in (0..h).step_by(rps as usize) { + let rows = (h - y0).min(rps); + let mut s = Vec::with_capacity((rows * w * 3) as usize); + for dy in 0..rows { + let y = y0 + dy; + for x in 0..w { + s.extend_from_slice(&[((x * 255) / w) as u8, ((y * 255) / h) as u8, 128]); + } + } + strips_owned.push(s); + } + let refs: Vec<&[u8]> = strips_owned.iter().map(Vec::as_slice).collect(); + let rgb_tiff = custom_striped_tiff(w, h, rps, 2, 1, 3, &refs, None, None); + let full_rgb = decode_rgba(&rgb_tiff).unwrap(); + for (shrink, want_size) in [(1u8, (17, 13)), (2, (9, 7)), (3, (5, 4))] { + let img = decode_rgba_reduced(&rgb_tiff, shrink).unwrap(); + assert_eq!(img.dimensions(), want_size, "RGB shrink {shrink}"); + let est = reduced_estimate(&rgb_tiff, shrink).unwrap(); + assert_eq!((est.0, est.1), want_size); + let step = 1u32 << shrink; + let (mut diff, mut n) = (0u64, 0u64); + for ry in 0..want_size.1 { + for rx in 0..want_size.0 { + let (ux0, ux1) = (rx * step, ((rx + 1) * step).min(w)); + let (uy0, uy1) = (ry * step, ((ry + 1) * step).min(h)); + let mut sum = [0u64; 3]; + let cnt = u64::from((ux1 - ux0) * (uy1 - uy0)); + for y in uy0..uy1 { + for x in ux0..ux1 { + let p = full_rgb.get_pixel(x, y).0; + for c in 0..3 { + sum[c] += u64::from(p[c]); + } + } + } + let got = img.get_pixel(rx, ry).0; + for (c, &s) in sum.iter().enumerate() { + let avg = ((s + cnt / 2) / cnt) as u8; + diff += u64::from(got[c].abs_diff(avg)); + n += 1; + } + assert_eq!(got[3], 255); + } + } + assert!(diff / n <= 1, "RGB shrink {shrink} mean diff {}", diff / n); + } + + // Odd-sized CMYK TIFF via the `tiff` encoder matches `decode_rgba` averaged over each block. + use tiff::encoder::colortype::{CMYK8, CMYKA8}; + let mut cmyk_px = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + cmyk_px.extend_from_slice(&[0, ((x * 255) / w) as u8, ((y * 255) / h) as u8, 20]); + } + } + let cmyk_tiff = tiff_of::(w, h, &cmyk_px, false); + let full_cmyk = decode_rgba(&cmyk_tiff).unwrap(); + let red_cmyk = decode_rgba_reduced(&cmyk_tiff, 2).unwrap(); + assert_eq!(red_cmyk.dimensions(), (9, 7)); + for ry in 0..6 { + for rx in 0..8 { + let p = red_cmyk.get_pixel(rx, ry).0; + let q = full_cmyk.get_pixel(rx * 4 + 2, ry * 4 + 2).0; + for c in 0..4 { + assert!(p[c].abs_diff(q[c]) <= 12, "CMYK ({rx},{ry}) c{c}: {} vs {}", p[c], q[c]); + } + } + } + + // CMYKA with transparent black pixels beside an opaque pixel: alpha-weighted averaging prevents + // transparent pixels from darkening opaque colour. + #[rustfmt::skip] + let cmyka_px: [u8; 4 * 4 * 5] = [ + 0, 255, 255, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, + 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, 0, + 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, + 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 255, + ]; + let cmyka_tiff = tiff_of::(4, 4, &cmyka_px, true); + let reduced_alpha = decode_rgba_reduced(&cmyka_tiff, 1).unwrap(); + assert_eq!(reduced_alpha.dimensions(), (2, 2)); + let opaque_want = decode_rgba(&tiff_of::(1, 1, &[0, 255, 255, 0], false)).unwrap().get_pixel(0, 0).0; + let tl = reduced_alpha.get_pixel(0, 0).0; + assert_eq!(tl[3], 64, "quarter opaque: {tl:?}"); + for c in 0..3 { + assert!(tl[c].abs_diff(opaque_want[c]) <= 1, "no dark bleed in top-left {tl:?} vs {opaque_want:?}"); + } + assert_eq!(reduced_alpha.get_pixel(1, 0).0[3], 0, "fully transparent cell stays alpha 0"); + + // Non-CMYK InkSet (InkSet = 2) is refused just like `decode_cmyk_tiff`. + let spot_cmyk = custom_striped_tiff(4, 4, 4, 5, 1, 4, &[&[0; 64]], None, Some(2)); + assert!(decode_rgba_reduced(&spot_cmyk, 1).is_none()); +} + +/// Oversized multi-strip TIFFs (> 256 MP / 1 GiB RGBA) are refused by `decode_rgba`, yet decode +/// cleanly at reduced proxy resolution via banded streaming (`#2381`). +#[test] +fn oversized_multi_strip_tiff_decodes_at_reduced_size_while_full_decode_is_refused() { + // 65,536 × 4,097 RGBA8 PackBits (~1.0002 GiB RGBA > MAX_RGBA_BYTES, ~16 MiB compressed). + let (w, h, rps) = (65_536u32, 4_097u32, 64u32); + let pb_row = packbits_repeat(w as usize * 4, 200); + let full_strip = pb_row.repeat(rps as usize); + let rem_rows = (h % rps) as usize; + let rem_strip = pb_row.repeat(rem_rows); + let full_strips = (h / rps) as usize; + let mut strips: Vec<&[u8]> = vec![&full_strip; full_strips]; + if rem_rows > 0 { + strips.push(&rem_strip); + } + let big_tiff = custom_striped_tiff(w, h, rps, 2, 32773, 4, &strips, Some(2), None); + + assert_eq!(pixel_size(&big_tiff), Some((w, h))); + assert!(too_large_to_decode(&big_tiff)); + assert!(decode_rgba(&big_tiff).is_none(), "full decode exceeds 1 GiB RGBA limit"); + + let reduced = decode_rgba_reduced(&big_tiff, 3).expect("reduced 1/8 decode succeeds via TiffBands"); + assert_eq!(reduced.dimensions(), (8_192, 513)); + assert_eq!(reduced.get_pixel(0, 0).0, [200, 200, 200, 200]); + assert_eq!(reduced.get_pixel(8_191, 512).0, [200, 200, 200, 200]); + + // A complete PackBits single-strip 1-bit monochrome TIFF works within the 512 MiB band cap, + // and is refused before pixel allocation once its single strip exceeds 512 MiB (~1 MiB file). + let mono_row = packbits_repeat(w as usize / 8, 0); + let small_strip = mono_row.repeat(16); + let small_single = custom_striped_tiff_with(w, 16, 16, 1, 32773, 1, 1, None, None, &[&small_strip], None, None); + let small_out = decode_rgba_reduced(&small_single, 3).expect("16-row 1-bit strip is within 512 MiB cap"); + assert_eq!(small_out.dimensions(), (8_192, 2)); + + let over_h = 8_200u32; // 65,536 × 8,200 = 537.4 MiB > 512 MiB band cap + let over_strip = mono_row.repeat(over_h as usize); + let single_strip_over_band = custom_striped_tiff_with(w, over_h, over_h, 1, 32773, 1, 1, None, None, &[&over_strip], None, None); + assert!(reduced_estimate(&single_strip_over_band, 3).is_none()); + assert!(decode_rgba_reduced(&single_strip_over_band, 3).is_none()); +} + +#[test] +fn reduced_tiff_estimate_counts_orientation_copy_and_float_or_lab_buffers() { + let (w, h) = (16u32, 12u32); + let px_count = (w * h) as usize; + + // Orientation 2..=4 swaps/flips pixels while keeping `bands.dimensions() == pixel_size`, + // adding a full group copy alongside the band during `TiffBands::decode`. + // Orientations 5..=8 swap stored dimensions relative to `pixel_size` and fall back to full decode. + let rgba_raw = vec![120u8; px_count * 4]; + let upright = custom_striped_tiff_with(w, h, h, 2, 1, 4, 8, None, Some(1), &[&rgba_raw], Some(2), None); + let flipped = custom_striped_tiff_with(w, h, h, 2, 1, 4, 8, None, Some(3), &[&rgba_raw], Some(2), None); + let swapped = custom_striped_tiff_with(w, h, h, 2, 1, 4, 8, None, Some(6), &[&rgba_raw], Some(2), None); + let est_upright = reduced_estimate(&upright, 1).unwrap(); + let est_flip = reduced_estimate(&flipped, 1).unwrap(); + assert_eq!((est_upright.0, est_upright.1), (8, 6)); + assert_eq!((est_flip.0, est_flip.1), (8, 6)); + assert_eq!(est_flip.2, est_upright.2 + px_count * 4); + assert_eq!(decode_rgba_reduced(&flipped, 1).unwrap().dimensions(), (8, 6)); + assert!(reduced_estimate(&swapped, 1).is_none()); + assert!(decode_rgba_reduced(&swapped, 1).is_none()); + + // Lab8 and Rgb32F convert through normalized 32-bit float intermediates before U8 output. + let rgb_raw = vec![128u8; px_count * 3]; + let rgb8 = custom_striped_tiff(w, h, h, 2, 1, 3, &[&rgb_raw], None, None); + let lab8 = custom_striped_tiff(w, h, h, 8, 1, 3, &[&rgb_raw], None, None); + let est_rgb8 = reduced_estimate(&rgb8, 1).unwrap(); + let est_lab8 = reduced_estimate(&lab8, 1).unwrap(); + assert_eq!(est_lab8.2 - est_rgb8.2, px_count * (32 - 4)); + assert!(decode_rgba_reduced(&lab8, 1).is_some()); + + let f32_raw: Vec = [0.5f32, 0.25, 0.75].repeat(px_count).into_iter().flat_map(f32::to_le_bytes).collect(); + let rgb32f = custom_striped_tiff_with(w, h, h, 2, 1, 3, 32, Some(3), None, &[&f32_raw], None, None); + let est_f32 = reduced_estimate(&rgb32f, 1).unwrap(); + let partial_16x12 = 32 * (std::mem::size_of::<((u32, u32), ([u32; 4], u32, u16))>() + 1); + assert_eq!(est_f32.2, px_count * 12 + px_count * 32 + partial_16x12 + (8 * 6) * 8); + assert!(decode_rgba_reduced(&rgb32f, 1).is_some()); + + // Multi-strip with Orientation = 3 crossing shrink boundaries still decodes cleanly. + let strip_rows = 3usize; + let strip_bytes = w as usize * strip_rows * 4; + let rgba_strips: Vec<&[u8]> = (0..4).map(|i| &rgba_raw[i * strip_bytes..(i + 1) * strip_bytes]).collect(); + let multi_flip = custom_striped_tiff_with(w, h, strip_rows as u32, 2, 1, 4, 8, None, Some(3), &rgba_strips, Some(2), None); + assert_eq!(decode_rgba_reduced(&multi_flip, 2).unwrap().dimensions(), (4, 3)); + + // Wide 1-row-per-strip grayscale TIFF counts the bounded partial-cell table at shrink = 3. + let wide_w = 262_136u32; + let wide_row = packbits_repeat(wide_w as usize, 180); + let wide_strips = vec![wide_row.as_slice(); 8]; + let wide_tiff = custom_striped_tiff(wide_w, 8, 1, 1, 32773, 1, &wide_strips, None, None); + let est_wide = reduced_estimate(&wide_tiff, 3).unwrap(); + assert_eq!((est_wide.0, est_wide.1), (32_767, 1)); + let min_partial = 65_536 * (std::mem::size_of::<((u32, u32), ([u32; 4], u32, u16))>() + 1); + assert!(est_wide.2 >= min_partial + wide_w as usize * 8 + 32_767 * 8); + assert_eq!(decode_rgba_reduced(&wide_tiff, 3).unwrap().dimensions(), (32_767, 1)); +} + /// Planar CMYK TIFFs and CMYK TIFFs with associated (premultiplied) alpha keep their inks through /// the shared decoder, so the PDF export's RGB fallback is only for other inks and oversized files. #[test] diff --git a/crates/images/src/tiff_reduced.rs b/crates/images/src/tiff_reduced.rs new file mode 100644 index 000000000..06652a3e8 --- /dev/null +++ b/crates/images/src/tiff_reduced.rs @@ -0,0 +1,294 @@ +//! Reduced-size TIFF decoding (1/2, 1/4, 1/8) via banded streaming for screen and link proxies. + +use std::collections::HashMap; + +use craft_image_codecs::{ChannelLayout, CodecError, InkSet, Limits, SampleType, TiffBands}; +use image::RgbaImage; + +use crate::CmykRaster; +use crate::colour::{DisplayColour, Pixels, to_display_rgba}; + +/// Largest `shrink` [`decode_reduced`] accepts: 3, an eighth of each side. +pub(crate) const MAX_SHRINK: u8 = crate::jpeg::MAX_SHRINK; + +/// Most bytes one strip or row of tiles may take while streaming: stops single-strip files +/// larger than this before any pixel buffer is allocated. +const MAX_BAND_BYTES: u64 = 512 << 20; + +/// Classic (`II*\0`, `MM\0*`) or BigTIFF (`II+\0`, `MM\0+`) signature. +pub(crate) fn is_tiff(bytes: &[u8]) -> bool { + matches!(bytes.get(..4), Some(b"II*\0" | b"MM\0*" | b"II+\0" | b"MM\0+")) +} + +fn limits() -> Limits { + Limits { max_alloc: MAX_BAND_BYTES, ..Limits::banded() } +} + +/// False when a Separated TIFF uses a non-CMYK ink set (`InkSet` != 1), matching +/// [`crate::decode_cmyk_tiff`]. +fn supported_ink_set(bytes: &[u8]) -> bool { + !crate::default_tiff_page(bytes).is_some_and(|page| page.photometric == Some(5) && page.ink_set.is_some_and(|set| set != InkSet::Cmyk)) +} + +/// Opens the default TIFF page for banded decoding at `1 / 2^shrink`, enforcing that both the +/// stream bands and the reduced RGBA output stay within budget. +fn open_checked(bytes: &[u8], shrink: u8) -> Option<(TiffBands<'_>, u32, u32)> { + if !is_tiff(bytes) || !(1..=MAX_SHRINK).contains(&shrink) || !supported_ink_set(bytes) { + return None; + } + let (pw, ph) = crate::pixel_size(bytes)?; + let bands = TiffBands::open(bytes, None, &limits()).ok()?.upright(); + if bands.dimensions() != (pw, ph) { + return None; + } + let step = 1u32 << shrink; + let (rw, rh) = (pw.div_ceil(step), ph.div_ceil(step)); + if rw == 0 || rh == 0 || crate::over_rgba_budget(rw, rh) { + return None; + } + Some((bands, rw, rh)) +} + +type PartialCell = ([u32; 4], u32, u16); + +/// Maximum incomplete reduced cells that can coexist in `partial` across sequential full-span +/// [`TiffBands`] callbacks: at most two boundary spans (`2 * max(rw, rh)`, capped at `out_px`). +fn max_partial_cells(rw: u32, rh: u32, out_px: usize) -> Option { + Some(usize::try_from(rw.max(rh)).ok()?.saturating_mul(2).min(out_px)) +} + +/// Worst-case `HashMap` allocation for `cells` live entries (`hashbrown` 7/8 load factor rounded +/// up to a power-of-two bucket table, plus one control byte per bucket). +fn partial_map_bytes(cells: usize) -> usize { + if cells == 0 { + return 0; + } + let min_buckets = cells.saturating_mul(8).div_ceil(7).max(8); + let buckets = min_buckets.checked_next_power_of_two().unwrap_or(min_buckets); + buckets.saturating_mul(std::mem::size_of::<((u32, u32), PartialCell)>() + 1) +} + +/// Reduced `(width, height, estimated_peak_bytes)` for a TIFF at `1 / 2^shrink` without decoding +/// any pixels. `None` when [`decode_reduced`] cannot handle the file. +pub(crate) fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { + let (bands, rw, rh) = open_checked(bytes, shrink)?; + let group = bands.group_bytes().ok()?; + let scratch = usize::try_from(bands.decode_scratch_bytes()).ok()?; + let is_cmyk = bands.layout().is_cmyk(); + let target_layout = if is_cmyk { ChannelLayout::CmykA } else { ChannelLayout::Rgba }; + let out_ch = target_layout.channels(); + let src_ch = bands.layout().channels().max(1); + let src_bpp = src_ch.saturating_mul(bands.sample_type().bytes()).max(1); + let group_px = group / src_bpp; + // Turning bands upright (`Orientation != 1`) copies the whole group inside `TiffBands::decode`. + let orient_copy = if (2..=8).contains(&bands.orientation()) { group } else { 0 }; + // Float and Lab bands convert through normalized 32-bit float intermediates before narrowing to U8. + let is_lab = matches!(bands.layout(), ChannelLayout::Lab | ChannelLayout::LabA); + let is_float = bands.sample_type().is_float(); + let conv_per_px = if bands.layout() == target_layout && bands.sample_type() == SampleType::U8 { + 0 + } else if !is_lab && !is_float { + out_ch + } else if bands.layout() == target_layout { + 4 * src_ch + out_ch + } else { + 4 * src_ch + 4 * out_ch + out_ch + }; + let conv_bytes = group_px.saturating_mul(conv_per_px); + let group_extra = scratch.max(orient_copy).max(conv_bytes); + let band_peak = group.saturating_add(group_extra); + let out_px = usize::try_from(rw).ok()?.checked_mul(usize::try_from(rh).ok()?)?; + let partial_bytes = partial_map_bytes(max_partial_cells(rw, rh, out_px)?); + // Reduced output buffers (CMYK inks + alpha + RGBA display, or RGBA + premultiplied copy). + let out_bytes = out_px.saturating_mul(if is_cmyk { 9 } else { 8 }); + let peak = band_peak.saturating_add(partial_bytes).saturating_add(out_bytes).max(8); + Some((rw, rh, peak)) +} + +struct AccumTarget<'a> { + w: u32, + h: u32, + rw: u32, + shrink: u8, + step: u32, + channels: usize, + max_partial: usize, + pixels_out: &'a mut [u8], + alpha_out: &'a mut [u8], + partial: &'a mut HashMap<(u32, u32), PartialCell>, +} + +fn write_cell(target: &mut AccumTarget<'_>, rx: u32, ry: u32, expected: u16, sums: [u32; 4], sum_a: u32) -> Result<(), CodecError> { + let out_idx = usize::try_from(ry) + .ok() + .and_then(|y| y.checked_mul(usize::try_from(target.rw).ok()?)) + .and_then(|row| row.checked_add(usize::try_from(rx).ok()?)) + .ok_or_else(|| CodecError::LimitExceeded("reduced pixel index out of range".into()))?; + let c_off = out_idx.checked_mul(4).ok_or_else(|| CodecError::LimitExceeded("reduced buffer offset out of range".into()))?; + let dst = target + .pixels_out + .get_mut(c_off..c_off.saturating_add(4)) + .ok_or_else(|| CodecError::InvalidImage("reduced output buffer too small".into()))?; + let exp = u32::from(expected.max(1)); + let out_a = ((sum_a + exp / 2) / exp).min(255) as u8; + for (d, &s) in dst[..target.channels].iter_mut().zip(&sums[..target.channels]) { + *d = (s + sum_a / 2).checked_div(sum_a).map_or(0, |v| v.min(255) as u8); + } + if target.channels == 3 { + dst[3] = out_a; + } else if let Some(a_slot) = target.alpha_out.get_mut(out_idx) { + *a_slot = out_a; + } + Ok(()) +} + +fn accumulate_group(target: &mut AccumTarget<'_>, gx: u32, gy: u32, gw: u32, gh: u32, src: &[u8]) -> Result<(), CodecError> { + if gw == 0 || gh == 0 || gx >= target.w || gy >= target.h { + return Ok(()); + } + let max_x = gx.saturating_add(gw).min(target.w); + let max_y = gy.saturating_add(gh).min(target.h); + let rx_start = gx >> target.shrink; + let rx_end = (max_x - 1) >> target.shrink; + let ry_start = gy >> target.shrink; + let ry_end = (max_y - 1) >> target.shrink; + let gw_usize = usize::try_from(gw).map_err(|_| CodecError::LimitExceeded("group width out of range".into()))?; + let px_stride = target.channels + 1; + + for ry in ry_start..=ry_end { + let uy0 = ry << target.shrink; + let uy1 = uy0.saturating_add(target.step).min(target.h); + let iy0 = uy0.max(gy); + let iy1 = uy1.min(max_y); + for rx in rx_start..=rx_end { + let ux0 = rx << target.shrink; + let ux1 = ux0.saturating_add(target.step).min(target.w); + let ix0 = ux0.max(gx); + let ix1 = ux1.min(max_x); + let expected = + u16::try_from((ux1 - ux0).saturating_mul(uy1 - uy0)).map_err(|_| CodecError::InvalidImage("reduced cell area overflow".into()))?; + let seen = + u16::try_from((ix1 - ix0).saturating_mul(iy1 - iy0)).map_err(|_| CodecError::InvalidImage("reduced overlap area overflow".into()))?; + + let mut sums = [0u32; 4]; + let mut sum_a = 0u32; + let span_px = (ix1 - ix0) as usize; + let x_off = (ix0 - gx) as usize; + for y in iy0..iy1 { + let row_start = ((y - gy) as usize).saturating_mul(gw_usize).saturating_add(x_off).saturating_mul(px_stride); + let span_bytes = span_px.saturating_mul(px_stride); + let row = src + .get(row_start..row_start.saturating_add(span_bytes)) + .ok_or_else(|| CodecError::InvalidImage("TIFF band row truncated".into()))?; + if target.channels == 3 { + for &[r, g, b, a] in row.as_chunks::<4>().0 { + let a = u32::from(a); + sum_a += a; + sums[0] += u32::from(r) * a; + sums[1] += u32::from(g) * a; + sums[2] += u32::from(b) * a; + } + } else { + for &[c, m, y_ink, k, a] in row.as_chunks::<5>().0 { + let a = u32::from(a); + sum_a += a; + sums[0] += u32::from(c) * a; + sums[1] += u32::from(m) * a; + sums[2] += u32::from(y_ink) * a; + sums[3] += u32::from(k) * a; + } + } + } + + if seen == expected { + write_cell(target, rx, ry, expected, sums, sum_a)?; + continue; + } + let cur_len = target.partial.len(); + let entry = match target.partial.entry((rx, ry)) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + if cur_len >= target.max_partial { + return Err(CodecError::LimitExceeded("partial reduced cells exceed boundary span".into())); + } + e.insert(([0u32; 4], 0u32, 0u16)) + } + }; + for (dst_s, s) in entry.0.iter_mut().zip(&sums) { + *dst_s += *s; + } + entry.1 += sum_a; + entry.2 += seen; + if entry.2 >= expected { + let Some((done_sums, done_a, _)) = target.partial.remove(&(rx, ry)) else { + return Err(CodecError::InvalidImage("missing completed reduced cell".into())); + }; + write_cell(target, rx, ry, expected, done_sums, done_a)?; + } + } + } + Ok(()) +} + +/// Decodes a TIFF at `1 / 2^shrink` (`1..=[MAX_SHRINK]`, each side rounded up) by streaming +/// strip/tile groups through [`TiffBands`] and averaging directly into the reduced display buffer, +/// applying the embedded ICC profile or active working CMYK profile just like [`crate::decode_rgba`]. +pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option { + let (mut bands, rw, rh) = open_checked(bytes, shrink)?; + let (w, h) = bands.dimensions(); + let step = 1u32 << shrink; + let is_cmyk = bands.layout().is_cmyk(); + let is_gray = bands.layout().is_gray(); + + let out_px = usize::try_from(rw).ok()?.checked_mul(usize::try_from(rh).ok()?)?; + let rgba_len = out_px.checked_mul(4)?; + let mut pixels_out = Vec::new(); + pixels_out.try_reserve_exact(rgba_len).ok()?; + pixels_out.resize(rgba_len, 0); + + let mut alpha_out = Vec::new(); + if is_cmyk { + alpha_out.try_reserve_exact(out_px).ok()?; + alpha_out.resize(out_px, 255); + } + + let max_partial = max_partial_cells(rw, rh, out_px)?; + let mut partial = HashMap::new(); + let target_layout = if is_cmyk { ChannelLayout::CmykA } else { ChannelLayout::Rgba }; + let mut target = AccumTarget { + w, + h, + rw, + shrink, + step, + channels: if is_cmyk { 4 } else { 3 }, + max_partial, + pixels_out: &mut pixels_out, + alpha_out: &mut alpha_out, + partial: &mut partial, + }; + + bands + .decode::(|gx, gy, group| { + let (gw, gh) = group.dimensions(); + let converted = group.converted(target_layout, SampleType::U8); + let src = converted.as_u8().ok_or_else(|| CodecError::InvalidImage("converted TIFF band is not 8-bit".into()))?; + accumulate_group(&mut target, gx, gy, gw, gh, src) + }) + .ok()?; + + if !partial.is_empty() { + return None; + } + + let icc = bands.icc.take(); + if is_cmyk { + let alpha = alpha_out.iter().any(|&a| a < 255).then_some(alpha_out); + let raster = CmykRaster { width: rw, height: rh, cmyk: pixels_out, alpha }; + return to_display_rgba(Pixels::Cmyk(raster), icc.as_deref(), &DisplayColour::active()); + } + let rgba = RgbaImage::from_raw(rw, rh, pixels_out)?; + let Some(icc) = icc.as_deref() else { return Some(rgba) }; + let px = if is_gray { Pixels::Gray(rgba) } else { Pixels::Rgb(rgba) }; + to_display_rgba(px, Some(icc), &DisplayColour::active()) +} diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 07719bf41..ff2dcc61b 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -77,7 +77,7 @@ pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { premultiplied(img.width(), img.height(), img.into_raw()) } -/// [`decode_pixmap`] of a JPEG at 1/2^`shrink` of its size, `shrink` 1 to +/// [`decode_pixmap`] of a JPEG or TIFF at 1/2^`shrink` of its size, `shrink` 1 to /// [`designcraft_images::MAX_REDUCED_SHRINK`], without a full-size decode. `None` where only a /// full decode applies (other formats, CMYK JPEGs). pub(crate) fn decode_pixmap_reduced(bytes: &[u8], shrink: u8) -> Option { diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4fd49d66b..3acf3e379 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -324,6 +324,27 @@ pub fn decoded(data: &AssetData, page: u32) -> Option> { Some(pm) } +/// Maximum RGBA byte size accepted for a decoded `Pixmap` (`1 GiB`). +const MAX_PIXMAP_BYTES: u64 = 1 << 30; + +/// Smallest mip level of `size` whose reduced decoder dimensions (each side rounded up) fit in +/// `Pixmap` (`u16::MAX` a side) and within `1 GiB` of RGBA. Returns `0` for ordinary sizes and +/// `>= 1` for oversized rasters so zoom-in clamps to a reduced decode instead of hitting +/// [`decode_full`]. +fn finest_level(size: (u32, u32)) -> u8 { + let fits = |(w, h): (u32, u32)| { + w <= u32::from(u16::MAX) && h <= u32::from(u16::MAX) && u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) <= MAX_PIXMAP_BYTES + }; + let mut cur = size; + for level in 0..MAX_LEVEL { + if fits(cur) { + return level; + } + cur = (cur.0.div_ceil(2), cur.1.div_ceil(2)); + } + MAX_LEVEL +} + /// The mip level of an image `size` pixels at full resolution closest above `on_screen` device /// pixels per point when drawn `width_pt` points wide. fn level_for(size: (u32, u32), width_pt: f64, on_screen: f64) -> u8 { @@ -334,7 +355,7 @@ fn level_for(size: (u32, u32), width_pt: f64, on_screen: f64) -> u8 { w = (w / 2).max(1); h = (h / 2).max(1); } - level + level.max(finest_level(size)) } /// `size` halved `times` times, as [`halve`] does. @@ -868,23 +889,18 @@ pub(crate) struct Want { pub on_screen: f64, } -/// Dimensions of the JPEG mip level selected for a request. `None` means the request uses the -/// full decode or is not an eligible JPEG, so warming must reserve its full decode size. +/// Dimensions of each mip level selected for a reduced-decode request. `None` means the request +/// uses the full decode or is not an eligible JPEG/TIFF, so warming must reserve its full size. fn reduced_sizes(bytes: &[u8], page: u32, width_pt: f64, on_screen: f64) -> Option> { - if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + if page != 0 || !designcraft_images::supports_reduced_decode(bytes) { return None; } - let (mut w, mut h) = crate::image_size(bytes)?; - let ppt = w as f64 / width_pt.max(1e-6); - let mut sizes = vec![(w, h)]; - while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { - (w, h) = ((w / 2).max(1), (h / 2).max(1)); - sizes.push((w, h)); - } - Some(sizes) + let size = crate::image_size(bytes)?; + let level = level_for(size, width_pt, on_screen); + Some((0..=level).map(|l| halved(size, l)).collect()) } -/// Cache and peak decode estimates for a group of requests that all use reduced JPEG mips. +/// Cache and peak decode estimates for a group of requests that all use reduced mips. fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { let mut dims = None; let mut levels = [false; 9]; @@ -897,7 +913,7 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (_, _, decode_peak) = designcraft_images::reduced_jpeg_estimate(&bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_estimate(&bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } @@ -1011,8 +1027,8 @@ fn failed(c: &Cache, k: &(SourceKey, u32), generation: u64) -> bool { } /// What decoding the drawings `wanted` of the asset `key` adds to the cache and holds at its -/// peak, and whether that is their reduced JPEG estimate (else a full decode's, which keeps only -/// the levels drawn). +/// peak, and whether that is their reduced JPEG/TIFF estimate (else a full decode's, which keeps +/// only the levels drawn). fn estimate(key: (SourceKey, u32), wanted: &[Want], levels: &DrawnLevels) -> (usize, usize, bool) { fault(key.0); if let Some((size, decoding)) = reduced_estimates(wanted) { @@ -1035,9 +1051,9 @@ fn estimate(key: (SourceKey, u32), wanted: &[Want], levels: &DrawnLevels) -> (us /// of everything else cached. An asset some drawing of which finds no level to draw is not held: /// it is decoded again, and the cached levels its decode estimate covers count with that /// estimate, not with everything else. The estimate of an asset in `reduced` covers the levels -/// from the one read from the JPEG blocks to each one drawn, as [`reduced_estimates`] counts -/// them; a full decode's covers the levels drawn. The levels of the assets in `index` become the -/// most recently used, so later stores evict other images first. +/// from the one read by the reduced JPEG or TIFF decoder to each one drawn, as [`reduced_estimates`] +/// counts them; a full decode's covers the levels drawn. The levels of the assets in `index` become +/// the most recently used, so later stores evict other images first. fn held_in_view( c: &mut Cache, index: &HashMap<(SourceKey, u32), usize>, @@ -1191,16 +1207,16 @@ fn waited(id: SourceKey) { WAITED.1.notify_all(); } -/// Level `level` of a JPEG for [`mip`], decoded at 1/2, 1/4 or 1/8 of its size straight from -/// its blocks and halved from there, so a screen-sized level needs no full-size decode. `None` -/// when the full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). +/// Level `level` of a JPEG or TIFF for [`mip`], decoded at 1/2, 1/4 or 1/8 of its size without a +/// full-size decode and halved from there. `None` when the full size is drawn, for other formats, +/// and for variants only a full decode reads (CMYK JPEGs, non-CMYK separated TIFFs). /// /// `gate`: wait at [`GATE`] for the decode's peak bytes, plus the encoded bytes it holds. fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option, colour: u64) -> Option> { if level == 0 || page != 0 { return None; } - if !bytes.starts_with(&[0xFF, 0xD8]) { + if !designcraft_images::supports_reduced_decode(bytes) { return None; } let shrink = level.min(designcraft_images::MAX_REDUCED_SHRINK); @@ -1210,10 +1226,10 @@ fn reduced(id: SourceKey, bytes: &[u8], page: u32, level: u8, gate: Option { - let (_, _, peak) = designcraft_images::reduced_jpeg_estimate(bytes, shrink)?; + let (_, _, peak) = designcraft_images::reduced_estimate(bytes, shrink)?; Some(reserve((peak.saturating_mul(3) / 2).saturating_add(held), id, None)) } None => None, @@ -1543,6 +1559,124 @@ pub(crate) mod tests { assert!(mip(&bytes, 0, 256.0, 0.1).is_none()); } + pub(crate) fn packbits_gray_tiff_rect(w: u32, h: u32, rows_per_strip: u32, val: u8) -> Vec { + let mut row = Vec::new(); + let mut left = w as usize; + while left >= 128 { + row.push(129); + row.push(val); + left -= 128; + } + if left > 1 { + row.push((1 - left as isize) as u8); + row.push(val); + } else if left == 1 { + row.push(0); + row.push(val); + } + + let n_strips = h.div_ceil(rows_per_strip) as usize; + let entries_count = 9usize; + let offsets_off = 8 + 2 + entries_count * 12 + 4; + let counts_off = offsets_off + n_strips * 4; + let mut data_off = counts_off + n_strips * 4; + let full_strip = row.repeat(rows_per_strip as usize); + let rem_rows = (h % rows_per_strip) as usize; + let rem_strip = row.repeat(rem_rows); + + let mut offsets = Vec::with_capacity(n_strips); + let mut counts = Vec::with_capacity(n_strips); + for i in 0..n_strips { + let len = if rem_rows > 0 && i + 1 == n_strips { rem_strip.len() } else { full_strip.len() }; + offsets.push(data_off as u32); + counts.push(len as u32); + data_off += len; + } + + let tags: [(u16, u16, u32, u32); 9] = [ + (256, 4, 1, w), + (257, 4, 1, h), + (258, 3, 1, 8), + (259, 3, 1, 32773), + (262, 3, 1, 1), + (273, 4, n_strips as u32, offsets_off as u32), + (277, 3, 1, 1), + (278, 4, 1, rows_per_strip), + (279, 4, n_strips as u32, counts_off as u32), + ]; + + let mut out = Vec::with_capacity(data_off); + out.extend(b"II*\0"); + out.extend(8u32.to_le_bytes()); + out.extend((tags.len() as u16).to_le_bytes()); + for (tag, kind, count, value) in tags { + out.extend(tag.to_le_bytes()); + out.extend(kind.to_le_bytes()); + out.extend(count.to_le_bytes()); + out.extend(value.to_le_bytes()); + } + out.extend(0u32.to_le_bytes()); + for o in offsets { + out.extend(o.to_le_bytes()); + } + for c in counts { + out.extend(c.to_le_bytes()); + } + for i in 0..n_strips { + if rem_rows > 0 && i + 1 == n_strips { + out.extend_from_slice(&rem_strip); + } else { + out.extend_from_slice(&full_strip); + } + } + out + } + + fn tiff(w: u32, h: u32) -> AssetData { + let img = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 255 / w) as u8, (y * 255 / h) as u8, 128])); + let mut out = std::io::Cursor::new(Vec::new()); + image::DynamicImage::ImageRgb8(img).write_to(&mut out, image::ImageFormat::Tiff).unwrap(); + AssetData::embedded(out.into_inner()) + } + + #[test] + fn screen_levels_of_a_tiff_and_oversized_tiff_need_no_full_size_decode() { + let bytes = tiff(1024, 768); + let id = bytes.key(); + let pm = mip(&bytes, 0, 1024.0, 0.1).unwrap(); + assert_eq!((pm.width(), pm.height()), (128, 96)); + assert!(lookup((id, 0, 0)).is_none(), "no full-size decode is kept"); + let small = mip(&bytes, 0, 1024.0, 0.02).unwrap(); + assert_eq!((small.width(), small.height()), (64, 48)); + assert!(lookup((id, 0, 0)).is_none(), "coarser mip is halved without decoding full size"); + + let want = Want { bytes: bytes.clone(), page: 0, width_pt: 1024.0, on_screen: 0.1 }; + let (cached, peak) = reduced_estimates(&[want]).unwrap(); + let full = decode_sizes(&bytes.load().unwrap(), 0); + assert!(cached < full.0 && peak < full.1, "reduced estimates {cached}/{peak}, full {full:?}"); + + // Print-scale rasters past 1 GiB RGBA clamp their finest mip level above 0 so zoom-in + // stays on the reduced decode path instead of falling back to `decode_full`. + assert_eq!(finest_level((23_800, 15_840)), 1); + assert_eq!(level_for((23_800, 15_840), 1000.0, 50.0), 1); + assert_eq!(finest_level((131_070, 128)), 1); + assert_eq!(finest_level((131_071, 128)), 2); + assert_eq!(finest_level((32_768, 32_769)), 2); + + let over_1gib = AssetData::embedded(packbits_gray_tiff_rect(65_536, 4_097, 256, 160)); + assert!(designcraft_images::too_large_to_decode(&over_1gib.load().unwrap())); + let want_big = Want { bytes: over_1gib, page: 0, width_pt: 1000.0, on_screen: 0.5 }; + assert!(reduced_estimates(&[want_big]).is_some()); + + let wide = AssetData::embedded(packbits_gray_tiff_rect(131_071, 32, 8, 170)); + assert!(crate::decode_pixmap(&wide.load().unwrap()).is_none(), "131071px side exceeds full Pixmap limit"); + let wide_pm = mip(&wide, 0, 1000.0, 50.0).expect("131071x32 TIFF clamps to level 2 instead of failing"); + assert!(!is_bad(wide.key(), 0)); + assert_eq!((wide_pm.width(), wide_pm.height()), (32_767, 8)); + let p = wide_pm.data()[usize::from(wide_pm.width()) + 100]; + assert_eq!([p.r, p.g, p.b, p.a], [170, 170, 170, 255]); + } + fn png_sized(w: u32, h: u32) -> AssetData { let img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 100, 50, 255])); let mut out = std::io::Cursor::new(Vec::new()); diff --git a/crates/render/src/proxy.rs b/crates/render/src/proxy.rs index 43e346a12..290f0f427 100644 --- a/crates/render/src/proxy.rs +++ b/crates/render/src/proxy.rs @@ -54,9 +54,9 @@ pub fn make_proxy(bytes: &[u8], page: u32) -> Option { None } -/// Decode `bytes`, through the reduced JPEG decode when it still leaves at least [`MAX_SIDE_PX`]. +/// Decode `bytes`, through reduced decoding when it still leaves at least [`MAX_SIDE_PX`]. fn decode_for_proxy(bytes: &[u8], page: u32) -> Option { - if page == 0 && bytes.starts_with(&[0xFF, 0xD8]) { + if page == 0 && designcraft_images::supports_reduced_decode(bytes) { let (w, h) = image_size(bytes)?; let long = w.max(h); let mut shrink = 0u8; @@ -214,4 +214,14 @@ mod tests { assert!(p.pixels.0.max(p.pixels.1) <= MAX_SIDE_PX && p.pixels.1 > p.pixels.0); assert!(p.data.len() <= MAX_BYTES); } + + #[test] + fn oversized_tiff_builds_proxy_without_full_decode() { + let tiff = crate::images::tests::packbits_gray_tiff_rect(65_536, 64, 16, 180); + assert!(crate::decode_pixmap(&tiff).is_none(), "65536px width exceeds full Pixmap limit"); + let p = make_proxy(&tiff, 0).expect("proxy generated via reduced banded TIFF decode"); + assert_eq!(p.mime, "image/jpeg"); + assert_eq!(p.pixels, (MAX_SIDE_PX, 1)); + assert!(p.data.len() <= MAX_BYTES); + } }