From 65ca7c1bbdbf44f2359bd4957e53d8b4e2d12242 Mon Sep 17 00:00:00 2001 From: Omar Saidahmed Date: Thu, 15 Oct 2026 09:00:20 -0400 Subject: [PATCH 01/27] remove unused deps and dead code --- Cargo.lock | 4 -- apps/photocraft/src/services.rs | 68 +------------------ .../photocraft/src/services/recovery_tests.rs | 3 +- crates/automation/Cargo.toml | 1 - crates/automation/src/server.rs | 2 +- crates/engine/src/float_cmds.rs | 2 +- crates/testkit/Cargo.toml | 3 - 7 files changed, 6 insertions(+), 77 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b3a268add9..0807a9f377 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4690,7 +4690,6 @@ dependencies = [ "photocraft-doc", "photocraft-engine", "photocraft-format", - "photocraft-geom", "photocraft-io", "rmcp", "schemars", @@ -4979,9 +4978,6 @@ name = "photocraft-testkit" version = "0.9.0" dependencies = [ "memory-stats", - "photocraft-color", - "photocraft-geom", - "photocraft-raster", "serde_json", ] diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 9de1c475ea..09714a4ae4 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -1,10 +1,8 @@ //! Native platform services: file dialogs (rfd), filesystem, codecs. -use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType as CS}; -use photocraft_color::{ColorMode, SampleType}; -use photocraft_doc::{Document, Layer, Size}; +use photocraft_codecs::{ChannelLayout, EncodeOptions, Image}; +use photocraft_doc::Document; use photocraft_format::RecoveryStore; -use photocraft_geom::Rect; use photocraft_ui_egui::{FileDialogAnswer, FileDialogReply, FileDialogRequest, Recoverable, Services}; use std::cell::RefCell; use std::future::Future; @@ -515,68 +513,6 @@ fn platform_beep() { } } -/// Flat-image import via photocraft-codecs (kept for reference/tests; the app uses photocraft-io). -#[allow(dead_code)] -pub fn import_flat(name: &str, bytes: &[u8]) -> Result { - let img = photocraft_codecs::decode(bytes).map_err(|e| e.to_string())?; - let (w, h) = (img.width(), img.height()); - let depth = match img.sample_type() { - CS::U8 => SampleType::U8, - CS::U16 => SampleType::U16, - _ => SampleType::F32, - }; - let gray = matches!(img.layout(), ChannelLayout::Gray | ChannelLayout::GrayA); - let cmyk = matches!(img.layout(), ChannelLayout::Cmyk | ChannelLayout::CmykA); - let mode = if gray { - ColorMode::Grayscale - } else if cmyk { - ColorMode::Cmyk - } else { - ColorMode::Rgb - }; - let target = match mode { - ColorMode::Grayscale => ChannelLayout::GrayA, - ColorMode::Cmyk => ChannelLayout::CmykA, - _ => ChannelLayout::Rgba, - }; - let sample = match depth { - SampleType::U8 => CS::U8, - SampleType::U16 => CS::U16, - SampleType::F32 => CS::F32, - }; - let conv = img.convert(target, sample); - let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or(name.to_string()); - let mut doc = Document::new(stem, Size::new(w, h), mode, depth); - doc.icc_profile = img.icc.clone().map(std::sync::Arc::new); - if let Some((x, _)) = img.meta.dpi { - doc.resolution_dpi = x; - } - let mut layer = Layer::raster("Background", doc.pixel_format()); - let data = conv.to_normalized(); - layer.surface_mut().ok_or("new raster layer has no pixels")?.write_region(Rect::from_xywh(0, 0, w, h), &data); - doc.layers.push(layer); - Ok(doc) -} - -#[allow(dead_code)] -pub fn export_flat(doc: &Document, path: &str) -> Result, String> { - let format = photocraft_codecs::from_extension(path).ok_or_else(|| format!("unknown file type for {path}"))?; - let buf = photocraft_compose::flatten(doc); - let (w, h) = (buf.rect.width(), buf.rect.height()); - let data: Vec = buf.px.iter().flat_map(|p| *p).collect(); - let img = match doc.depth { - SampleType::U8 => Image::from_u8(w, h, ChannelLayout::Rgba, buf.to_rgba8().pixels), - SampleType::U16 => Image::from_u16(w, h, ChannelLayout::Rgba, &data.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect::>()), - SampleType::F32 => Image::from_f32(w, h, ChannelLayout::Rgba, &data), - } - .map_err(|e| e.to_string())?; - let img = match &doc.icc_profile { - Some(icc) if doc.mode == ColorMode::Rgb => img.with_icc(Some((**icc).clone())), - _ => img, - }; - photocraft_codecs::encode(&img, format, &EncodeOptions::default()).map_err(|e| e.to_string()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/apps/photocraft/src/services/recovery_tests.rs b/apps/photocraft/src/services/recovery_tests.rs index b1bd2d51c0..23191ed7f9 100644 --- a/apps/photocraft/src/services/recovery_tests.rs +++ b/apps/photocraft/src/services/recovery_tests.rs @@ -1,5 +1,6 @@ use super::*; -use photocraft_color::Color; +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Size; use photocraft_format::{Autosaver, RecoveryEntry, SaveOptions, list_recovery}; use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 0738140a41..574ad1250c 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -10,7 +10,6 @@ rust-version.workspace = true workspace = true [dependencies] -photocraft-geom = { workspace = true } photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-codecs = { workspace = true } diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f223bc5109..e93566cbc3 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -1174,7 +1174,7 @@ mod tests { break; } assert!(t.elapsed().as_secs() < 60, "doc_inspect never saw the finished job: {inspected}"); - std::thread::sleep(std::time::Duration::from_millis(5)); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; } } } diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rs index e5450b2339..09aff81b7e 100644 --- a/crates/engine/src/float_cmds.rs +++ b/crates/engine/src/float_cmds.rs @@ -218,7 +218,7 @@ pub(crate) fn before_command(s: &mut Session, id: &str) -> Result> return Ok(None); } match id { - "edit.undo" | "edit.stepBackward" => { + "edit.undo" => { st.floating = None; Ok(Some(json!({"floating": "returned"}))) } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 0d69300d90..80e533935b 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,9 +8,6 @@ license.workspace = true workspace = true [dependencies] -photocraft-geom = { workspace = true } -photocraft-color = { workspace = true } -photocraft-raster = { workspace = true } serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] From 6f2abe20fca3c35d39b81b3a4de2aba11c28803b Mon Sep 17 00:00:00 2001 From: cortezsilvano-bot <250676892+cortezsilvano-bot@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:14:47 -0500 Subject: [PATCH 02/27] =?UTF-8?q?Print:=20Functions=20=E2=80=BA=20Bleed=20?= =?UTF-8?q?(corner=20crop=20marks=20on=20the=20trim=20line)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Photoshop's Print dialog has Functions › Bleed: crop marks print inside the image by the bleed width, so trimming on them cuts through the artwork and leaves no paper-white sliver. target-app-parity listed it as missing ("No Separations/bleed"). - file.print / file.printOneCopy take "bleed" in inches (default 0), report it back, and Print One Copy remembers it. - Corner crop marks move onto the trim line, still starting 6 pt outside the image. Centre and registration marks are unchanged (a symmetric bleed doesn't move the midlines). - One helper (corner_crop_segments) drives both the PDF writer and the native Windows primitives; the dialog preview draws the marks there too. - Negative, non-numeric or too-wide bleeds are BadParams, never a panic; bleed without corner crop marks changes nothing and reports 0. - With bleed absent or 0 the PDF is byte-identical (tested). The Print dialog field is a follow-up: every tl! label needs all translations. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/print_cmds.rs | 50 ++++++++++--- crates/engine/src/print_cmds/tests.rs | 71 +++++++++++++++++++ crates/engine/src/print_cmds/windows_marks.rs | 24 +++++-- crates/ui-egui/src/file_ui.rs | 6 +- docs/target-app-parity.md | 5 +- 5 files changed, 138 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9a0af4a054..29de3e57f0 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -61,6 +61,27 @@ pub struct Marks { pub corner_crop: bool, pub center_crop: bool, pub registration: bool, + /// Photoshop's Functions › Bleed, in points: corner crop marks sit this far inside the image + /// edge, so the trim cuts through the image and leaves no paper-white sliver. 0 = on the edge. + pub bleed: f64, +} + +/// Gap between the image edge and a crop mark, and the mark's length (pt). +const MARK_GAP: f64 = 6.0; +const MARK_LEN: f64 = 18.0; + +/// Corner crop marks around `(x, y, w, h)` as eight `(from, to)` segments, a horizontal then a +/// vertical one per corner. Each starts `MARK_GAP` outside the image (so it never prints on it) +/// and lies on the trim line, `bleed` inside the edge. The inset is symmetric, so this holds for +/// both bottom-up (PDF) and top-down (Windows) coordinates. +fn corner_crop_segments(bleed: f64, (x, y, w, h): (f64, f64, f64, f64)) -> [((f64, f64), (f64, f64)); 8] { + let mut out = [((0.0, 0.0), (0.0, 0.0)); 8]; + for (i, (cx, cy, dx, dy)) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)].into_iter().enumerate() { + let (tx, ty) = (cx - dx * bleed, cy - dy * bleed); + out[2 * i] = ((cx + dx * MARK_GAP, ty), (cx + dx * (MARK_GAP + MARK_LEN), ty)); + out[2 * i + 1] = ((tx, cy + dy * MARK_GAP), (tx, cy + dy * (MARK_GAP + MARK_LEN))); + } + out } /// One page: paper (pt), image box (pt, origin bottom-left), marks and texts. @@ -102,12 +123,11 @@ fn deflate(data: &[u8]) -> Vec { /// Vector marks around `(x, y, w, h)`. fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { let mut s = String::from("q 0 G 0.3 w\n"); - let (gap, len) = (6.0, 18.0); + let (gap, len) = (MARK_GAP, MARK_LEN); let line = |s: &mut String, x0: f64, y0: f64, x1: f64, y1: f64| s.push_str(&format!("{x0:.2} {y0:.2} m {x1:.2} {y1:.2} l S\n")); if m.corner_crop { - for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] { - line(&mut s, cx + dx * gap, cy, cx + dx * (gap + len), cy); - line(&mut s, cx, cy + dy * gap, cx, cy + dy * (gap + len)); + for ((x0, y0), (x1, y1)) in corner_crop_segments(m.bleed, (x, y, w, h)) { + line(&mut s, x0, y0, x1, y1); } } if m.center_crop { @@ -303,10 +323,16 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result { let (pw, ph) = paper(p, cmd)?; let dpi = f64::from(doc.resolution_dpi.max(1.0)); let (iw, ih) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); - let marks = Marks { + // Bleed in inches, like Photoshop's Position fields; the marks need it in points. + let bleed = match p.get("bleed") { + None | Some(Value::Null) => 0.0, + Some(v) => v.as_f64().filter(|b| b.is_finite() && *b >= 0.0).ok_or_else(|| bad(cmd, "bleed is a width in inches, 0 or more"))? * 72.0, + }; + let mut marks = Marks { corner_crop: p.get("cornerCropMarks").and_then(Value::as_bool).unwrap_or(false), center_crop: p.get("centerCropMarks").and_then(Value::as_bool).unwrap_or(false), registration: p.get("registrationMarks").and_then(Value::as_bool).unwrap_or(false), + bleed, }; let margin = if marks.corner_crop || marks.center_crop || marks.registration { 36.0 } else { 18.0 }; let fit = p.get("scaleToFit").and_then(Value::as_bool).unwrap_or(false); @@ -316,6 +342,14 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result { p.get("scale").and_then(Value::as_f64).filter(|v| *v > 0.0).unwrap_or(100.0) / 100.0 }; let (w, h) = (iw * scale, ih * scale); + // The trim box must keep some area, or the marks of opposite corners would cross. + if 2.0 * marks.bleed >= w.min(h) { + return Err(bad(cmd, format!("bleed {:.3} in leaves no image inside the trim ({:.2} × {:.2} in printed)", marks.bleed / 72.0, w / 72.0, h / 72.0))); + } + // Bleed only moves crop marks; without them it has nothing to change. + if !marks.corner_crop { + marks.bleed = 0.0; + } let center = p.get("center").and_then(Value::as_bool).unwrap_or(true); let (x, y) = if center { ((pw - w) / 2.0, (ph - h) / 2.0) @@ -398,7 +432,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { require_printing_enabled()?; let printed = print_windows(&page, p, &doc.name, copies)?; return Ok(json!({ - "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, + "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "bleed": marks.bleed / 72.0, "scale": scale * 100.0, "copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color, })); } @@ -431,7 +465,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { sent = true; } Ok( - json!({"pdf": pdf_path, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "color": color}), + json!({"pdf": pdf_path, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "bleed": marks.bleed / 72.0, "scale": scale * 100.0, "copies": copies, "command": command, "sent": sent, "spooler": spool, "color": color}), ) } @@ -750,7 +784,7 @@ pub fn specs() -> Vec { CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } }; } - const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##; + const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"bleed":in=0 (Functions › Bleed: corner crop marks this far inside the image edge, on the trim line),"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##; vec![ spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print), diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index d012f6de41..f3d1fc3fe3 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -434,3 +434,74 @@ fn printers_lists_the_spooler_destinations_without_a_document() { None => assert!(list.iter().all(|p| p["default"] == false)), } } + +/// A dry-run print to `name`.pdf with `extra` params; returns the result and the PDF content stream. +fn print_with(s: &mut Session, dir: &str, name: &str, extra: Value) -> (Value, Vec) { + let mut p = json!({"output": format!("{dir}/{name}.pdf"), "dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.print", p).unwrap(); + let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap(); + (r, pdf) +} + +#[test] +fn zero_bleed_prints_exactly_as_before() { + let mut s = session("rgb", 8); + let dir = tmp("bleed-zero"); + let (plain, a) = print_with(&mut s, &dir, "plain", json!({"cornerCropMarks": true})); + let (zero, b) = print_with(&mut s, &dir, "zero", json!({"cornerCropMarks": true, "bleed": 0.0})); + assert_eq!(a, b, "bleed 0 must not change a single byte"); + assert_eq!(plain["bleed"], 0.0); + assert_eq!(zero["bleed"], 0.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bleed_puts_corner_crop_marks_on_the_trim_line_outside_the_image() { + let mut s = session("rgb", 8); + let dir = tmp("bleed"); + let (r, pdf) = print_with(&mut s, &dir, "bleed", json!({"cornerCropMarks": true, "centerCropMarks": true, "bleed": 0.125})); + assert_eq!(r["bleed"], 0.125); + let rect: Vec = r["imageRect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]); + let c = pdf_content(&pdf); + // Bottom-left corner (PDF is bottom-up): the horizontal mark runs left from 6 pt outside the + // image, 9 pt (0.125 in) above the image's bottom edge; the vertical one 9 pt right of its left edge. + assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x - 6.0, y + 9.0, x - 24.0, y + 9.0)), "{c}"); + assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + 9.0, y - 6.0, x + 9.0, y - 24.0)), "{c}"); + // Top-right corner, mirrored. + assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w + 6.0, y + h - 9.0, x + w + 24.0, y + h - 9.0)), "{c}"); + assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w - 9.0, y + h + 6.0, x + w - 9.0, y + h + 24.0)), "{c}"); + // Centre crop marks are on the midlines, which a symmetric bleed does not move. + assert!(c.contains(&format!("{:.2} {:.2} m {:.2} {:.2} l S", x + w / 2.0, y - 6.0, x + w / 2.0, y - 24.0)), "{c}"); + // Print One Copy repeats the last print, bleed included. + let again = s.execute("file.printOneCopy", json!({"output": format!("{dir}/again.pdf"), "dryRun": true})).unwrap(); + assert_eq!(again["bleed"], 0.125); + // The image box itself is unchanged: bleed moves marks, not pixels. + let (plain, _) = print_with(&mut s, &dir, "plain", json!({"cornerCropMarks": true})); + assert_eq!(plain["imageRect"], r["imageRect"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bleed_without_corner_crop_marks_changes_nothing() { + let mut s = session("rgb", 8); + let dir = tmp("bleed-nomarks"); + let (_, a) = print_with(&mut s, &dir, "plain", json!({"registrationMarks": true})); + let (r, b) = print_with(&mut s, &dir, "bleed", json!({"registrationMarks": true, "bleed": 0.1})); + assert_eq!(a, b); + assert_eq!(r["bleed"], 0.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_bleed_is_an_error_not_a_panic() { + let mut s = session("rgb", 8); + // The test document prints 300 × 150 pt, so 1.05 in (75.6 pt) leaves no trim box. + for bleed in [json!(-0.1), json!("0.1"), json!(true), json!([0.1]), json!(1.05), json!(1e308)] { + let r = s.execute("file.print", json!({"dryRun": true, "send": false, "output": "", "cornerCropMarks": true, "bleed": bleed})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "bleed {bleed}: {r:?}"); + } +} diff --git a/crates/engine/src/print_cmds/windows_marks.rs b/crates/engine/src/print_cmds/windows_marks.rs index 857e6335a9..b78d4234b9 100644 --- a/crates/engine/src/print_cmds/windows_marks.rs +++ b/crates/engine/src/print_cmds/windows_marks.rs @@ -1,5 +1,5 @@ //! App-owned print-mark composition in points from the sheet's top-left. -use super::Marks; +use super::{MARK_GAP, MARK_LEN, Marks, corner_crop_segments}; use craft_print::rgb::{Primitive, Shape}; pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Vec { @@ -7,11 +7,10 @@ pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Ve let line = |out: &mut Vec, x0, y0, x1, y1| { out.push(Primitive { shape: Shape::Line { from: (x0, y0), to: (x1, y1) }, width: 0.3, color: [0; 3] }); }; - let (gap, len) = (6.0, 18.0); + let (gap, len) = (MARK_GAP, MARK_LEN); if marks.corner_crop { - for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] { - line(&mut out, cx + dx * gap, cy, cx + dx * (gap + len), cy); - line(&mut out, cx, cy + dy * gap, cx, cy + dy * (gap + len)); + for ((x0, y0), (x1, y1)) in corner_crop_segments(marks.bleed, (x, y, w, h)) { + line(&mut out, x0, y0, x1, y1); } } if marks.center_crop { @@ -37,11 +36,24 @@ mod tests { use super::*; #[test] fn marks_surround_the_final_image_box_in_physical_points() { - let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true }, (100.0, 200.0, 144.0, 72.0)); + let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true, bleed: 0.0 }, (100.0, 200.0, 144.0, 72.0)); assert_eq!(out.len(), 24); assert_eq!(out[0].shape, Shape::Line { from: (94.0, 200.0), to: (76.0, 200.0) }); assert_eq!(out[12].shape, Shape::Ellipse { bounds: (167.0, 180.0, 10.0, 10.0) }); assert!(out.iter().all(|p| p.width == 0.3 && p.color == [0; 3])); assert!(primitives(Marks::default(), (0.0, 0.0, 10.0, 10.0)).is_empty()); } + + #[test] + fn bleed_moves_corner_crop_marks_onto_the_trim_line_in_top_down_coordinates() { + let rect = (100.0, 200.0, 144.0, 72.0); + let out = primitives(Marks { corner_crop: true, bleed: 9.0, ..Marks::default() }, rect); + assert_eq!(out.len(), 8); + // Top-left corner: still outside the image, but on the trim line 9 pt in (y down here). + assert_eq!(out[0].shape, Shape::Line { from: (94.0, 209.0), to: (76.0, 209.0) }); + assert_eq!(out[1].shape, Shape::Line { from: (109.0, 194.0), to: (109.0, 176.0) }); + // Bottom-right corner, mirrored. + assert_eq!(out[6].shape, Shape::Line { from: (250.0, 263.0), to: (268.0, 263.0) }); + assert_eq!(out[7].shape, Shape::Line { from: (235.0, 278.0), to: (235.0, 296.0) }); + } } diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 3f87f6339c..aebd7ca18a 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -921,11 +921,13 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (Print › Functions › Bleed through `file.print`; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -286,7 +286,7 @@ just presence. | Transform, warp, puppet, perspective, liquify | ~88% | No Face-Aware Liquify (needs a landmark model) | | Automation: CLI, MCP, headless server, control channel | ~95% | Ahead of Photoshop here (see below) | | Image modes (RGB/Gray/CMYK/Lab/Indexed/Duotone/Multichannel) | ~85% | Multichannel display-only; no ink-plate model | -| Print / export / Save for Web / slices / Generator | ~85% | No Separations/bleed; droplets basic | +| Print / export / Save for Web / slices / Generator | ~85% | No Separations; Bleed only through `file.print` (no Print dialog field yet); droplets basic | | Computational photo (Photomerge, HDR, Lens, Camera Raw, Wide Angle) | ~70% | Classical implementations; generic lens profiles only | | Data-driven graphics (Variables, Data Sets) | ~0% | Not started (5 menu items) | | Video / Timeline / animation | ~0% | Not started (13 menu items) — a whole subsystem | @@ -565,6 +565,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Print: Functions › Bleed (`file.print` / `file.printOneCopy` `bleed`, corner crop marks on the trim line, PDF and Windows paths); the Print dialog field is still missing; percentages unchanged | | 2026-10-13 | minor | Vector shapes: on-canvas corner radius widgets on live rectangles (TOOL-214-12); estimates unchanged | | 2026-10-13 | minor | Stale "missing tool" rows corrected against main: Color Replacement (`paint.colorReplacement`), Red Eye (`paint.redEye`) and Add/Delete Anchor Point (the Pen flyout) are live toolbar tools and Frame landed, so Art History Brush is the only tool still missing; percentages unchanged | | 2026-10-12 | minor | Free Transform options bar H/V skew fields; percentages unchanged | From 708d393988f7108ea5d68b9c08e4c7be2b0e904d Mon Sep 17 00:00:00 2001 From: LochLogic <252105752+LochLogic@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:24:07 -0600 Subject: [PATCH 03/27] Tests: every GPU test holds gpu_lock (STATUS_ACCESS_VIOLATION on Windows) testkit::gpu_lock documents that WARP faults in d3d10warp.dll when two GPU harnesses render in parallel in one test process, and that every test that builds a GPU harness or device holds the lock. Fifteen tests didn't, so on Windows checker_canvas and marquee_autoscroll (and the lib test binary's GPU tests) could take their whole test binary down with STATUS_ACCESS_VIOLATION. They now take the lock on their first line, as the others do. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/clipping_indicator_tests.rs | 1 + crates/ui-egui/src/gpu_canvas_mip_tests.rs | 1 + crates/ui-egui/src/navigator_gpu_tests.rs | 1 + crates/ui-egui/src/panel_docking_tests.rs | 3 +++ crates/ui-egui/src/type_tool_tests.rs | 1 + crates/ui-egui/tests/adjust_preview_gpu.rs | 2 ++ crates/ui-egui/tests/checker_canvas.rs | 1 + crates/ui-egui/tests/layout_perf.rs | 1 + crates/ui-egui/tests/marquee_autoscroll.rs | 3 +++ crates/ui-egui/tests/pattern_preview_canvas.rs | 1 + 10 files changed, 15 insertions(+) diff --git a/crates/ui-egui/src/clipping_indicator_tests.rs b/crates/ui-egui/src/clipping_indicator_tests.rs index 9bfb600b6f..7395a533de 100644 --- a/crates/ui-egui/src/clipping_indicator_tests.rs +++ b/crates/ui-egui/src/clipping_indicator_tests.rs @@ -83,6 +83,7 @@ fn alt_click_clipping_still_creates_releases_and_undoes_without_moving_rows() { #[test] #[ignore = "writes synthetic English Layers-panel screenshots for before/after inspection"] fn write_clipping_indicator_preview() { + let _gpu = photocraft_testkit::gpu_lock(); let output = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../plan/evidence/clipping"); std::fs::create_dir_all(&output).unwrap(); for theme in crate::theme::ThemeKind::ALL { diff --git a/crates/ui-egui/src/gpu_canvas_mip_tests.rs b/crates/ui-egui/src/gpu_canvas_mip_tests.rs index a1c3e8ee14..82e911bae9 100644 --- a/crates/ui-egui/src/gpu_canvas_mip_tests.rs +++ b/crates/ui-egui/src/gpu_canvas_mip_tests.rs @@ -51,6 +51,7 @@ fn read_mips(gpu: &GpuCanvas, key: u64) -> Vec> { #[test] fn canvas_mips_preserve_opaque_pixels_and_partial_updates() { + let _gpu = photocraft_testkit::gpu_lock(); let rs = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| egui_kittest::wgpu::create_render_state(wgpu_setup(), Default::default()))); let Ok(rs) = rs else { eprintln!("skipping mip readback: no GPU adapter"); diff --git a/crates/ui-egui/src/navigator_gpu_tests.rs b/crates/ui-egui/src/navigator_gpu_tests.rs index 51326597f4..d2342d17ac 100644 --- a/crates/ui-egui/src/navigator_gpu_tests.rs +++ b/crates/ui-egui/src/navigator_gpu_tests.rs @@ -47,6 +47,7 @@ fn near(a: [u8; 4], b: [u8; 3]) -> bool { #[test] fn navigator_draws_the_gpu_canvas_texture_and_follows_edits() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(8); if !h.state().perf.gpu { diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rs index c6feeff633..a4ae378eda 100644 --- a/crates/ui-egui/src/panel_docking_tests.rs +++ b/crates/ui-egui/src/panel_docking_tests.rs @@ -175,6 +175,7 @@ fn shared_layout_keeps_panel_identity_across_themes_and_respects_workspace_lock( /// Explicit offscreen evidence; this creates no native windows. #[test] fn capture_custom_panel_docking_visual_fixtures() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(directory) = std::env::var_os("CRAFT_UI_DOCKING_FIXTURES").map(std::path::PathBuf::from) else { return }; std::fs::create_dir_all(&directory).unwrap(); for theme in crate::theme::ThemeKind::ALL { @@ -211,6 +212,7 @@ fn capture_custom_panel_docking_visual_fixtures() { #[test] fn floating_group_titles_are_opaque_in_studio_themes() { + let _gpu = photocraft_testkit::gpu_lock(); // Studio's tab strip is transparent over the dock's card; a floating group must not show the canvas (#4509). let mut app = app(); app.run("window.panel.float", json!({"panel":"swatches","x":40,"y":60,"width":300,"height":300})).unwrap(); @@ -346,6 +348,7 @@ fn splitting_a_short_column_keeps_the_layers_footer_visible_and_usable() { #[test] fn populated_canvas_keeps_a_real_opacity_edit_after_floating_and_redocking() { + let _gpu = photocraft_testkit::gpu_lock(); let mut app = app(); app.ui.theme = crate::theme::ThemeKind::Studio; app.run("file.new", json!({"width":480,"height":360})).unwrap(); diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool_tests.rs index c7b54c8871..7a23c9ccc3 100644 --- a/crates/ui-egui/src/type_tool_tests.rs +++ b/crates/ui-egui/src/type_tool_tests.rs @@ -1130,6 +1130,7 @@ fn temporary_type_transform_captures_press_and_rejects_collapsed_geometry() { #[test] #[ignore = "writes visual evidence to target/issue-1091; run explicitly for visual QA"] fn temporary_type_transform_visual_evidence() { + let _gpu = photocraft_testkit::gpu_lock(); let out = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/issue-1091"); std::fs::create_dir_all(&out).unwrap(); for (index, theme) in crate::theme::ThemeKind::ALL.into_iter().enumerate() { diff --git a/crates/ui-egui/tests/adjust_preview_gpu.rs b/crates/ui-egui/tests/adjust_preview_gpu.rs index 82d47596fc..c7104f72ee 100644 --- a/crates/ui-egui/tests/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/adjust_preview_gpu.rs @@ -126,6 +126,7 @@ fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]], skip: usize) -> f32 { #[test] fn preview_layer_composites_on_the_gpu_like_the_command() { + let _gpu = photocraft_testkit::gpu_lock(); let Some((device, queue, mut comp)) = gpu() else { return }; // GPU vs CPU of the same document (as the compositor parity tests), and GPU preview vs the // command's CPU result (adds the command's rounding to the layer depth). @@ -170,6 +171,7 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { /// The zoomed-out proxy preview (own document and layer ids) composites on the GPU like the CPU. #[test] fn proxy_preview_composites_on_the_gpu() { + let _gpu = photocraft_testkit::gpu_lock(); use photocraft_ui_egui::adjust_preview::{base_document, proxy_base, proxy_with_settings}; let Some((device, queue, mut comp)) = gpu() else { return }; for selection in [false, true] { diff --git a/crates/ui-egui/tests/checker_canvas.rs b/crates/ui-egui/tests/checker_canvas.rs index e626b42128..3c5e061afd 100644 --- a/crates/ui-egui/tests/checker_canvas.rs +++ b/crates/ui-egui/tests/checker_canvas.rs @@ -278,6 +278,7 @@ fn grid_line_contrast_over_grey(h: &mut Harness, grey: u8) -> i32 { #[test] fn pixel_grid_does_not_flip_colour_across_mid_tones() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; h.run_steps(4); // 0x87 and 0x90 sit either side of luma 0.55, where the line used to switch from a full white diff --git a/crates/ui-egui/tests/layout_perf.rs b/crates/ui-egui/tests/layout_perf.rs index fb17833e18..1afb0f36cf 100644 --- a/crates/ui-egui/tests/layout_perf.rs +++ b/crates/ui-egui/tests/layout_perf.rs @@ -220,6 +220,7 @@ fn the_move_preview_is_what_the_move_commits() { #[test] fn layout_document_composites_on_the_gpu_like_the_cpu() { + let _gpu = photocraft_testkit::gpu_lock(); use eframe::wgpu; fn block_on(f: F) -> F::Output { let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); diff --git a/crates/ui-egui/tests/marquee_autoscroll.rs b/crates/ui-egui/tests/marquee_autoscroll.rs index 2fc5772604..ab5b6f6bb5 100644 --- a/crates/ui-egui/tests/marquee_autoscroll.rs +++ b/crates/ui-egui/tests/marquee_autoscroll.rs @@ -82,6 +82,7 @@ fn selection(h: &Harness) -> Option<[i32; 4]> { #[test] fn marquee_dragged_past_the_right_edge_scrolls_and_selects_beyond_the_view() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; setup(&mut h, "rectMarquee"); let start = xf(&h); @@ -121,6 +122,7 @@ fn marquee_dragged_past_the_right_edge_scrolls_and_selects_beyond_the_view() { #[test] fn a_drag_inside_the_canvas_does_not_scroll() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; setup(&mut h, "rectMarquee"); let start = xf(&h); @@ -139,6 +141,7 @@ fn a_drag_inside_the_canvas_does_not_scroll() { #[test] fn rotated_marquee_scrolls_on_the_axis_that_is_visibly_clipped() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness_with_size(egui::vec2(1200.0, 640.0)) else { return }; setup(&mut h, "rectMarquee"); let rect = xf(&h).rect; diff --git a/crates/ui-egui/tests/pattern_preview_canvas.rs b/crates/ui-egui/tests/pattern_preview_canvas.rs index 627bbddaa2..aef11c00dd 100644 --- a/crates/ui-egui/tests/pattern_preview_canvas.rs +++ b/crates/ui-egui/tests/pattern_preview_canvas.rs @@ -52,6 +52,7 @@ fn near(a: [u8; 3], b: [u8; 3]) -> bool { #[test] fn pattern_preview_repeats_the_document_on_gpu_and_cpu_canvases() { + let _gpu = photocraft_testkit::gpu_lock(); let Some(mut h) = harness() else { return }; let app = h.state_mut(); app.run("file.new", json!({"width": 200, "height": 100, "mode": "rgb", "depth": 8})).expect("new"); From 2a9973f9a52631bf8917cc608b0a493434b32a7e Mon Sep 17 00:00:00 2001 From: aqibmohd271 <188757755+aqibmohd271@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:49:07 +0400 Subject: [PATCH 04/27] fix(print): preserve WinAnsi characters in PDF labels --- contributors/people.toml | 3 ++ crates/engine/src/print_cmds.rs | 45 ++++++++++++++++++++++++--- crates/engine/src/print_cmds/tests.rs | 27 ++++++++++++++++ 3 files changed, 70 insertions(+), 5 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 8694c72698..3ae5dc9208 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -162,3 +162,6 @@ sync_github_name = true [people.sidney] real_name = "Sidney Markowitz" sync_github_name = true + +[people.aqibmohd271] +sync_github_name = true diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9a0af4a054..2681854b41 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -76,16 +76,51 @@ pub struct PrintPage { pub emulsion_down: bool, } +// ISO 32000-1, Annex D.2: the standard Helvetica font below uses WinAnsiEncoding, +// not UTF-8. Escape non-ASCII bytes as three octal digits so the content stays ASCII +// and a following digit cannot become part of the escape. Other scripts still need +// an embedded font; retain the existing '?' fallback for unsupported characters. fn pdf_string(s: &str) -> String { let mut o = String::from("("); for c in s.chars() { - match c { - '(' | ')' | '\\' => { + let byte = match c { + '\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => c as u8, + '€' => 0x80, + '‚' => 0x82, + 'ƒ' => 0x83, + '„' => 0x84, + '…' => 0x85, + '†' => 0x86, + '‡' => 0x87, + 'ˆ' => 0x88, + '‰' => 0x89, + 'Š' => 0x8a, + '‹' => 0x8b, + 'Œ' => 0x8c, + 'Ž' => 0x8e, + '‘' => 0x91, + '’' => 0x92, + '“' => 0x93, + '”' => 0x94, + '•' => 0x95, + '–' => 0x96, + '—' => 0x97, + '˜' => 0x98, + '™' => 0x99, + 'š' => 0x9a, + '›' => 0x9b, + 'œ' => 0x9c, + 'ž' => 0x9e, + 'Ÿ' => 0x9f, + _ => b'?', + }; + match byte { + b'(' | b')' | b'\\' => { o.push('\\'); - o.push(c); + o.push(char::from(byte)); } - c if c.is_ascii() && !c.is_ascii_control() => o.push(c), - _ => o.push('?'), + 0x80..=0xff => o.push_str(&format!("\\{byte:03o}")), + _ => o.push(char::from(byte)), } } o.push(')'); diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index d012f6de41..8a9480422c 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -434,3 +434,30 @@ fn printers_lists_the_spooler_destinations_without_a_document() { None => assert!(list.iter().all(|p| p["default"] == false)), } } + +#[test] +fn print_strings_keep_winansi_accents_and_punctuation() { + assert_eq!(pdf_string("Café – résumé"), r"(Caf\351 \226 r\351sum\351)"); + assert_eq!(pdf_string("€ ‘quote’ “double” • Œœ Šš Žž Ÿ"), r"(\200 \221quote\222 \223double\224 \225 \214\234 \212\232 \216\236 \237)"); + assert_eq!(pdf_string("é7"), r"(\3517)", "octal escapes must have three digits before a digit"); +} + +#[test] +fn print_strings_keep_pdf_delimiters_safe_and_fallback_bounded() { + assert_eq!(pdf_string(r"a(b)\c"), r"(a\(b\)\\c)"); + assert_eq!(pdf_string("\n\r\t\0\u{7f}\u{81}中😀"), "(????????)"); + assert_eq!(pdf_string(""), "()"); +} + +#[test] +fn printed_pdf_uses_winansi_for_labels_and_descriptions() { + let mut page = page_of(3, vec![255; 6], false); + page.label = Some("Café – résumé.psd".into()); + page.description = Some("Price: €20 (proof)".into()); + let pdf = print_pdf(&page); + assert!(String::from_utf8_lossy(&pdf).contains("/Encoding /WinAnsiEncoding")); + let content = pdf_content(&pdf); + assert!(content.contains(r"(Caf\351 \226 r\351sum\351.psd) Tj"), "{content}"); + assert!(content.contains(r"(Price: \20020 \(proof\)) Tj"), "{content}"); + assert!(content.is_ascii(), "encoded bytes are escaped, never UTF-8 text operands"); +} From a465fd2b1c9a1dd3867c8499168553c4796fae5d Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 17 Oct 2026 19:06:54 -0700 Subject: [PATCH 05/27] A second launch that sets only environment overrides keeps its own process PHOTOCRAFT_PRESENT_MODE, PHOTOCRAFT_FRAME_LATENCY, PHOTOCRAFT_STROKE_TRACE, PHOTOCRAFT_IN_WINDOW_MENUS and the two automation roots are documented as the equivalent of the per-launch flags, and a per-launch flag makes a launch keep its own process. A launch that sets only variables left launch_options empty, so it handed its files to the running instance (or merely raised its window) and exited before any override was read. Those variables now count as the flags they stand for; empty and 0 mean off, as with PHOTOCRAFT_NEW_INSTANCE. Test: each variable maps to its flag, a value that means off maps to nothing, and skip_reason names the flag. --- apps/photocraft/src/main.rs | 4 ++ apps/photocraft/src/single_instance.rs | 53 +++++++++++++++++++++++++- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 05355e55bf..8d51aa651f 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -369,6 +369,10 @@ fn main() -> eframe::Result { #[cfg(not(target_os = "macos"))] let single_instance = { let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok(); + // A variable documented as the equivalent of a per-launch flag counts as that flag: a + // launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it + // keeps its own process instead of handing its files over and being ignored. + launch_options.extend_from_slice(&single_instance::env_launch_options()); let context = single_instance::LaunchContext { per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform, new_instance_flag: new_instance, diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index d2cd65c678..d607e231e0 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -82,10 +82,35 @@ pub struct LaunchContext<'a> { pub control: bool, /// Paths that aren't valid Unicode: this launch reports them. pub unreadable_paths: bool, - /// Options that only apply to the process they're given to (`--safe-gpu`, …). + /// Options that only apply to the process they're given to (`--safe-gpu`, …), including the + /// ones this launch's environment sets (see [`env_launch_options`]). pub launch_options: &'a [&'static str], } +/// Variables documented as the equivalent of a per-launch flag, each with the flag it stands for +/// (`PHOTOCRAFT_PRESENT_MODE` is `--present-mode`). Setting one asks for the same thing as giving +/// the flag, so it belongs to this process alone. +const ENV_LAUNCH_OPTIONS: [(&str, &str); 6] = [ + ("PHOTOCRAFT_PRESENT_MODE", "--present-mode"), + ("PHOTOCRAFT_FRAME_LATENCY", "--frame-latency"), + ("PHOTOCRAFT_STROKE_TRACE", "--stroke-trace"), + ("PHOTOCRAFT_IN_WINDOW_MENUS", "--in-window-menus"), + ("PHOTOCRAFT_AUTOMATION_READ_ROOT", "--automation-read-root"), + ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "--automation-write-root"), +]; + +/// The per-process options this launch's environment sets, named as the flags they stand for. A +/// launch that sets only variables would otherwise hand its files to the running instance, which +/// never sees the override, and exit. Empty and `0` mean off, as with `PHOTOCRAFT_NEW_INSTANCE`. +pub fn env_launch_options() -> Vec<&'static str> { + env_launch_options_from(|name| std::env::var_os(name)) +} + +/// [`env_launch_options`] with the reader given, so the rule is testable without the environment. +fn env_launch_options_from(get: impl Fn(&str) -> Option) -> Vec<&'static str> { + ENV_LAUNCH_OPTIONS.iter().filter(|(name, _)| get(name).is_some_and(|v| !v.is_empty() && v != "0")).map(|(_, flag)| *flag).collect() +} + /// Why this launch runs as its own instance, or `None` to take part in single-instance. pub fn skip_reason(c: &LaunchContext) -> Option { if !c.per_user_settings { @@ -645,4 +670,30 @@ mod tests { let reason = skip_reason(&LaunchContext { launch_options: &["--safe-gpu"], ..base }); assert!(reason.is_some_and(|r| r.contains("--safe-gpu"))); } + + /// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch + /// that sets only variables has per-process options, so it keeps its own process rather than + /// handing its files to the running instance, which never sees the override. + #[test] + fn an_environment_override_counts_as_a_process_option() { + let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into())); + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec!["--present-mode"]); + assert_eq!( + with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]), + vec!["--stroke-trace", "--automation-write-root"] + ); + // Nothing set, or a value that means off (`0`, empty), is an ordinary launch. + assert!(with(&[]).is_empty()); + assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "0"), ("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); + let base = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &[], + }; + let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base }); + assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}"); + } } From b5fb2fde62138023becdd6b685f389da3f6cacd3 Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 17 Oct 2026 20:07:00 -0700 Subject: [PATCH 06/27] single_instance: each environment override is off the way it is read --- apps/photocraft/src/single_instance.rs | 67 +++++++++++++++++++++----- 1 file changed, 55 insertions(+), 12 deletions(-) diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index d607e231e0..a42c2120fd 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -88,27 +88,61 @@ pub struct LaunchContext<'a> { } /// Variables documented as the equivalent of a per-launch flag, each with the flag it stands for -/// (`PHOTOCRAFT_PRESENT_MODE` is `--present-mode`). Setting one asks for the same thing as giving -/// the flag, so it belongs to this process alone. -const ENV_LAUNCH_OPTIONS: [(&str, &str); 6] = [ - ("PHOTOCRAFT_PRESENT_MODE", "--present-mode"), - ("PHOTOCRAFT_FRAME_LATENCY", "--frame-latency"), - ("PHOTOCRAFT_STROKE_TRACE", "--stroke-trace"), - ("PHOTOCRAFT_IN_WINDOW_MENUS", "--in-window-menus"), - ("PHOTOCRAFT_AUTOMATION_READ_ROOT", "--automation-read-root"), - ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "--automation-write-root"), +/// (`PHOTOCRAFT_PRESENT_MODE` is `--present-mode`) and the rule that says whether its value asks for +/// that option at all. Setting one asks for the same thing as giving the flag, so it belongs to this +/// process alone. +const ENV_LAUNCH_OPTIONS: [(&str, &str, ValueRule); 6] = [ + ("PHOTOCRAFT_PRESENT_MODE", "--present-mode", present_mode_is_on), + ("PHOTOCRAFT_FRAME_LATENCY", "--frame-latency", frame_latency_is_on), + ("PHOTOCRAFT_STROKE_TRACE", "--stroke-trace", stroke_trace_is_on), + ("PHOTOCRAFT_IN_WINDOW_MENUS", "--in-window-menus", flag_is_on), + ("PHOTOCRAFT_AUTOMATION_READ_ROOT", "--automation-read-root", path_is_set), + ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "--automation-write-root", path_is_set), ]; +/// Whether a variable's value asks this launch for its own option. Each rule matches how that +/// variable is read where it takes effect, so a value ignored there keeps no process here either. +type ValueRule = fn(&str) -> bool; + +/// A value `presentation::parse` accepts: it warns and ignores the rest, so an unrecognised +/// `PHOTOCRAFT_PRESENT_MODE` changes nothing and so needs no process of its own. +fn present_mode_is_on(value: &str) -> bool { + !value.trim().is_empty() && crate::presentation::parse(Some(value.trim()), None).0.mode.is_some() +} + +/// [`present_mode_is_on`] for `PHOTOCRAFT_FRAME_LATENCY`, which takes `1` to `3`. +fn frame_latency_is_on(value: &str) -> bool { + !value.trim().is_empty() && crate::presentation::parse(None, Some(value.trim())).0.latency.is_some() +} + +/// Anything except `""`, `0`, `off` and `false`, which is how `StrokeTrace::from_value` reads it: the +/// rest is a stderr summary or a CSV path. +fn stroke_trace_is_on(value: &str) -> bool { + !matches!(value.trim(), "" | "0" | "off" | "false") +} + +/// Any value except empty and `0`, as `main.rs` reads `PHOTOCRAFT_IN_WINDOW_MENUS` - which is why +/// `off` means on there, and why this rule is not shared with the stroke trace above. +fn flag_is_on(value: &str) -> bool { + let value = value.trim(); + !value.is_empty() && value != "0" +} + +/// A path is an option; an empty value is no path. Not trimmed: a path may end in a space. +fn path_is_set(value: &str) -> bool { + !value.is_empty() +} + /// The per-process options this launch's environment sets, named as the flags they stand for. A /// launch that sets only variables would otherwise hand its files to the running instance, which -/// never sees the override, and exit. Empty and `0` mean off, as with `PHOTOCRAFT_NEW_INSTANCE`. +/// never sees the override, and exit. pub fn env_launch_options() -> Vec<&'static str> { env_launch_options_from(|name| std::env::var_os(name)) } /// [`env_launch_options`] with the reader given, so the rule is testable without the environment. fn env_launch_options_from(get: impl Fn(&str) -> Option) -> Vec<&'static str> { - ENV_LAUNCH_OPTIONS.iter().filter(|(name, _)| get(name).is_some_and(|v| !v.is_empty() && v != "0")).map(|(_, flag)| *flag).collect() + ENV_LAUNCH_OPTIONS.iter().filter(|(name, _, is_on)| get(name).is_some_and(|v| is_on(&v.to_string_lossy()))).map(|(_, flag, _)| *flag).collect() } /// Why this launch runs as its own instance, or `None` to take part in single-instance. @@ -682,9 +716,18 @@ mod tests { with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]), vec!["--stroke-trace", "--automation-write-root"] ); - // Nothing set, or a value that means off (`0`, empty), is an ordinary launch. + // Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way + // it is read where it takes effect, not by one rule shared across all six. assert!(with(&[]).is_empty()); assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "0"), ("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); + // The trace is off at `off` and `false` as well, and a value the presentation parser rejects + // is ignored there, so neither keeps a process of its own here. + assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); + assert!(with(&[("PHOTOCRAFT_AUTOMATION_READ_ROOT", "")]).is_empty()); + // Spaces are not part of a value, except in a path, where they can be. + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec!["--present-mode", "--stroke-trace"]); + // `PHOTOCRAFT_IN_WINDOW_MENUS=off` means menus in the window there, so it means it here too. + assert_eq!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "off")]), vec!["--in-window-menus"]); let base = LaunchContext { per_user_settings: true, new_instance_flag: false, From d3d1506e13e37fd363304a5fa4f2337dbfe7770d Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 17 Oct 2026 20:16:25 -0700 Subject: [PATCH 07/27] single_instance: the menu override is on and off exactly as main.rs reads it --- apps/photocraft/src/single_instance.rs | 29 +++++++++++++++++--------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index a42c2120fd..ad893bd58a 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -104,31 +104,33 @@ const ENV_LAUNCH_OPTIONS: [(&str, &str, ValueRule); 6] = [ /// variable is read where it takes effect, so a value ignored there keeps no process here either. type ValueRule = fn(&str) -> bool; -/// A value `presentation::parse` accepts: it warns and ignores the rest, so an unrecognised -/// `PHOTOCRAFT_PRESENT_MODE` changes nothing and so needs no process of its own. +/// A value `presentation::parse` accepts, handed over as written: it trims, treats empty as unset and +/// warns and ignores anything it does not recognise, so an unrecognised `PHOTOCRAFT_PRESENT_MODE` +/// changes nothing there and so needs no process of its own here. fn present_mode_is_on(value: &str) -> bool { - !value.trim().is_empty() && crate::presentation::parse(Some(value.trim()), None).0.mode.is_some() + crate::presentation::parse(Some(value), None).0.mode.is_some() } /// [`present_mode_is_on`] for `PHOTOCRAFT_FRAME_LATENCY`, which takes `1` to `3`. fn frame_latency_is_on(value: &str) -> bool { - !value.trim().is_empty() && crate::presentation::parse(None, Some(value.trim())).0.latency.is_some() + crate::presentation::parse(None, Some(value)).0.latency.is_some() } /// Anything except `""`, `0`, `off` and `false`, which is how `StrokeTrace::from_value` reads it: the -/// rest is a stderr summary or a CSV path. +/// rest is a stderr summary or a CSV path. It trims, so `" 0 "` is off there and off here. fn stroke_trace_is_on(value: &str) -> bool { !matches!(value.trim(), "" | "0" | "off" | "false") } -/// Any value except empty and `0`, as `main.rs` reads `PHOTOCRAFT_IN_WINDOW_MENUS` - which is why -/// `off` means on there, and why this rule is not shared with the stroke trace above. +/// Any value except empty and exactly `0`, as `main.rs` reads `PHOTOCRAFT_IN_WINDOW_MENUS` - which is +/// why `off` means on there, why this rule is not shared with the stroke trace above, and why it does +/// not trim: a padded `" 0 "` enables the menus there, so it keeps a process here too. fn flag_is_on(value: &str) -> bool { - let value = value.trim(); !value.is_empty() && value != "0" } -/// A path is an option; an empty value is no path. Not trimmed: a path may end in a space. +/// A path is an option; an empty value is no path. Not trimmed: a path may end in a space. An empty +/// root is read as no root unless `--control` is given, and that flag keeps its own process already. fn path_is_set(value: &str) -> bool { !value.is_empty() } @@ -724,8 +726,15 @@ mod tests { // is ignored there, so neither keeps a process of its own here. assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); assert!(with(&[("PHOTOCRAFT_AUTOMATION_READ_ROOT", "")]).is_empty()); - // Spaces are not part of a value, except in a path, where they can be. + // Spaces are part of the value only where the reader keeps them: the trace and the two + // presentation values are trimmed where they take effect, the menu flag and a path are not. assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec!["--present-mode", "--stroke-trace"]); + assert_eq!( + with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", " 0 "), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", " /tmp/out ")]), + vec!["--in-window-menus", "--automation-write-root"] + ); + // A whitespace-only menu value is not empty, so it enables the menus there and here too. + assert_eq!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", " ")]), vec!["--in-window-menus"]); // `PHOTOCRAFT_IN_WINDOW_MENUS=off` means menus in the window there, so it means it here too. assert_eq!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "off")]), vec!["--in-window-menus"]); let base = LaunchContext { From a1c9743eacbeb28a10ecac71f5eb9d00907452b1 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 18 Oct 2026 13:09:47 -0700 Subject: [PATCH 08/27] launch args: the environment overrides fold into launch_options again #6499 moved the argument parsing into parse_launch_args, and main() now destructures the result without mut, so the line that folds the PHOTOCRAFT_* overrides into launch_options fails with E0596. One mut on that field; nothing else in the change moves. --- apps/photocraft/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 8796620d58..d4f47c1b39 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -496,7 +496,7 @@ fn main() -> eframe::Result { unreadable_paths, safe_gpu, new_instance, - launch_options, + mut launch_options, present_mode_arg, frame_latency_arg, stroke_trace_arg, From 84df1468d89fe9ad4a15e5596eeb41a376ac8217 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 18 Oct 2026 13:55:31 -0700 Subject: [PATCH 09/27] launch args: keep the `mut` off macOS builds CodeRabbit on #7242: the LaunchArgs destructuring asked for a mutable launch_options, but the only mutation happens inside the cfg(not(target_os = "macos")) block, so a macOS build warns about an unused mut. The binding is made mutable inside that block instead, where the fold happens. No behaviour change on any platform; upstream CI has no macOS leg, so this is warning hygiene, not a CI fix. --- apps/photocraft/src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index d4f47c1b39..4a9a11b9d0 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -496,7 +496,7 @@ fn main() -> eframe::Result { unreadable_paths, safe_gpu, new_instance, - mut launch_options, + launch_options, present_mode_arg, frame_latency_arg, stroke_trace_arg, @@ -525,6 +525,9 @@ fn main() -> eframe::Result { // A variable documented as the equivalent of a per-launch flag counts as that flag: a // launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it // keeps its own process instead of handing its files over and being ignored. + // Folded in here, inside the block that only non-macOS builds compile, so the binding + // above keeps its `mut` off macOS, where nothing is folded in. + let mut launch_options = launch_options; launch_options.extend_from_slice(&single_instance::env_launch_options()); let context = single_instance::LaunchContext { per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform, From ababe94f2333bca5ac5cc39e8ecee5d274df3319 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 11:20:45 -0700 Subject: [PATCH 10/27] Print: an IPv6 print server is parsed as a host, not split on its last colon Endpoint::parse split the server string on its last ':', which is wrong for an IPv6 literal: "::1" became host ":" on port 1, and "[::1]:631" kept its brackets inside the host, which to_socket_addrs cannot resolve on Linux or macOS. An IPv6 CUPS endpoint was therefore always refused by detect(), even when CUPS was listening on it. A bracketed server now takes its host from inside the brackets and its port from after them. A bare address with more than one ':' is the host with the default port, because its last ':' cannot be told apart from a port separator; a zone id (fe80::1%eth0) carries no ':', so a port can still follow it. host:port, a bare host and a socket path are unchanged. Test: "::1", "[::1]", "[::1]:631", "[fe80::1]:6310", "fe80::1%eth0:631", and the cases that already worked. Fail before, pass after. --- crates/ipp/src/lib.rs | 17 +++++++++++++++-- crates/ipp/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index 9f1209df45..fd9eda8065 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -111,12 +111,25 @@ impl Endpoint { .find(Endpoint::reachable) } - /// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). + /// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). An IPv6 + /// server is `[address]` or `[address]:port`; written bare (more than one `:`) it keeps the + /// default port, because its last `:` cannot be told apart from a port separator. pub fn parse(server: &str) -> Endpoint { if server.starts_with('/') { return Endpoint::Unix(PathBuf::from(server)); } - let (host, port) = server.rsplit_once(':').and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631)); + // `[IPv6]:port` - the brackets tell the address from the port, and are not part of the host. + if let Some(rest) = server.strip_prefix('[') + && let Some((host, tail)) = rest.split_once(']') + { + let port = tail.strip_prefix(':').and_then(|p| p.parse().ok()).unwrap_or(631); + return Endpoint::Tcp(host.to_string(), port); + } + // A bare IPv6 literal has more than one ':', so splitting on the last one would cut the + // address in half: it is the host, and the port stays the default. A zone id (`fe80::1%eth0`) + // carries no ':', so there a port can still follow the address. + let host_port = if server.matches(':').count() > 1 && !server.contains('%') { None } else { server.rsplit_once(':') }; + let (host, port) = host_port.and_then(|(h, p)| p.parse().ok().map(|p| (h.to_string(), p))).unwrap_or((server.to_string(), 631)); Endpoint::Tcp(host, port) } diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index ff3ccb6a49..ce895d81c8 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -232,6 +232,25 @@ fn the_unix_socket_endpoint_works_and_detect_honours_cups_server() { let _ = std::fs::remove_dir_all(&dir); } +/// An IPv6 print server is not a `host:port` split: a bare address has more than one ':', and the +/// brackets of `[address]:port` must not end up inside the host, where no resolver can read them. +#[test] +fn an_ipv6_print_server_is_parsed_as_a_host_not_as_host_port() { + assert_eq!(Endpoint::parse("::1"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("fe80::1"), Endpoint::Tcp("fe80::1".into(), 631)); + assert_eq!(Endpoint::parse("2001:db8::1"), Endpoint::Tcp("2001:db8::1".into(), 631)); + assert_eq!(Endpoint::parse("[::1]"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("[::1]:631"), Endpoint::Tcp("::1".into(), 631)); + assert_eq!(Endpoint::parse("[fe80::1]:6310"), Endpoint::Tcp("fe80::1".into(), 6310)); + // A zone id carries no ':', so a port can still follow it without brackets. + assert_eq!(Endpoint::parse("fe80::1%eth0:631"), Endpoint::Tcp("fe80::1%eth0".into(), 631)); + // What already worked is unchanged. + assert_eq!(Endpoint::parse("cups.example"), Endpoint::Tcp("cups.example".into(), 631)); + assert_eq!(Endpoint::parse("cups.example:6310"), Endpoint::Tcp("cups.example".into(), 6310)); + assert_eq!(Endpoint::parse("127.0.0.1:6310"), Endpoint::Tcp("127.0.0.1".into(), 6310)); + assert_eq!(Endpoint::parse("/var/run/cups/cups.sock"), Endpoint::Unix("/var/run/cups/cups.sock".into())); +} + #[test] fn requests_start_with_the_mandatory_attributes() { let r = Request::new(OP_PRINT_JOB, 9).end(); From 094bb727d3b4ee7e8c7408d3816db13efe78ca06 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 11:38:08 -0700 Subject: [PATCH 11/27] Print: the no-listener test takes a port the OS says is free, not port 1 The last case of error_statuses_and_broken_replies_are_errors called printers(&Endpoint::Tcp("127.0.0.1", 1)) and expected Error::Unreachable. No port is guaranteed closed: on a FreeBSD CI VM something accepted on port 1 and reset the connection, so the client got as far as sending and the test failed with "print server reply: sending: Broken pipe (os error 32)" instead. Bind 127.0.0.1:0, read its port and drop the listener, so the case uses a port the OS has just released, and keep the assertion. The fake() helper in the same file already takes its port that way. A held port really does read differently, which is why the old case asserted a property of the machine rather than of the client: against a listener that accepts and closes immediately, printers() returns "print server reply: reading: An existing connection was forcibly closed by the remote host. (os error 10054)" on Windows, not Error::Unreachable. cargo test -p photocraft-ipp: 9 passed / 0 failed, the changed test five runs in a row; clippy --all-targets -- -D warnings and cargo fmt --check clean. --- crates/ipp/src/tests.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index ff3ccb6a49..0737236c69 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -186,8 +186,12 @@ fn error_statuses_and_broken_replies_are_errors() { assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); let (ep, _rx) = fake(b"not ipp at all".to_vec(), false, 200); assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); - // Nobody listening. - let e = printers(&Endpoint::Tcp("127.0.0.1".into(), 1)).unwrap_err(); + // Nobody listening. No port is guaranteed free - on a CI VM something can hold port 1 and reset the + // connection - so take one the OS says is free and release it again. + let free = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = free.local_addr().unwrap().port(); + drop(free); + let e = printers(&Endpoint::Tcp("127.0.0.1".into(), port)).unwrap_err(); assert!(matches!(e, Error::Unreachable(_)), "{e}"); } From 909e1cdd8400322ff79f3a6f61e5a1c2d412a06c Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 12:13:08 -0700 Subject: [PATCH 12/27] Print: an IPv6 endpoint writes its authority in brackets, and a mistyped one stays unreachable Codex-cloud's review of this fix found two more places where an IPv6 print server did not work. host() feeds the Host: header and the ipp:// printer-uri, and it wrote the endpoint the way it is stored: "::1:631". The last colon reads as the port separator, so CUPS got a malformed authority and a malformed printer-uri even though detect() could now connect. An IPv6 host is bracketed there, and in Display, which is what the user is shown; to_socket_addrs still gets the bare address, which is what it needs. A bracketed endpoint with anything else after the bracket - "[::1]:abc", "[::1]:70000", "[::1]junk" - fell back to the default port, so a mistyped CUPS_SERVER was accepted whenever something answered on 631 and jobs went to an endpoint nobody configured. The whole string now stays the host: it cannot resolve, so detect() reports it unreachable. Tests: an_ipv6_endpoint_writes_its_authority_in_brackets, and three mistyped endpoints in the parse test. Both fail before this commit and pass after. photocraft-ipp 11 passed / 0 failed; clippy --all-targets -- -D warnings and fmt --check clean. --- crates/ipp/src/lib.rs | 19 +++++++++++++++++-- crates/ipp/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index fd9eda8065..b5863e910a 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -113,7 +113,9 @@ impl Endpoint { /// `server` as a socket path (starts with `/`) or `host[:port]` (port 631 by default). An IPv6 /// server is `[address]` or `[address]:port`; written bare (more than one `:`) it keeps the - /// default port, because its last `:` cannot be told apart from a port separator. + /// default port, because its last `:` cannot be told apart from a port separator. Anything else + /// after the bracket (`[::1]:abc`) stays the host, so a mistyped endpoint cannot resolve rather + /// than quietly becoming the default one. pub fn parse(server: &str) -> Endpoint { if server.starts_with('/') { return Endpoint::Unix(PathBuf::from(server)); @@ -122,7 +124,16 @@ impl Endpoint { if let Some(rest) = server.strip_prefix('[') && let Some((host, tail)) = rest.split_once(']') { - let port = tail.strip_prefix(':').and_then(|p| p.parse().ok()).unwrap_or(631); + // Nothing after the bracket, or a real `:port`, is understood. Anything else (`[::1]:abc`, + // `[::1]:70000`, `[::1]junk`) keeps the whole string as the host, so the mistyped endpoint + // stays unresolvable instead of quietly becoming the default one. + let port = if tail.is_empty() { + 631 + } else if let Some(port) = tail.strip_prefix(':').and_then(|p| p.parse().ok()) { + port + } else { + return Endpoint::Tcp(server.to_string(), 631); + }; return Endpoint::Tcp(host.to_string(), port); } // A bare IPv6 literal has more than one ':', so splitting on the last one would cut the @@ -163,9 +174,12 @@ impl Endpoint { } } + /// The endpoint as an HTTP authority: an IPv6 host is bracketed, or its last colon reads as the + /// port separator and the request carries a host CUPS has never heard of. fn host(&self) -> String { match self { Endpoint::Unix(_) => "localhost".into(), + Endpoint::Tcp(host, port) if host.contains(':') => format!("[{host}]:{port}"), Endpoint::Tcp(host, port) => format!("{host}:{port}"), } } @@ -175,6 +189,7 @@ impl std::fmt::Display for Endpoint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Endpoint::Unix(p) => write!(f, "{}", p.display()), + Endpoint::Tcp(h, p) if h.contains(':') => write!(f, "[{h}]:{p}"), Endpoint::Tcp(h, p) => write!(f, "{h}:{p}"), } } diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index ce895d81c8..bc08594ad2 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -249,6 +249,27 @@ fn an_ipv6_print_server_is_parsed_as_a_host_not_as_host_port() { assert_eq!(Endpoint::parse("cups.example:6310"), Endpoint::Tcp("cups.example".into(), 6310)); assert_eq!(Endpoint::parse("127.0.0.1:6310"), Endpoint::Tcp("127.0.0.1".into(), 6310)); assert_eq!(Endpoint::parse("/var/run/cups/cups.sock"), Endpoint::Unix("/var/run/cups/cups.sock".into())); + // A mistyped bracketed endpoint is not quietly the default one: the whole string stays the host, + // so nothing can resolve it and detect() reports the endpoint unreachable. + assert_eq!(Endpoint::parse("[::1]:abc"), Endpoint::Tcp("[::1]:abc".into(), 631)); + assert_eq!(Endpoint::parse("[::1]:70000"), Endpoint::Tcp("[::1]:70000".into(), 631)); + assert_eq!(Endpoint::parse("[::1]junk"), Endpoint::Tcp("[::1]junk".into(), 631)); + assert!(!Endpoint::parse("[::1]:abc").reachable()); +} + +/// The authority a request carries (the `Host:` header and the `ipp://` printer-uri) has to bracket an +/// IPv6 host, or its last colon reads as the port separator and CUPS sees a nonsense host. +#[test] +fn an_ipv6_endpoint_writes_its_authority_in_brackets() { + assert_eq!(Endpoint::parse("::1").host(), "[::1]:631"); + assert_eq!(Endpoint::parse("[::1]:631").host(), "[::1]:631"); + assert_eq!(Endpoint::parse("[fe80::1]:6310").host(), "[fe80::1]:6310"); + assert_eq!(Endpoint::parse("cups.example").host(), "cups.example:631"); + assert_eq!(Endpoint::parse("cups.example:6310").host(), "cups.example:6310"); + assert_eq!(Endpoint::parse("127.0.0.1:6310").host(), "127.0.0.1:6310"); + // What the user is shown is written the same way. + assert_eq!(Endpoint::parse("::1").to_string(), "[::1]:631"); + assert_eq!(Endpoint::parse("cups.example:6310").to_string(), "cups.example:6310"); } #[test] From c06a7384a588c8c2c5242a7461de1028ae2e7aa0 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 18:18:51 -0700 Subject: [PATCH 13/27] Print: a scoped IPv6 endpoint escapes its zone id in the request authority `CUPS_SERVER=fe80::1%3:631` parses as `Tcp("fe80::1%3", 631)`, and host() wrote `[fe80::1%3]:631` into the HTTP `Host:` header and into the `ipp://` printer-uri. A bare "%" is not valid inside an authority - RFC 3986 section 3.2.2 reserves "%" for escaping - so a strict HTTP/1.1 server can answer 400 and the printer-uri is not a readable URI. The zone is now written "%25"-escaped for the wire and kept raw for the socket, which is the only place a scope means anything (measured on Windows: `("fe80::1%3", 631).to_socket_addrs()` gives `[fe80::1%3]:631`). The two reviews disagreed about the form. Codex-cloud (fork #68) cited RFC 6874; CodeRabbit here pointed out that RFC 9844 (Aug 2025) obsoletes RFC 6874 and suggested dropping the zone from the authority. Dropping it was considered and not taken: it would send `Host: [fe80::1]:631` and `ipp://[fe80::1]:631/...` for a server reached at `fe80::1%3`, naming a different and ambiguous link-local host from the one the socket opened to, and it would rewrite the printer-uri a queued printer is registered under. The escaped form is what CUPS, curl and the ipp:// URIs CUPS writes use, and current URL libraries (yarl) still read "%25" as the URI form of a zone while rejecting a bare "%". Regressions: numeric zone ids in both authority forms, an interface-name zone, the raw host after parse, and the unchanged IPv6/IPv4/hostname authorities. The printer-uri assertion no longer echoes host() back, so it pins the authority the fake server receives. Reverting the escape fails the new assertion (checked). Platform limit, unchanged by this commit: an interface-name zone (`fe80::1%eth0`) does not resolve on Windows (getaddrinfo 11001), so only numeric scope ids are usable there, and the client reports that as `Error::Unreachable`. cargo test on a standalone copy of the crate: 11 passed / 0 failed; cargo clippy --all-targets -- -D warnings and cargo fmt --check clean. --- crates/ipp/src/lib.rs | 10 ++++++++-- crates/ipp/src/tests.rs | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index b5863e910a..6fe1032496 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -175,11 +175,17 @@ impl Endpoint { } /// The endpoint as an HTTP authority: an IPv6 host is bracketed, or its last colon reads as the - /// port separator and the request carries a host CUPS has never heard of. + /// port separator and the request carries a host CUPS has never heard of. A scoped address keeps + /// its zone id and writes it escaped as "%25": "%" is not valid inside an authority (RFC 3986 + /// section 3.2.2 reserves it for escaping), and the escaped form is what CUPS, curl and the + /// ipp:// URIs CUPS writes use for a zone. RFC 9844 (Aug 2025) obsoleted RFC 6874, which had made + /// that form URI syntax, so this is interop rather than a standard; dropping the zone instead + /// would name a different host on the wire than the socket was opened to. The socket still gets + /// the raw address%zone, which is the form a resolver understands. fn host(&self) -> String { match self { Endpoint::Unix(_) => "localhost".into(), - Endpoint::Tcp(host, port) if host.contains(':') => format!("[{host}]:{port}"), + Endpoint::Tcp(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")), Endpoint::Tcp(host, port) => format!("{host}:{port}"), } } diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index bc08594ad2..02623f71d8 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -158,7 +158,10 @@ fn a_print_job_carries_the_document_and_returns_its_id() { assert_eq!(op, OP_PRINT_JOB); assert_eq!(doc, pdf); let get = |n: &str| attrs.iter().find(|a| a.name == n).cloned().unwrap_or_else(|| panic!("{n}")); - assert_eq!(get("printer-uri").values[0], format!("ipp://{}/printers/Office", ep.host()).as_bytes()); + let uri = String::from_utf8(get("printer-uri").values[0].clone()).unwrap(); + // Spelled out here rather than echoed back from host(), so the printer-uri the server receives is + // pinned down even when the authority is an IP literal. + assert!(uri.starts_with("ipp://127.0.0.1:") && uri.ends_with("/printers/Office"), "{uri}"); assert_eq!(get("job-name").values[0], b"photo.psd"); assert_eq!(get("requesting-user-name").values[0], b"diego"); assert_eq!(get("document-format").values[0], b"application/pdf"); @@ -267,9 +270,17 @@ fn an_ipv6_endpoint_writes_its_authority_in_brackets() { assert_eq!(Endpoint::parse("cups.example").host(), "cups.example:631"); assert_eq!(Endpoint::parse("cups.example:6310").host(), "cups.example:6310"); assert_eq!(Endpoint::parse("127.0.0.1:6310").host(), "127.0.0.1:6310"); - // What the user is shown is written the same way. + // A scoped address keeps its zone id, but the authority writes it "%25"-escaped: a bare "%" is + // not valid inside an authority, and the escaped form is what CUPS and curl-style ipp:// URIs + // use. The host itself stays raw, because that is what the resolver gets. + assert_eq!(Endpoint::parse("fe80::1%3:631").host(), "[fe80::1%253]:631"); + assert_eq!(Endpoint::parse("[fe80::1%3]:6310").host(), "[fe80::1%253]:6310"); + assert_eq!(Endpoint::parse("fe80::1%eth0:631").host(), "[fe80::1%25eth0]:631"); + assert_eq!(Endpoint::parse("fe80::1%3:631"), Endpoint::Tcp("fe80::1%3".into(), 631)); + // What the user is shown is written the same way, with the zone exactly as it was typed. assert_eq!(Endpoint::parse("::1").to_string(), "[::1]:631"); assert_eq!(Endpoint::parse("cups.example:6310").to_string(), "cups.example:6310"); + assert_eq!(Endpoint::parse("fe80::1%3:631").to_string(), "[fe80::1%3]:631"); } #[test] From 82a1f54cc81b8cdb707b04ff9e982b5a37912c8a Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 19 Oct 2026 18:28:44 -0700 Subject: [PATCH 14/27] Print: the no-listener case refuses through a seam instead of a port it hopes is free The released-port version only proved the port was unused a moment earlier. Between drop(free) and the connect, another process can be handed that exact ephemeral port, and the case then reports a protocol error or blocks instead of Unreachable - the same flake this branch was meant to remove, just quieter. connect() now goes through open_tcp(host, port, addr, open), a private helper that takes the connect call as a parameter. The refusal test decides what is closed, so it owns no port: it asserts Unreachable, that the message names the endpoint, and that the reason the connect failed survives. The end-to-end "nobody reachable" case now names a host that can never resolve (RFC 2606) rather than a port nobody owns. Fake-server protocol tests are unchanged, and no public injection point or dependency was added. --- crates/ipp/src/lib.rs | 17 ++++++++++++----- crates/ipp/src/tests.rs | 35 +++++++++++++++++++++++++++++------ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/ipp/src/lib.rs b/crates/ipp/src/lib.rs index 9f1209df45..79d4f0775f 100644 --- a/crates/ipp/src/lib.rs +++ b/crates/ipp/src/lib.rs @@ -12,7 +12,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use std::io::{Read, Write}; -use std::net::{TcpStream, ToSocketAddrs}; +use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; use std::path::PathBuf; use std::time::Duration; @@ -142,10 +142,7 @@ impl Endpoint { Endpoint::Tcp(host, port) => { let addr = (host.as_str(), *port).to_socket_addrs().map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?.next(); let addr = addr.ok_or_else(|| Error::Unreachable(format!("{host}:{port}: no address")))?; - let s = TcpStream::connect_timeout(&addr, CONNECT).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?; - let _ = s.set_read_timeout(Some(REQUEST)); - let _ = s.set_write_timeout(Some(REQUEST)); - Ok(Stream::Tcp(s)) + open_tcp(host, *port, addr, |addr| TcpStream::connect_timeout(&addr, CONNECT)) } } } @@ -167,6 +164,16 @@ impl std::fmt::Display for Endpoint { } } +/// Open one address and put the request timeouts on it. The connect call is a parameter so the +/// refusal path can be tested at all: no port is guaranteed to stay free between picking one and +/// using it, and what a refused connect reported is what the caller is supposed to hear. +fn open_tcp(host: &str, port: u16, addr: SocketAddr, open: impl FnOnce(SocketAddr) -> std::io::Result) -> Result { + let s = open(addr).map_err(|e| Error::Unreachable(format!("{host}:{port}: {e}")))?; + let _ = s.set_read_timeout(Some(REQUEST)); + let _ = s.set_write_timeout(Some(REQUEST)); + Ok(Stream::Tcp(s)) +} + enum Stream { #[cfg(unix)] Unix(std::os::unix::net::UnixStream), diff --git a/crates/ipp/src/tests.rs b/crates/ipp/src/tests.rs index 0737236c69..0914291879 100644 --- a/crates/ipp/src/tests.rs +++ b/crates/ipp/src/tests.rs @@ -186,13 +186,36 @@ fn error_statuses_and_broken_replies_are_errors() { assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); let (ep, _rx) = fake(b"not ipp at all".to_vec(), false, 200); assert!(matches!(printers(&ep), Err(Error::Protocol(_)))); - // Nobody listening. No port is guaranteed free - on a CI VM something can hold port 1 and reset the - // connection - so take one the OS says is free and release it again. - let free = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = free.local_addr().unwrap().port(); - drop(free); - let e = printers(&Endpoint::Tcp("127.0.0.1".into(), port)).unwrap_err(); + // Nobody reachable. A port is never guaranteed to be free, let alone to stay free: that is what + // made the old port-1 case fail on a FreeBSD CI VM. A name that can never resolve (RFC 2606) + // reaches the same exit without owning or releasing anything. + let e = printers(&Endpoint::Tcp("printer.invalid".into(), 631)).unwrap_err(); assert!(matches!(e, Error::Unreachable(_)), "{e}"); + assert!(e.to_string().contains("printer.invalid"), "{e} does not name the server it tried"); +} + +#[test] +fn a_refused_connection_is_unreachable_and_keeps_why() { + // The refused-connect path, with the machine no longer deciding what is closed: the connect call + // is a parameter, so this test cannot race for an ephemeral port with anything. + let addr: SocketAddr = "192.0.2.9:631".parse().unwrap(); + let asked_for = std::cell::RefCell::new(None); + let open = |seen: SocketAddr| -> std::io::Result { + *asked_for.borrow_mut() = Some(seen); + Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "nobody is listening on this port")) + }; + let e = match open_tcp("printserver", 631, addr, open) { + Ok(_) => panic!("nothing opens {addr}"), + Err(e) => e, + }; + assert_eq!(*asked_for.borrow(), Some(addr), "the connector is handed the resolved address"); + match &e { + Error::Unreachable(m) => { + assert!(m.contains("printserver:631"), "{e} does not name the endpoint"); + assert!(m.contains("nobody is listening on this port"), "{e} loses why the connect failed"); + } + other => panic!("expected Unreachable, got {other}"), + } } #[test] From 331c7f38a553a173eb1f5e23bb6b77ad3fd9b3f2 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 21 Oct 2026 01:15:29 +0800 Subject: [PATCH 15/27] perf(raster): read 16- and 32-bit rows into RGBA with the colour model resolved per row --- crates/color/src/lib.rs | 23 ++++++++++++++++++ crates/raster/src/lib.rs | 51 +++++++++++++++++++++++++++++++--------- 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index a33437963b..281c3e01b9 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -120,6 +120,29 @@ pub fn read_sample(bytes: &[u8], sample: SampleType, index: usize) -> f32 { } } +/// [`read_sample`] for the `out.len()` samples from sample index `start` on, matching the sample +/// type once instead of per sample. +pub fn read_samples(bytes: &[u8], sample: SampleType, start: usize, out: &mut [f32]) { + let end = start + out.len(); + match sample { + SampleType::U8 => { + for (o, b) in out.iter_mut().zip(&bytes[start..end]) { + *o = *b as f32 / 255.0; + } + } + SampleType::U16 => { + for (o, b) in out.iter_mut().zip(bytes[start * 2..end * 2].as_chunks::<2>().0) { + *o = u16::from_ne_bytes(*b) as f32 / 65535.0; + } + } + SampleType::F32 => { + for (o, b) in out.iter_mut().zip(bytes[start * 4..end * 4].as_chunks::<4>().0) { + *o = f32::from_ne_bytes(*b); + } + } + } +} + /// Write a normalised f32 sample; integer types are clamped and rounded. #[inline] pub fn write_sample(bytes: &mut [u8], sample: SampleType, index: usize, v: f32) { diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 958ab38b53..8347eb51ef 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -14,7 +14,7 @@ use std::collections::BTreeMap; use std::fmt; use std::sync::Arc; -use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, write_sample}; +use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, read_samples, write_sample}; use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; /// A checked surface allocation could not be represented or reserved. @@ -503,9 +503,7 @@ impl Surface { match tile { Some(t) => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; - for (i, d) in dst.iter_mut().enumerate() { - *d = read_sample(&t.data, self.format.sample, base + i); - } + read_samples(&t.data, self.format.sample, base, dst); } None if n == 1 => dst.fill(dp[0]), None => { @@ -529,8 +527,8 @@ impl Surface { let n = fmt.channels(); let mut stack = [0.0; 8]; let mut heap = Vec::new(); - let px = self.default_samples(&mut stack, &mut heap); - let dp = to_rgba(&fmt, px); + let dp = to_rgba(&fmt, self.default_samples(&mut stack, &mut heap)); + let mut row = Vec::new(); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); @@ -574,11 +572,17 @@ impl Surface { } } _ => { - for (i, d) in dst.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate() { - *v = read_sample(&t.data, fmt.sample, base + i * n + c); - } - *d = to_rgba(&fmt, px); + // The row's samples in one pass, then its colour model resolved once: + // RGB and grey take their channels as `to_rgba` does, other models go + // through it. + row.resize(dst.len() * n, 0.0); + read_samples(&t.data, fmt.sample, base, &mut row); + let a = |s: &[f32], i: usize| if fmt.alpha { s[i] } else { 1.0 }; + let pixels = dst.iter_mut().zip(row.chunks_exact(n)); + match fmt.mode { + ColorMode::Rgb => pixels.for_each(|(d, s)| *d = [s[0], s[1], s[2], a(s, 3)]), + ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => pixels.for_each(|(d, s)| *d = [s[0], s[0], s[0], a(s, 1)]), + _ => pixels.for_each(|(d, s)| *d = to_rgba(&fmt, s)), } } } @@ -1603,6 +1607,31 @@ mod tests { } } + #[test] + fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() { + // Across tile edges and a missing tile; float samples include -0, out-of-range and NaN. + let rect = Rect::new(-3, -1, 300, 2); + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { + for depth in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(mode, depth, alpha); + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75]; + for (i, x) in (-2..260).enumerate() { + let px: Vec = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect(); + s.write_pixel(x, 0, &px); + } + let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; + s.read_rgba_into(rect, &mut out); + for (i, actual) in out.iter().enumerate() { + let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); + assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}"); + } + } + } + } + } + #[test] fn tile_content_bounds_scans_against_the_given_pixel() { let mut s = Surface::new(PixelFormat::GRAY8); From aab9cdc04590f8512478722a529ea01fc7070122 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 21 Oct 2026 10:01:07 +0800 Subject: [PATCH 16/27] Compose: Color Balance works out each channel's curve once, not per pixel color_balance_channel recomputed the folded black point, white point and midtone gamma, and four of the five powf calls of the gamma > 1 Hermite join, for every sample. Those depend only on the sliders, so BalanceCurve works them out once per channel and the per-sample step is the clamp and one powf (or the Hermite polynomial). The CPU compositor builds the three curves once per buffer and the GPU plan once per LUT (it sampled color_balance_channel 3 x 4096 times). Results are bit-identical: a new test compares the curve against the per-sample formula it replaced, to the bit, over 123 slider settings, both Preserve Luminosity modes and a 1/1024 ramp. --- crates/compose/src/adjust.rs | 174 +++++++++++++++++++++++++++-------- crates/gpu/src/plan.rs | 6 +- 2 files changed, 141 insertions(+), 39 deletions(-) diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 38e34fcd12..9a6e7492fb 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -232,7 +232,8 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth } } Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { - map_rgb(buf, |c| std::array::from_fn(|ch| color_balance_channel([*shadows, *midtones, *highlights], *preserve_luminosity, ch, c[ch]))) + let curves = BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); + map_rgb(buf, |c| std::array::from_fn(|ch| curves[ch].eval(c[ch]))) } Adjustment::SelectiveColor { relative, adjustments } => map_rgb(buf, |c| selective_color(c, *relative, adjustments)), Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => { @@ -786,48 +787,89 @@ pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f /// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white /// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones. /// -/// A gamma > 1 starts with slope 2^gamma at black ([`balance_gamma`]: up to 18 of 255 brighter +/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter /// near black without it). When the black point reaches the white point, input /// at or above the white point is white and the rest black. pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { - let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); - let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); - let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); - let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); - let (black, white, m) = if preserve_luminosity { - (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) - } else { - ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) - }; - let (b, w) = (black / 255.0, 1.0 - white / 255.0); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if v >= w { - return 1.0; - } - if v <= b { - return 0.0; - } - balance_gamma((v - b) / (w - b), 2f32.powf(m / 100.0)) + BalanceCurve::new(tones, preserve_luminosity, ch).eval(v) } -/// The midtone gamma of Color Balance's per-channel Levels (`u` in 0..1): `u^(1/gamma)`, except -/// that a gamma > 1 (which would start with infinite slope) starts at slope 2^gamma and joins the -/// power curve in a cubic Hermite at twice the input where that line meets it (Photoshop, -/// measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). -fn balance_gamma(u: f32, gamma: f32) -> f32 { - let e = 1.0 / gamma.max(0.01); - let power = u.powf(e); - if gamma <= 1.0 { - return power; +/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't +/// depend on the sample worked out once rather than per pixel. +pub struct BalanceCurve { + /// Input black and white points. + b: f32, + w: f32, + /// The power curve's exponent, 1 / gamma. + e: f32, + /// The Hermite join of a gamma > 1. + knee: Option, +} + +/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the +/// power curve's value (`p`) and slope (`d`) at `u0`. +#[derive(Clone, Copy)] +struct Knee { + u0: f32, + s0: f32, + p: f32, + d: f32, +} + +impl BalanceCurve { + /// The red, green and blue curves. + pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] { + std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch)) } - let s0 = 2f32.powf(gamma); - let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); - if u0.is_nan() || u0 <= 0.0 || u >= u0 { - return power; + + /// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and + /// highlights slider triples `tones`. + pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + // The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1 + // (which would start with infinite slope) starts at slope 2^gamma and joins the power + // curve in a cubic Hermite at twice the input where that line meets it (Photoshop, + // measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). + let gamma = 2f32.powf(m / 100.0); + let e = 1.0 / gamma.max(0.01); + let knee = if gamma > 1.0 { + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + (!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) }) + } else { + None + }; + Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee } + } + + /// The curve at `v` (0..1). + pub fn eval(&self, v: f32) -> f32 { + let (b, w) = (self.b, self.w); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let u = (v - b) / (w - b); + match self.knee { + Some(Knee { u0, s0, p, d }) if u < u0 => { + let t = u / u0; + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + _ => u.powf(self.e), + } } - let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); - let (t2, t3) = (t * t, t * t * t); - ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) } /// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans, @@ -1736,6 +1778,66 @@ mod tone_tests { } } + #[test] + fn color_balance_curve_matches_the_per_sample_formula_bitwise() { + // The curve works out its sample-independent terms once; this is the formula it replaced, + // evaluated whole for every sample. + fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + let (b, w) = (black / 255.0, 1.0 - white / 255.0); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0)); + let e = 1.0 / gamma.max(0.01); + let power = u.powf(e); + if gamma <= 1.0 { + return power; + } + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + if u0.is_nan() || u0 <= 0.0 || u >= u0 { + return power; + } + let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + let mut seed = 0x9e37_79b9_u32; + let mut slider = || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed % 241) as f32 - 120.0 + }; + let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]]; + settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider())))); + let samples: Vec = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect(); + for tones in settings { + for preserve in [false, true] { + for ch in [0, 1, 2, 7] { + let curve = BalanceCurve::new(tones, preserve, ch); + for &v in &samples { + let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v)); + assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}"); + } + } + } + } + } + #[test] fn levels_and_curves_apply_each_channel_before_the_master() { // These two affine tone adjustments describe the same mapping: diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 6cb44b9200..82fb580833 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -1757,9 +1757,9 @@ pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraf (13, p, Some(rows)) } Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { - // Per-channel curves (compose::adjust::color_balance_channel), through the Levels kernel. - let tones = [*shadows, *midtones, *highlights]; - (7, p, Some(lut_rows(|ch, v| adjust::color_balance_channel(tones, *preserve_luminosity, ch, v), 3))) + // Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel. + let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); + (7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3))) } Adjustment::SelectiveColor { relative, adjustments } => { // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact). From d278a85696f9cd2f0bf371a1dcd81f3099ba18cf Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 21 Oct 2026 11:26:21 +0800 Subject: [PATCH 17/27] Compose: tone and hue-range lookups truncate instead of calling floor Baseline x86-64 has no SSE4.1 roundss, so f32::floor is an out-of-line libm call there. lut, which every Levels, Curves, Hue/Saturation range and modern Brightness/Contrast sample goes through, floored its non-negative table position. Truncating is the same there (NaN casts to 0 either way) and inlines. Bit-identical. --- crates/compose/src/adjust.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 38e34fcd12..a742876de1 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -898,7 +898,9 @@ fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) { #[inline] fn lut(table: &[f32], v: f32) -> f32 { let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32; - let i = x.floor() as usize; + // Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the + // libm call baseline x86-64 (no SSE4.1) makes for it. + let i = x as usize; let j = (i + 1).min(table.len() - 1); let f = x - i as f32; table[i] * (1.0 - f) + table[j] * f From 420353c5ae0ebf34359a3f68d5e97bbcaa8a9709 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 21 Oct 2026 12:26:47 +0800 Subject: [PATCH 18/27] Compose: adjustment layers blend back in Normal mode without a per-pixel mode dispatch An adjustment layer's result was blended back into the backdrop pixel by pixel through blend_rgb, which looks up the HDR flag and dispatches on the mode, three channel calls deep, for every pixel. Normal (nearly every adjustment layer) gives the source exactly, so blend_back skips the dispatch for it, and walks the backdrop, the result and the coverage in step instead of indexing by coordinates. Bit-identical. --- crates/compose/src/lib.rs | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2ed1873a9d..e3bd865389 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -967,6 +967,21 @@ fn quantize(b: &mut Buffer, q: f32) { } } +/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each +/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. +fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { + for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { + if k <= 0.0 { + continue; + } + let s = [a[0], a[1], a[2]]; + // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment + // layers are Normal: no per-pixel mode dispatch for them. + let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; + *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; + } +} + /// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling). #[inline] fn dissolve_noise(x: i32, y: i32) -> f32 { @@ -1748,19 +1763,9 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer cx.apply_adjustment(adj, &mut adjusted); // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. advanced::composite_clipped(clipped, &mut adjusted, cx); - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let k = opacity * mask_k(&mv, i); - if k <= 0.0 { - continue; - } - // Only `adjusted` has changed; this pixel's original backdrop is still in place. - let b = backdrop.px[i]; - let a = adjusted.px[i]; - let blended = blend::blend_rgb(layer.blend, [b[0], b[1], b[2]], [a[0], a[1], a[2]]); - backdrop.px[i] = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; - } + match &mv { + Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), + None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), } recycle_buffer(adjusted); return; From f2dce8071843e0cfcc285e4a942c3da2bcb9ac10 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 21 Oct 2026 12:26:49 +0800 Subject: [PATCH 19/27] Compose: quantize floors without a libm call Baseline x86-64 has no SSE4.1 roundss, so f32::floor is a software routine there, called once per sample of the backdrop under every adjustment layer of an 8- or 16-bit document. branchless_floor rounds through 2^23 and steps down where that went up: bit-identical to floor for every f32 (a new test sweeps every 4099th bit pattern and the edges around whole numbers and 2^23), and with no branch the loop vectorizes. --- crates/compose/src/lib.rs | 17 ++++++++++++++++- crates/compose/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e3bd865389..7ea894bfb9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -962,11 +962,26 @@ pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { fn quantize(b: &mut Buffer, q: f32) { for p in &mut b.px { for v in p.iter_mut() { - *v = (*v * q + 0.5).floor() / q; + *v = branchless_floor(*v * q + 0.5) / q; } } } +/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline +/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample +/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the +/// loop vectorizes. +#[inline] +fn branchless_floor(x: f32) -> f32 { + // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the + // nearest whole number; where that went up, step down. + const WHOLE: f32 = 8_388_608.0; + let a = x.abs(); + let r = ((a + WHOLE) - WHOLE).copysign(x); + let r = if r > x { r - 1.0 } else { r }; + if a < WHOLE { r } else { x } +} + /// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each /// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 99823457fa..93b048b9f9 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3624,3 +3624,19 @@ fn fully_masked_adjustment_tiles_preserve_output_and_skip_tone_work() { } } } + +#[test] +fn branchless_floor_matches_floor_bitwise() { + // Every 4099th bit pattern (all exponents, both signs, NaNs and infinities among them), plus + // the values either side of the whole numbers and of 2^23 where the rounding steps. + let mut xs: Vec = (0..=u32::MAX).step_by(4099).map(f32::from_bits).collect(); + for w in [0.0f32, 1.0, 2.0, 254.0, 255.0, 32768.0, 4_194_303.0, 4_194_304.0, 8_388_607.0, 8_388_608.0, 16_777_216.0] { + for v in [w, -w] { + xs.extend([v, v.next_up(), v.next_down(), v + 0.5, v - 0.5]); + } + } + xs.extend([f32::INFINITY, f32::NEG_INFINITY, f32::NAN, -f32::NAN, f32::MIN_POSITIVE, -f32::MIN_POSITIVE, f32::MAX, f32::MIN]); + for x in xs { + assert_eq!(branchless_floor(x).to_bits(), x.floor().to_bits(), "{x:e} ({:#010x})", x.to_bits()); + } +} From 013863da95125f7f206284d529532f5d5b628172 Mon Sep 17 00:00:00 2001 From: VishnuByrraju Date: Wed, 21 Oct 2026 10:39:00 +0530 Subject: [PATCH 20/27] fix(psd): an edited type layer updates the Photoshop-era Txt2 objects too (#6971) Older Photoshop keeps each type layer's text object at /DocumentObjects /TextObjects (named keys, run lengths under /Length) and re-renders from it. type.edit refreshed TySh and the numbered /1 /1 list but left the old text there, so the layer came back with its old text. build_txt2_at now refits that entry like edited_object does for the numbered ones: the model text, one ParagraphRun run per paragraph, every other run array cut or extended to the new UTF-16 total. Entries are only edited in place (never grown), a malformed run array leaves the entry as the file has it, and an unchanged block is still written back byte for byte. A legacy block holding both lists with a stale older copy is repaired on re-save. --- crates/text/src/psd.rs | 103 +++++++++++++++++--- crates/text/src/tests.rs | 196 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 287 insertions(+), 12 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 99fb2ebf0f..ae86138024 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -1104,6 +1104,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi let prev = previous.and_then(parse_txt2); let prev_objects: &[E] = prev.as_ref().and_then(|p| p.path(&["1", "1"]).and_then(E::as_array)).unwrap_or(&[]); let mut slots: Vec = prev_objects.to_vec(); + // The older Photoshop's objects (#6971): named keys at `/DocumentObjects /TextObjects` + // instead of the numbered `/1 /1`, one entry per layer by `TextIndex` position (the same + // numbering the slots take), its text under `Model /Text` and its run lengths under `/Length`. + // Photoshop re-renders a type layer from this copy when the file has one, so an edit that + // left the old text here showed the old text back on reopen. The entries are only ever edited + // in place, never grown: a layer the block has no entry for has no stale copy to fix. + let mut td: Option> = prev.as_ref().and_then(|p| p.path(&["DocumentObjects", "TextObjects"])).and_then(E::as_array).map(<[E]>::to_vec); + let mut td_changed = false; let mut fonts: Vec = prev.as_ref().and_then(|p| p.path(&["0", "1", "0"]).and_then(E::as_array)).map(<[E]>::to_vec).unwrap_or_default(); let fonts_before = fonts.len(); // Looked up once per save, not per layer: a crafted block with many objects must not cost @@ -1118,6 +1126,21 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi let text = format!("{}\r", layer.text.replace('\n', "\r")); let modes = txt2_mode_runs(layer); let at = *index as usize; + // The older Photoshop's copy of this object (#6971), refitted like the numbered one + // below. The entry's own text is the check, so a file a previous save left with a stale + // copy beside a current `/1 /1` object is repaired here too. + if let Some(entries) = td.as_mut() { + let fixed = match entries.get(at) { + Some(entry) if entry.path(&["Model", "Text"]).and_then(E::as_str) != Some(text.as_str()) => td_edited_object(entry, &text), + _ => None, + }; + if let Some(fixed) = fixed + && let Some(slot) = entries.get_mut(at) + { + *slot = fixed; + td_changed = true; + } + } // A stub an earlier save wrote beside Photoshop's objects counts as no object at all, so // it is replaced like a missing one (below) and re-saving such a file repairs it, whether // or not the layer's text changed. @@ -1182,6 +1205,14 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi Some(objs @ E::Dict(_)) => objs.set("1", E::Array(slots)), _ => outer.set("1", E::Dict(vec![("1".into(), E::Array(slots))])), } + // The older Photoshop's objects, whatever the loop fixed in them (an untouched list is left + // exactly as the file has it, so the byte-for-byte return below still holds). + if td_changed + && let Some(entries) = td + && let Some(objects @ E::Dict(_)) = outer.get_mut("DocumentObjects") + { + objects.set("TextObjects", E::Array(entries)); + } // Nothing changed: the file's own bytes (writing them back would re-encode strings and numbers). if let (Some(bytes), Some(p)) = (previous, &prev) && *p == outer @@ -1237,7 +1268,7 @@ fn new_object(template: &E, at: usize, text: &str) -> Option { } } if let Some(runs) = view.path(&["1", "0"]).and_then(E::as_array) { - let fitted = runs_per(runs, ¶graphs)?; + let fitted = runs_per(runs, ¶graphs, "1")?; view.get_mut("1")?.set("0", E::Array(fitted)); } Some(object) @@ -1290,34 +1321,82 @@ fn edited_object(object: &E, text: &str) -> Option { let Some(runs) = value.get("0").and_then(E::as_array).filter(|r| r.iter().all(|x| matches!(x, E::Dict(_)) && x.get("1").is_some())) else { continue; }; - let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs)? } else { runs_to_length(runs, total)? }; + let fitted = if key.as_str() == "5" { runs_per(runs, ¶graphs, "1")? } else { runs_to_length(runs, total, "1")? }; value.set("0", E::Array(fitted)); } Some(object) } -/// `runs` (`<< … /1 length >>`) remade with the lengths `lens`: run i keeps the content of the -/// file's run i, else of its last one. `None` for an empty `runs`. -fn runs_per(runs: &[E], lens: &[usize]) -> Option> { +/// The older Photoshop's `Txt2` text object `object` (`<< /Model << /Text … /ParagraphRun … >> +/// /View … >>`) for the changed engine text `text` (`\r` breaks, trailing `\r`): the model's text +/// replaced and every run array of the model refitted the way [`edited_object`] refits the +/// numbered objects' — the paragraph runs (`/ParagraphRun`) one per paragraph of the new text, the +/// others (`/StyleRun`, `/KernRun`, …) cut or extended to the new total. The model's other keys, +/// the view and the rest are kept: these blocks (the objects at `/DocumentObjects /TextObjects` +/// that older Photoshop versions write and re-render from, #6971) name their keys and number +/// their runs with `/Length` in UTF-16 units instead of `/1`. `None` when the object or one of +/// its run arrays isn't shaped as Photoshop writes it: the caller then leaves the entry as the +/// file has it, rather than write text its runs don't cover (#6968). +fn td_edited_object(object: &E, text: &str) -> Option { + let mut object = object.clone(); + let model = object.get_mut("Model").filter(|m| matches!(m, E::Dict(_)))?; + let E::Dict(entries) = model else { return None }; + // The text must be there to replace: refitted runs over a text the model doesn't hold would + // be a half-edited object. + if !entries.iter().any(|(k, v)| k == "Text" && matches!(v, E::String(_))) { + return None; + } + let total = utf16_len(text) as usize; + let paragraphs: Vec = text.split_inclusive('\r').map(|p| p.encode_utf16().count()).collect(); + for (key, value) in entries.iter_mut() { + if key.as_str() == "Text" { + *value = E::String(text.to_string()); + continue; + } + if !matches!(value, E::Dict(_)) { + continue; + } + // A model dict without `RunArray` isn't a run array (the view's keys live elsewhere), so + // it is skipped; a named `RunArray` is unambiguous — malformed, the whole entry is left to + // the file rather than half-updated. + let Some(runs) = value.get("RunArray") else { continue }; + let fitted = match runs { + E::Array(runs) if runs.iter().all(|x| matches!(x, E::Dict(_)) && x.get("Length").is_some()) => { + if key.as_str() == "ParagraphRun" { + runs_per(runs, ¶graphs, "Length")? + } else { + runs_to_length(runs, total, "Length")? + } + } + _ => return None, + }; + value.set("RunArray", E::Array(fitted)); + } + Some(object) +} + +/// `runs` (`<< … /1 length >>`, the length key named `len_key`) remade with the lengths `lens`: +/// run i keeps the content of the file's run i, else of its last one. `None` for an empty `runs`. +fn runs_per(runs: &[E], lens: &[usize], len_key: &str) -> Option> { let last = runs.last()?; lens.iter() .enumerate() .map(|(i, &len)| { let mut r = runs.get(i).unwrap_or(last).clone(); - r.set("1", E::Int(i64::try_from(len).ok()?)); + r.set(len_key, E::Int(i64::try_from(len).ok()?)); Some(r) }) .collect() } -/// `runs` (`<< … /1 length >>`) covering `total` UTF-16 units: the leading runs as they were, cut -/// where `total` ends, the last kept run extended when `total` is longer. Empty runs are dropped. -/// `None` when `runs` is empty or a length isn't a count. -fn runs_to_length(runs: &[E], total: usize) -> Option> { +/// `runs` (`<< … /1 length >>`, the length key named `len_key`) covering `total` UTF-16 units: +/// the leading runs as they were, cut where `total` ends, the last kept run extended when `total` +/// is longer. Empty runs are dropped. `None` when `runs` is empty or a length isn't a count. +fn runs_to_length(runs: &[E], total: usize, len_key: &str) -> Option> { let mut out: Vec<(E, usize)> = Vec::new(); let mut left = total; for r in runs { - let len = r.get("1").and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())?; + let len = r.get(len_key).and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())?; let take = len.min(left); if take > 0 { out.push((r.clone(), take)); @@ -1332,7 +1411,7 @@ fn runs_to_length(runs: &[E], total: usize) -> Option> { } out.into_iter() .map(|(mut r, len)| { - r.set("1", E::Int(i64::try_from(len).ok()?)); + r.set(len_key, E::Int(i64::try_from(len).ok()?)); Some(r) }) .collect() diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 6aecea05a8..d7d37a091d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1085,6 +1085,202 @@ fn txt2_keeps_a_kept_objects_extras_and_drops_them_with_its_text() { assert!(object.path(&["0", "keep"]).is_none(), "model extras of another text are dropped"); } +/// The `DocumentObjects` value older Photoshop writes beside the numbered objects +/// (`/DocumentObjects /TextObjects`, named keys, run lengths under `/Length` in UTF-16 units, +/// #6971): one entry per layer, its `\r`-terminated text in `Model /Text`, one paragraph run per +/// paragraph, one style and kern run covering the whole text. +fn photoshop_era_objects(texts: &[&str]) -> crate::engine_data::Value { + use crate::engine_data::Value as E; + let run = |len: i64| E::Dict(vec![("RunData".into(), E::Dict(vec![("0".into(), E::String(String::new()))])), ("Length".into(), E::Int(len))]); + let entries = texts + .iter() + .map(|t| { + let text = format!("{t}\r"); + let paragraphs: Vec = text.split_inclusive('\r').map(|p| p.encode_utf16().count() as i64).collect(); + let total = text.encode_utf16().count() as i64; + E::Dict(vec![ + ( + "Model".into(), + E::Dict(vec![ + ("Text".into(), E::String(text)), + ("ParagraphRun".into(), E::Dict(vec![("RunArray".into(), E::Array(paragraphs.iter().map(|&n| run(n)).collect()))])), + ("StyleRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])), + ("KernRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run(total)]))])), + ]), + ), + ("View".into(), E::Dict(vec![("0".into(), E::Array(vec![E::Dict(vec![("0".into(), E::Int(0))])]))])), + ]) + }) + .collect(); + E::Dict(vec![("TextObjects".into(), E::Array(entries))]) +} + +/// A whole `Txt2` block shaped like the older Photoshop's: document resources and the objects at +/// `/DocumentObjects /TextObjects`, no numbered `/1 /1` list at all. +fn photoshop_era_txt2(texts: &[&str]) -> Vec { + use crate::engine_data::Value as E; + crate::engine_data::write_bare(&[ + ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])), + ("0".into(), E::dict()), + ("DocumentObjects".into(), photoshop_era_objects(texts)), + ]) +} + +/// #6971: Photoshop re-renders a type layer from the objects older Photoshop keeps at +/// `/DocumentObjects /TextObjects` when the file has them, so an edit that left the old text +/// there showed the old text back on reopen. The save refits that copy the way it refits the +/// numbered ones — the new text, one paragraph run per paragraph of it, the other runs to its +/// total — and keeps the entries' view and the rest. +#[test] +fn edited_text_updates_the_photoshop_era_objects() { + use crate::engine_data::Value as E; + use photocraft_doc::text::Kerning; + let prev = photoshop_era_txt2(&["Line 1\rLine 2"]); + let before = crate::psd::parse_txt2(&prev).unwrap(); + let t = styled("Hi\nBye", CharStyle { kerning: Kerning::Optical, ..Default::default() }); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap(); + let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects"); + assert_eq!(entries.len(), 1, "no entry is added"); + let entry = entries.first().expect("the entry"); + let model = entry.get("Model").expect("the model"); + assert_eq!(model.get("Text").and_then(E::as_str), Some("Hi\rBye\r"), "the stale text is replaced"); + let lens = |key: &str| -> Vec { + model + .path(&[key, "RunArray"]) + .and_then(E::as_array) + .map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect()) + .unwrap_or_default() + }; + assert_eq!(lens("ParagraphRun"), vec![3, 4], "one paragraph run per paragraph of the new text"); + assert_eq!(lens("StyleRun"), vec![7], "the style runs cover the new text's UTF-16 units"); + assert_eq!(lens("KernRun"), vec![7]); + assert_eq!( + entry.get("View"), + before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()).and_then(|e| e.get("View")), + "the view is kept" + ); + // The numbered list is written alongside, as it was before this fix. + let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects"); + assert_eq!(slots.len(), 1); + assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("Hi\rBye\r")); +} + +/// Only the entries of layers the save holds change: another layer's object — one no layer names +/// — is written back as the file has it. +#[test] +fn only_the_edited_photoshop_era_object_changes() { + use crate::engine_data::Value as E; + use photocraft_doc::text::Kerning; + let prev = photoshop_era_txt2(&["One", "Two"]); + let before = crate::psd::parse_txt2(&prev).unwrap(); + let style = |kerning: Kerning| CharStyle { kerning, ..Default::default() }; + let t0 = runs_of("One", &[(3, style(Kerning::Metrics))]); + let t1 = runs_of("Changed", &[(7, style(Kerning::Optical))]); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t0), (1, &t1)], Some(&prev))).unwrap(); + let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects"); + let was = before.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects before"); + assert_eq!(entries.len(), 2, "no entry is added"); + assert_eq!(entries.first(), was.first(), "the unchanged entry is written back as it was"); + assert_eq!(entries.get(1).and_then(|e| e.path(&["Model", "Text"])).and_then(E::as_str), Some("Changed\r"), "the edited entry takes the new text"); +} + +/// Files saved by the old code have both lists: the numbered object current, the older copy still +/// holding the text of an earlier edit. Re-saving repairs the stale copy even when the numbered +/// object's text matches the layer (nothing else about the file changes). +#[test] +fn legacy_file_with_both_object_lists_repairs_the_stale_one() { + use crate::engine_data::Value as E; + use photocraft_doc::text::Kerning; + let mut prev = photoshop_txt2(&[(4, 1)]); + prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["Old stuff"]))])); + let before = crate::psd::parse_txt2(&prev).unwrap(); + let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() }); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap(); + let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects"); + assert_eq!(entries.len(), 1); + let model = entries.first().expect("the entry").get("Model").expect("the model"); + assert_eq!(model.get("Text").and_then(E::as_str), Some("AVA\r"), "the stale copy is repaired"); + let lens = model + .path(&["StyleRun", "RunArray"]) + .and_then(E::as_array) + .map(|rs| rs.iter().map(|r| r.get("Length").and_then(E::as_i64).unwrap_or(-1)).collect::>()); + assert_eq!(lens, Some(vec![4]), "its runs cover the layer's text"); + let slots = out.path(&["1", "1"]).and_then(E::as_array).expect("the numbered objects"); + assert_eq!(slots.first().and_then(|o| o.path(&["0", "0"])).and_then(E::as_str), Some("AVA\r"), "the numbered object is kept as it was"); + assert_eq!(before.path(&["1", "1"]).and_then(E::as_array).and_then(|s| s.first()), slots.first(), "the numbered object changes not at all"); +} + +/// When both lists hold the layer's text, the block is written back byte for byte — #2374 holds +/// for the older objects too: re-encoding them would only risk Photoshop refusing the file. +#[test] +fn unchanged_block_with_both_object_lists_is_byte_identical() { + use photocraft_doc::text::Kerning; + let mut prev = photoshop_txt2(&[(4, 1)]); + prev.extend_from_slice(&crate::engine_data::write_bare(&[("DocumentObjects".into(), photoshop_era_objects(&["AVA"]))])); + let t = styled("AVA", CharStyle { kerning: Kerning::Metrics, ..Default::default() }); + assert_eq!(crate::psd::build_txt2(&[(0, &t)], Some(&prev)), prev); +} + +/// An entry shaped unlike Photoshop writes it — a run without its `/Length`, a `RunArray` that +/// isn't an array, an empty one, an object with no text to replace — is left exactly as the file +/// has it: a half-refitted object (new text over old runs) is what made Photoshop quit (#6968), +/// so the save never writes one. +#[test] +fn odd_photoshop_era_entries_are_left_as_the_file_has_them() { + use crate::engine_data::Value as E; + use photocraft_doc::text::Kerning; + let run = |len: i64| E::Dict(vec![("RunData".into(), E::dict()), ("Length".into(), E::Int(len))]); + let entry = |model: Vec<(&str, E)>| { + E::Dict(vec![("Model".into(), E::Dict(model.into_iter().map(|(k, v)| (k.to_string(), v)).collect())), ("View".into(), E::dict())]) + }; + let with_text = |text: E, style: E| { + entry(vec![ + ("Text", text), + ("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))])), + ("StyleRun", E::Dict(vec![("RunArray".into(), style)])), + ]) + }; + let odd = [ + with_text(E::String("Old\r".into()), E::Array(vec![E::Dict(vec![("RunData".into(), E::dict())])])), + with_text(E::String("Old\r".into()), E::Int(3)), + with_text(E::String("Old\r".into()), E::Array(vec![])), + E::Int(3), + entry(vec![("ParagraphRun", E::Dict(vec![("RunArray".into(), E::Array(vec![run(4)]))]))]), + with_text(E::Int(9), E::Array(vec![run(4)])), + ]; + for (i, object) in odd.iter().enumerate() { + let prev = crate::engine_data::write_bare(&[ + ("98".into(), E::Dict(vec![("0".into(), E::Int(14))])), + ("0".into(), E::dict()), + ("DocumentObjects".into(), E::Dict(vec![("TextObjects".into(), E::Array(vec![object.clone()]))])), + ]); + let was = crate::psd::parse_txt2(&prev).unwrap(); + let t = styled("New", CharStyle { kerning: Kerning::Optical, ..Default::default() }); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &t)], Some(&prev))).unwrap(); + let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects"); + assert_eq!( + entries.first(), + was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first()), + "entry {i} is left as the file has it" + ); + } +} + +/// A `TextIndex` past the entries the block holds has no stale copy to fix: nothing is grown to +/// the layer's number (the slot list grows as it always did), and the entries stay the file's. +#[test] +fn a_text_index_beyond_the_photoshop_era_entries_grows_nothing() { + use crate::engine_data::Value as E; + use photocraft_doc::text::Kerning; + let prev = photoshop_era_txt2(&["Only one"]); + let was = crate::psd::parse_txt2(&prev).unwrap(); + let t = styled("Whatever", CharStyle { kerning: Kerning::Optical, ..Default::default() }); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(crate::psd::MAX_TEXT_INDEX, &t)], Some(&prev))).unwrap(); + let entries = out.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).expect("the objects"); + assert_eq!(entries.len(), 1, "no entry is grown to the layer's number"); + assert_eq!(entries.first(), was.path(&["DocumentObjects", "TextObjects"]).and_then(E::as_array).and_then(|e| e.first())); +} + /// A `Txt2` shaped like Photoshop's: document resources and settings beside the text objects /// (`/0`, `/1 /0`, `/1 /2`), style runs carrying a full style (font, size, leading) besides the /// auto-kern mode, a Latin-1 string without a byte-order mark, reals, and a second object no From 755ca9e2a0c3eca56b0dc556dc8363b6bda235a9 Mon Sep 17 00:00:00 2001 From: FartmanAndBurps <345790579+FartmanAndBurps@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:31:08 +0100 Subject: [PATCH 21/27] feat(print): add interactive preview positioning Drag the visible image in the print preview using paper-scaled egui points. Switch Center to manual without moving the grab point, allow signed Top/Left offsets, and retain the shared preview/PDF layout and mirrored behavior. Add regression coverage for negative PDF placement, native HiDPI dragging, centering, clipping, scaling, fit, mirroring and invalid geometry. Validation: 25 engine print tests, 19 file-dialog unit tests, four print-dialog integration tests and the adversarial-command test pass. Formatting, all-target clippy, desktop check/build and layer checks pass. Three existing socket-binding tests are sandbox-blocked and excluded from the successful print-suite rerun. GUI capture and wasm checks remain limited by the environment. --- crates/engine/src/print_cmds.rs | 22 +++- crates/engine/src/print_cmds/tests.rs | 58 +++++++++ crates/ui-egui/src/file_ui.rs | 136 +++++++++++++++++++-- crates/ui-egui/tests/custom_print_paper.rs | 94 +++++++++++++- docs/printing.md | 16 +++ 5 files changed, 307 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9b264f0611..e747f7db6f 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -490,6 +490,9 @@ pub struct PrintLayout { pub emulsion_down: bool, } +/// Symmetric safety bound for manual Top/Left offsets, shared with the dialog (inches). +pub const MAX_POSITION_INCHES: f64 = 10000.0; + /// The print layout for `doc` with Print parameters `p` (used by the dialog's preview too). pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result { let (pw, ph) = paper(p, cmd)?; @@ -513,10 +516,25 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result { ((pw - w) / 2.0, (ph - h) / 2.0) } else { // Top / left in inches from the paper's top-left corner (Photoshop's Position fields). - let top = p.get("top").and_then(Value::as_f64).unwrap_or(0.0) * 72.0; - let left = p.get("left").and_then(Value::as_f64).unwrap_or(0.0) * 72.0; + let position = |key: &str| -> Result { + let value = match p.get(key) { + None => 0.0, + Some(v) => v.as_f64().ok_or_else(|| bad(cmd, "print positions must be finite numbers in inches"))?, + }; + if !value.is_finite() || value.abs() > MAX_POSITION_INCHES { + return Err(bad(cmd, "print positions must be within -10000 to 10000 inches")); + } + Ok(value * 72.0) + }; + let top = position("top")?; + let left = position("left")?; (left, ph - top - h) }; + // Guard geometry before converting to screen points or writing PDF operators. Even a + // finite JSON scale can overflow when multiplied by document dimensions. + if ![pw, ph, x, y, w, h, scale].into_iter().all(|v| v.is_finite() && v.abs() <= 1.0e9) || w <= 0.0 || h <= 0.0 { + return Err(bad(cmd, "print layout must have finite geometry within 1000000000 points and positive image dimensions")); + } let emulsion_down = p.get("emulsionDown").and_then(Value::as_bool).unwrap_or(false); Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down }) } diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 38567ffb6d..f96f5e0654 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -1,6 +1,64 @@ use super::*; use photocraft_doc::{Knot, NamedPath, Path, Subpath}; +#[test] +fn negative_print_positions_match_pdf_without_changing_the_document() { + let dir = tmp("negative-position"); + for (scale, fit, landscape, mirrored) in + [(100.0, false, false, false), (175.0, false, true, false), (50.0, true, false, false), (100.0, false, false, true)] + { + let mut s = session("rgb", 8); + let before = s.active().unwrap().doc.clone(); + let revision = s.active().unwrap().revision; + let path = format!("{dir}/{scale}-{fit}-{landscape}-{mirrored}.pdf"); + let p = json!({"paper": "a4", "center": false, "left": -0.5, "top": -0.25, + "scale": scale, "scaleToFit": fit, "orientation": if landscape {"landscape"} else {"portrait"}, + "emulsionDown": mirrored, "output": path, "send": false, "dryRun": true}); + let preview = layout(&before, &p, "file.print").unwrap(); + let (x, y, w, h) = preview.rect; + assert_eq!(x, -36.0); + assert!((preview.paper.1 - y - h + 18.0).abs() < 1e-9); + assert!((w / h - 2.0).abs() < 1e-9); + if !fit { + assert!((w - 300.0 * scale / 100.0).abs() < 1e-9); + } else { + assert!((w - (preview.paper.0 - 36.0)).abs() < 1e-9); + } + let result = s.execute("file.print", p).unwrap(); + assert_eq!(result["sent"], false); + assert_eq!(result["imageRect"], json!([x, y, w, h])); + let pdf = std::fs::read(path).unwrap(); + let content = pdf_content(&pdf); + assert!(content.contains(&format!("q {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q"))); + assert_eq!(content.contains(&format!("q -1 0 0 1 {:.2} 0 cm", preview.paper.0)), mirrored); + let after = s.active().unwrap(); + assert_eq!(after.revision, revision); + assert_eq!(after.doc.size, before.size); + assert_eq!(after.doc.resolution_dpi, before.resolution_dpi); + assert_eq!(photocraft_compose::thumbnail(&before, 32).pixels, photocraft_compose::thumbnail(&after.doc, 32).pixels); + } +} + +#[test] +fn print_position_and_geometry_bounds_reject_malformed_inputs() { + let s = session("rgb", 8); + let doc = &s.active().unwrap().doc; + for key in ["top", "left"] { + for value in [json!(-10000.0), json!(10000.0), json!(-0.125)] { + let mut p = json!({"center": false}); + p[key] = value; + assert!(layout(doc, &p, "file.print").is_ok()); + } + for value in [json!(1e308), json!(-10001.0), json!("NaN"), Value::Null] { + let mut p = json!({"center": false}); + p[key] = value; + assert!(layout(doc, &p, "file.print").is_err()); + } + } + assert!(layout(doc, &json!({"scale": 1e308}), "file.print").is_err()); + assert!(layout(doc, &json!({"paper": [1e308, 792]}), "file.print").is_err()); +} + fn tmp(name: &str) -> String { let d = std::env::temp_dir().join(format!("photocraft-print-{}-{name}", std::process::id())); let _ = std::fs::remove_dir_all(&d); diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 32f97bc4e8..65bc4fa499 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -841,6 +841,10 @@ fn length_field(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str) -> bo } fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32) -> bool { + length_field_range(ui, label, pt, units, decimals, 0.0..=10000.0) +} + +fn length_field_range(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32, range: std::ops::RangeInclusive) -> bool { let t = Tokens::get(ui.ctx()); let k = unit_pt(units); let mut v = (*pt / k) as f32; @@ -848,7 +852,7 @@ fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, ui.horizontal(|ui| { ui.label(egui::RichText::new(label).color(t.text_dim)); let before = v; - crate::widgets::value_field_prec(ui, &mut v, 0.0..=10000.0, units, 70.0, decimals); + crate::widgets::value_field_prec(ui, &mut v, range, units, 70.0, decimals); if (v - before).abs() > 1e-4 && v.is_finite() { *pt = f64::from(v) * k; changed = true; @@ -919,6 +923,32 @@ fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) { } } +/// Both the pointer and the painter use egui points, including on Retina displays. +/// Applying pixels_per_point here would count the display scale a second time. +fn drag_print_position(f: &mut Map, start: photocraft_engine::print_cmds::PrintLayout, delta: egui::Vec2, points_per_print_point: f32) -> bool { + if !points_per_print_point.is_finite() || points_per_print_point <= 0.0 || !delta.is_finite() { + return false; + } + let (x, y, _, h) = start.rect; + let direction = if start.emulsion_down { -1.0 } else { 1.0 }; + let left = (x + direction * f64::from(delta.x) / f64::from(points_per_print_point)) / 72.0; + let top = (start.paper.1 - y - h + f64::from(delta.y) / f64::from(points_per_print_point)) / 72.0; + if !left.is_finite() || !top.is_finite() { + return false; + } + let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES; + f.insert("center".into(), json!(false)); + f.insert("left".into(), json!(left.clamp(-limit, limit))); + f.insert("top".into(), json!(top.clamp(-limit, limit))); + true +} + +fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, page: egui::Rect, k: f32) -> egui::Rect { + let (x, y, w, h) = l.rect; + let x = if l.emulsion_down { l.paper.0 - x - w } else { x }; + egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k)) +} + fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; @@ -946,19 +976,39 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { + Ok(mut l) => { let (pw, ph) = l.paper; let k = ((area.width() - 20.0) / pw as f32).min((area.height() - 20.0) / ph as f32); let page = egui::Rect::from_center_size(area.center(), egui::vec2(pw as f32 * k, ph as f32 * k)); ui.painter().rect_filled(page, 0.0, egui::Color32::WHITE); ui.painter().rect_stroke(page, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); + let mut img = print_preview_image(l, page, k); + let drag_id = ui.id().with(("print-position", id)); + let visible = img.intersect(page).intersect(ui.clip_rect()); + let response = ui.interact(visible, drag_id, egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Image, true, tl!("Print preview image"))); + // Keep a fixed layout and press origin for the whole gesture: rounding and + // the transition from Center must never accumulate or move the grab point. + if response.drag_started_by(egui::PointerButton::Primary) + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + { + ui.data_mut(|d| d.insert_temp(drag_id, (l, origin, k))); + } + if (response.dragged_by(egui::PointerButton::Primary) || response.drag_stopped_by(egui::PointerButton::Primary)) + && let Some((start, origin, scale)) = ui.data(|d| d.get_temp::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)) + && let Some(pointer) = response.interact_pointer_pos() + && drag_print_position(f, start, pointer - origin, scale) + { + if let Ok(updated) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") { + l = updated; + img = print_preview_image(l, page, k); + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } + if !ui.input(|i| i.pointer.primary_down()) { + ui.data_mut(|d| d.remove::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)); + } let (x, y, w, h) = l.rect; - // Emulsion Down shows the page as it prints: mirrored. - let x = if l.emulsion_down { pw - x - w } else { x }; - let img = egui::Rect::from_min_size( - egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), - egui::vec2(w as f32 * k, h as f32 * k), - ); let key = egui::Id::new(("print-thumb", doc.id.0, app.session.active().map_or(0, |d| d.revision))); let tex: Option> = ui.data(|d| d.get_temp(key)); let tex = tex.unwrap_or_else(|| { @@ -1138,17 +1188,24 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map (PhotocraftApp, egui::Context) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap(); diff --git a/crates/ui-egui/tests/custom_print_paper.rs b/crates/ui-egui/tests/custom_print_paper.rs index d0d81dea69..6363464ef2 100644 --- a/crates/ui-egui/tests/custom_print_paper.rs +++ b/crates/ui-egui/tests/custom_print_paper.rs @@ -1,6 +1,9 @@ //! #3820: edit custom paper through the real Print dialog, preview it, and print safely to PDF. use egui::{Event, Key, Modifiers, PointerButton, vec2}; -use egui_kittest::{Harness, kittest::Queryable}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; use photocraft_ui_egui::{PhotocraftApp, file_ui::open_print}; use serde_json::{Map, Value, json}; @@ -22,7 +25,11 @@ fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp) { } fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).with_max_steps(64).build_ui_state(show, app); + harness_at_scale(app, 1.0) +} + +fn harness_at_scale(app: PhotocraftApp, pixels_per_point: f32) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).with_pixels_per_point(pixels_per_point).with_max_steps(64).build_ui_state(show, app); PhotocraftApp::setup_context(&h.ctx, Default::default()); h.run_steps(4); h @@ -42,8 +49,8 @@ fn shown(h: &Harness<'_, PhotocraftApp>, text: &str) -> bool { } fn enter_length(h: &mut Harness<'_, PhotocraftApp>, label: &str, value: &str) { - // Anchor the pointer to the real label; the existing length widget immediately follows it. - let pos = h.get_by_label(label).rect().right_center() + vec2(35.0, 0.0); + // Use the editor's actual accessibility bounds rather than a fixed offset from its label. + let pos = h.get_by_label(label).parent().unwrap().get_by_role(egui::accesskit::Role::SpinButton).rect().center(); h.event(Event::PointerMoved(pos)); h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); h.run_steps(1); @@ -60,6 +67,85 @@ fn fields(h: &Harness<'_, PhotocraftApp>, id: u64) -> Map { h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone() } +fn painted_image(h: &Harness<'_, PhotocraftApp>) -> egui::Rect { + let active = h.state().session.active().unwrap(); + let key = egui::Id::new(("print-thumb", active.doc.id.0, active.revision)); + let tex = h.ctx.data(|d| d.get_temp::>(key)).unwrap(); + h.output() + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == tex.id() => Some(mesh.calc_bounds()), + _ => None, + }) + .expect("the print image must be painted") +} + +#[test] +fn preview_drag_and_negative_fields_work_at_standard_and_retina_scale() { + for pixels_per_point in [1.0, 2.0] { + let (mut app, id) = app(); + app.ui + .dialog_mut(id) + .unwrap() + .fields + .extend(json!({"paper": "a4", "center": true, "scale": 100, "scaleToFit": false, "units": "cm"}).as_object().unwrap().clone()); + let mut h = harness_at_scale(app, pixels_per_point); + let start = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap(); + let start_image = painted_image(&h); + let from = start_image.center(); + let delta = vec2(-24.0, 18.0); + h.event(Event::PointerMoved(from)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for step in 1..=3 { + h.event(Event::PointerMoved(from + delta * (step as f32 / 3.0))); + h.run_steps(1); + } + let during = fields(&h, id); + assert_eq!(during["center"], false, "Center must switch off during the drag"); + // The hit target was registered before this frame's pointer handling. Inspect the + // actual painted mesh to verify the image moves immediately, without a frame of lag. + let moved_image = painted_image(&h); + assert!( + (moved_image.min - start_image.min - delta).length() < 0.1, + "the visible image must stay under the pointer when Center turns off: {start_image:?} -> {moved_image:?}, delta {delta:?}" + ); + let k = (310.0 / start.paper.0).min(380.0 / start.paper.1); + assert!((during["left"].as_f64().unwrap() * 72.0 - start.rect.0 - f64::from(delta.x) / k).abs() < 0.001); + assert!((during["top"].as_f64().unwrap() * 72.0 - (start.paper.1 - start.rect.1 - start.rect.3) - f64::from(delta.y) / k).abs() < 0.001); + h.event(Event::PointerButton { pos: from + delta, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + click(&mut h, "Centimeters"); + click(&mut h, "Inches"); + enter_length(&mut h, "Top", "-0.25"); + enter_length(&mut h, "Left", "-0.5"); + let negative = fields(&h, id); + assert_eq!(negative["top"], -0.25); + assert_eq!(negative["left"], -0.5); + let visible = h.get_by_label("Print preview image").rect(); + assert!(visible.is_positive(), "a partly off-page image must retain a visible drag target"); + let from = visible.center(); + h.event(Event::PointerMoved(from)); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + // Keep capture even when both the pointer and image leave the sheet entirely. + h.event(Event::PointerMoved(from - vec2(400.0, 0.0))); + h.run_steps(2); + assert!(fields(&h, id)["left"].as_f64().unwrap() < -1.0); + h.event(Event::PointerMoved(from + vec2(12.0, 12.0))); + h.run_steps(2); + assert!(fields(&h, id)["left"].as_f64().unwrap() > -0.5); + h.event(Event::PointerButton { pos: from + vec2(12.0, 12.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + click(&mut h, "Center"); + let centered = photocraft_engine::print_cmds::layout(&h.state().session.active().unwrap().doc, &Value::Object(fields(&h, id)), "file.print").unwrap(); + assert_eq!(fields(&h, id)["center"], true); + assert!((centered.rect.0 - (centered.paper.0 - centered.rect.2) / 2.0).abs() < 1e-9); + assert!((centered.rect.1 - (centered.paper.1 - centered.rect.3) / 2.0).abs() < 1e-9); + } +} + #[test] fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() { let (mut app, id) = app(); diff --git a/docs/printing.md b/docs/printing.md index 399944d57d..7b5d2a93fe 100644 --- a/docs/printing.md +++ b/docs/printing.md @@ -5,6 +5,22 @@ position and scale, crop and registration marks, labels, colour handling) and ha to a printer. The rendering is `print_cmds.rs` in `photocraft-engine`, shared by the dialog, the batch commands and automation (`file.print`, `file.printOneCopy`); this page is about the hand-off. +## Positioning the preview + +Drag the visible image on the paper to change Top and Left. Starting a drag switches Center +off using the currently resolved layout, including Scale to Fit Media, so the image stays at +the grab point. Top/Left stay visible but disabled while Center is on, keeping the dialog and +paper stationary when a drag enables them. Position fields accept negative values in inches, centimetres or millimetres; +the stored command parameters are inches from the sheet's top-left. Manual positions are +bounded to ±10000 inches. Height, width and paper dimensions retain their positive fields. + +The preview converts egui point displacement to PDF points using its paper display scale. +No extra Retina pixel factor is needed: painting and pointer input both use egui points. +Emulsion Down reverses the horizontal position change to match the mirrored output. The image +is clipped to the paper; any visible portion remains a drag target. A completely off-page image +can be recovered with Top/Left or Center. These controls affect print parameters only, and +the preview and generated PDF continue to share `print_cmds::layout`. + ## Routes to the printer | Route | When | What the user sees | From 9f9209c5cc1454aa1a28045d10a6b405966cf4d6 Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Wed, 21 Oct 2026 08:15:14 -0400 Subject: [PATCH 22/27] Clipboard: a panic while reading the clipboard is reported, not a crash (refs #7582) The OS clipboard read (arboard, plus decoding a copied file with photocraft-codecs) and write now run under crash_guard::guard, like Open and Export. A panic there becomes the paste's error in the status bar and the app keeps its documents, instead of closing. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 40 +++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 999952f186..589b399bd4 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -414,6 +414,17 @@ fn recovery_services(dir: Option) -> Services { } } +/// The OS clipboard read and write run under the crash guard, like Open and Export (#7582): a +/// panic in arboard, or in decoding a copied file, becomes the paste's (or copy's) error and the +/// app keeps its documents. +fn guarded_clipboard_get(mut read: impl FnMut() -> Result)>, String> + 'static) -> photocraft_ui_egui::ClipboardGetFn { + Box::new(move || crate::crash_guard::guard("Paste", &mut read)) +} + +fn guarded_clipboard_set(mut write: impl FnMut(u32, u32, &[u8]) -> Result<(), String> + 'static) -> photocraft_ui_egui::ClipboardSetFn { + Box::new(move |w: u32, h: u32, px: &[u8]| crate::crash_guard::guard("Copy", || write(w, h, px))) +} + /// The pixels to paste when the clipboard holds copied files rather than an image (Copy in /// Files, Finder or Explorer puts paths on the clipboard, #338): the first file that decodes, /// upright, as RGBA8. Files that aren't images are skipped after reading only their header. @@ -558,7 +569,7 @@ pub fn native(automation: Option) -> beep: Some(platform_beep), clipboard_set_image: Some({ let clip = clip.clone(); - Box::new(move |w: u32, h: u32, px: &[u8]| { + guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| { let mut slot = clip.try_borrow_mut().map_err(|_| "clipboard is busy".to_string())?; let cb = match slot.as_mut() { Some(c) => c, @@ -570,7 +581,7 @@ pub fn native(automation: Option) -> clipboard_get_image: Some({ let clip = clip.clone(); let unreadable = clip_unreadable.clone(); - Box::new(move || { + guarded_clipboard_get(move || { let mut slot = clip.try_borrow_mut().map_err(|_| "clipboard is busy".to_string())?; let cb = match slot.as_mut() { Some(c) => c, @@ -1289,4 +1300,29 @@ mod tests { assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); assert!(image_from_files(&[bin]).is_none()); } + + /// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is + /// the paste's error in the status bar, not a crash: the document stays and the next paste + /// works. The same for a panic while writing it. + #[test] + fn a_panicking_clipboard_read_is_reported_not_a_crash() { + let panics = Rc::new(Cell::new(true)); + let p = panics.clone(); + let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) }); + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() }); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + + let error = app.run("edit.paste", json!({})).unwrap_err(); + assert!(error.contains("Paste failed"), "{error}"); + assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged"); + + panics.set(false); + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works"); + + let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug")); + assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed")); + } } From ff8dc65c8208218a371be9bfeddb720262f7aef1 Mon Sep 17 00:00:00 2001 From: Aditya Vishwakarma <72960955+adi-1108@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:52:05 +0530 Subject: [PATCH 23/27] test(io): cover PSD palette boundaries and bitmap row packing Co-Authored-By: Claude Opus 5.5 --- crates/io/src/palette_map.rs | 141 +++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index b268efcb9c..a41cdc782e 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -124,3 +124,144 @@ fn bits(doc: &Document) -> Vec { }); out } + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_color::{Color, SampleType}; + use photocraft_doc::Size; + + fn document(width: u32, height: u32, depth: SampleType, mode: ColorMode, pixels: &[f32]) -> Document { + let mut doc = Document::with_background("palette test", Size::new(width, height), ColorMode::Rgb, depth, Color::rgba(0.0, 0.0, 0.0, 1.0)); + let bounds = doc.bounds(); + doc.layers[0].surface_mut().unwrap().write_region(bounds, pixels); + doc.mode = mode; + doc + } + + fn round_trip(doc: &Document) -> (PsdFile, Document) { + let (file, _) = document_to_psd(doc, false).unwrap(); + let bytes = file.to_bytes().unwrap(); + let file = PsdFile::from_bytes(&bytes).unwrap(); + let back = crate::import("test.psd", &bytes).unwrap().document; + (file, back) + } + + #[test] + fn full_palette_endpoints_round_trip_with_either_transparent_endpoint() { + let colors: Vec<_> = (0..=255).map(|v| [v, 255 - v, v / 2]).collect(); + for transparent in [0, 255] { + let opaque = 255 - transparent; + let rgb = colors[usize::from(opaque)].map(|v| f32::from(v) / 255.0); + let mut doc = document(2, 1, SampleType::U8, ColorMode::Indexed, &[rgb[0], rgb[1], rgb[2], 1.0, 0.0, 0.0, 0.0, 0.0]); + doc.color_table = Some(ColorTable { colors: colors.clone(), transparent: Some(transparent) }); + let (file, back) = round_trip(&doc); + assert_eq!((file.header.color_mode, file.header.depth, file.header.channels), (PsdMode::Indexed, 8, 1)); + assert_eq!(file.decode_merged().unwrap(), [opaque, transparent]); + assert_eq!(file.resource(COLOR_TABLE_COUNT).unwrap().data, [1, 0]); + assert_eq!(file.color_mode_data.len(), 768); + for (i, c) in colors.iter().enumerate() { + assert_eq!([file.color_mode_data[i], file.color_mode_data[256 + i], file.color_mode_data[512 + i]], *c); + } + assert_eq!(back.color_table, doc.color_table); + let surface = back.layers[0].surface().unwrap(); + assert_eq!(surface.pixel(0, 0), vec![rgb[0], rgb[1], rgb[2], 1.0]); + assert_eq!(surface.pixel(1, 0)[3], 0.0); + } + } + + #[test] + fn indexed_alpha_threshold_uses_stored_samples_at_all_depths() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = document(3, 1, depth, ColorMode::Indexed, &[0.0, 0.0, 0.0, 0.49, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.51]); + doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: Some(1) }); + let (file, back) = round_trip(&doc); + assert_eq!(file.decode_merged().unwrap(), [1, 0, 0], "{depth:?}"); + let surface = back.layers[0].surface().unwrap(); + assert_eq!((0..3).map(|x| surface.pixel(x, 0)[3]).collect::>(), [0.0, 1.0, 1.0]); + } + } + + #[test] + fn small_palette_zero_pads_unused_entries_and_rejects_invalid_lengths() { + let mut doc = document(1, 1, SampleType::U8, ColorMode::Indexed, &[1.0, 0.0, 0.0, 1.0]); + doc.color_table = Some(ColorTable { colors: vec![[255, 0, 0]], transparent: None }); + let (file, back) = round_trip(&doc); + assert_eq!(file.color_mode_data[0], 255); + assert!(file.color_mode_data[1..].iter().all(|&v| v == 0)); + assert_eq!(back.color_table, doc.color_table); + for count in [0, 257] { + doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0]; count], transparent: None }); + assert!(document_to_psd(&doc, false).is_none(), "{count}"); + } + doc.color_table = None; + assert!(document_to_psd(&doc, false).is_none()); + } + + #[test] + fn indexed_import_bounds_malformed_count_and_transparency_resources() { + let mut doc = document(1, 1, SampleType::U8, ColorMode::Indexed, &[0.0, 0.0, 0.0, 1.0]); + doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: None }); + let (original, _) = document_to_psd(&doc, false).unwrap(); + for (count, expected) in [(vec![0, 0], 1), (vec![1, 1], 256), (vec![255, 255], 256), (vec![0], 256)] { + let mut file = original.clone(); + file.resources.retain(|r| r.id != COLOR_TABLE_COUNT); + file.resources.push(ImageResource::new(COLOR_TABLE_COUNT, count)); + file.resources.push(ImageResource::new(TRANSPARENCY_INDEX, vec![255, 255])); + let bytes = file.to_bytes().unwrap(); + let back = crate::import("malformed.psd", &bytes).unwrap().document; + let table = back.color_table.unwrap(); + assert_eq!(table.colors.len(), expected); + assert_eq!(table.transparent, None); + assert_eq!(back.layers[0].surface().unwrap().pixel(0, 0)[3], 1.0); + } + } + + #[test] + fn bitmap_rows_are_msb_first_and_independently_byte_padded() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for width in [1u32, 7, 8, 9, 15, 17] { + // Opposite rows expose padding carried into the next row or reversed bit order. + let pixels: Vec<_> = (0..2) + .flat_map(|y| { + (0..width).flat_map(move |x| { + let v = if (x + y) % 2 == 0 { 0.0 } else { 1.0 }; + [v, v, v, 1.0] + }) + }) + .collect(); + let doc = document(width, 2, depth, ColorMode::Bitmap, &pixels); + let (file, back) = round_trip(&doc); + assert_eq!((file.header.color_mode, file.header.depth, file.header.channels), (PsdMode::Bitmap, 1, 1)); + let mut expected = Vec::new(); + for y in 0..2 { + for byte in 0..width.div_ceil(8) { + let mut packed = 0; + for bit in 0..8 { + let x = byte * 8 + bit; + if x < width && (x + y) % 2 == 0 { + packed |= 0x80 >> bit; + } + } + expected.push(packed); + } + } + assert_eq!(file.decode_merged().unwrap(), expected, "{depth:?}, width={width}"); + assert!(file.color_mode_data.is_empty()); + assert_eq!(back.mode, ColorMode::Bitmap); + let gray_alpha: Vec<_> = pixels.as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[3]]).collect(); + assert_eq!(back.layers[0].surface().unwrap().read_region(back.bounds()), gray_alpha); + } + } + } + + #[test] + fn bitmap_alpha_is_flattened_over_white_before_thresholding() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let doc = document(3, 1, depth, ColorMode::Bitmap, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.49, 0.0, 0.0, 0.0, 0.51]); + let (file, back) = round_trip(&doc); + assert_eq!(file.decode_merged().unwrap(), [0x20], "{depth:?}"); + assert_eq!(back.layers[0].surface().unwrap().read_region(back.bounds()), [1.0, 1.0, 1.0, 1.0, 0.0, 1.0]); + } + } +} From a0c6af075cea6aaf24cdb290317455ba390f2b80 Mon Sep 17 00:00:00 2001 From: FartmanAndBurps <345790579+FartmanAndBurps@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:36:49 +0100 Subject: [PATCH 24/27] docs(print): explain interactive positioning coordinates and safeguards --- crates/engine/src/print_cmds.rs | 11 +++++++++- crates/engine/src/print_cmds/tests.rs | 4 ++++ crates/ui-egui/src/file_ui.rs | 24 ++++++++++++++++++++-- crates/ui-egui/tests/custom_print_paper.rs | 6 ++++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index e747f7db6f..fba485a2c0 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -493,7 +493,16 @@ pub struct PrintLayout { /// Symmetric safety bound for manual Top/Left offsets, shared with the dialog (inches). pub const MAX_POSITION_INCHES: f64 = 10000.0; -/// The print layout for `doc` with Print parameters `p` (used by the dialog's preview too). +/// Resolves the shared preview/PDF layout without changing `doc`. +/// +/// Paper and image bounds use points (72 per inch), with the image origin at bottom-left. +/// Manual `top`/`left` are inches from the paper's top-left; negative values place artwork +/// off-page. Center ignores these offsets. Scale to Fit preserves the aspect ratio and uses +/// the available paper area after the existing mark margins, overriding percentage scale. +/// Emulsion Down is recorded for rendering; the returned rectangle is not yet mirrored. +/// +/// Returns an error for malformed manual offsets or offsets beyond [`MAX_POSITION_INCHES`], +/// nonfinite geometry, geometry magnitudes above 1e9, or nonpositive image dimensions. pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result { let (pw, ph) = paper(p, cmd)?; let dpi = f64::from(doc.resolution_dpi.max(1.0)); diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index f96f5e0654..dee6240f46 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -1,6 +1,8 @@ use super::*; use photocraft_doc::{Knot, NamedPath, Path, Subpath}; +/// Compares signed-offset layout with actual PDF image operators and whole-page mirroring +/// across scale/fit/orientation cases, while checking the source document stays unchanged. #[test] fn negative_print_positions_match_pdf_without_changing_the_document() { let dir = tmp("negative-position"); @@ -39,6 +41,8 @@ fn negative_print_positions_match_pdf_without_changing_the_document() { } } +/// Checks inclusive signed inch limits, malformed manual offsets and overflow-prone scale +/// or paper inputs at the shared layout boundary, without invoking a printer. #[test] fn print_position_and_geometry_bounds_reject_malformed_inputs() { let s = session("rgb", 8); diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 65bc4fa499..8350a1b1b8 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -840,10 +840,14 @@ fn length_field(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str) -> bo length_field_prec(ui, label, pt, units, 0) } +/// Edits a point-valued length in the selected units, with the requested decimal precision. +/// Retains the nonnegative 0..=10000 display-unit range used by existing size fields. fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32) -> bool { length_field_range(ui, label, pt, units, decimals, 0.0..=10000.0) } +/// Edits a length stored in print points (72 per inch), returning true for a finite edit. +/// `range` is in the displayed `units`; a signed range permits negative Top/Left offsets. fn length_field_range(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32, range: std::ops::RangeInclusive) -> bool { let t = Tokens::get(ui.ctx()); let k = unit_pt(units); @@ -923,8 +927,14 @@ fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) { } } -/// Both the pointer and the painter use egui points, including on Retina displays. -/// Applying pixels_per_point here would count the display scale a second time. +/// Converts total displacement from a fixed drag-start layout into manual inch offsets. +/// Resolving Center before the drag avoids a jump; each update replaces the offsets rather +/// than accumulating movement. Emulsion Down reverses horizontal layout-space movement. +/// +/// `delta` and the painter use egui points, including on Retina displays; the scale is egui +/// points per print point (1/72 inch). Applying pixels_per_point would count HiDPI twice. +/// Invalid scales or nonfinite displacement/offsets return false without changing fields. +/// Accepted offsets are clamped to the engine's safety bound and Center is disabled. fn drag_print_position(f: &mut Map, start: photocraft_engine::print_cmds::PrintLayout, delta: egui::Vec2, points_per_print_point: f32) -> bool { if !points_per_print_point.is_finite() || points_per_print_point <= 0.0 || !delta.is_finite() { return false; @@ -943,12 +953,18 @@ fn drag_print_position(f: &mut Map, start: photocraft_engine::pri true } +/// Maps the engine's bottom-left print-point rectangle into top-left egui coordinates. +/// `k` is egui points per print point; Emulsion Down mirrors placement across the page, +/// matching the PDF page transform. Returns the full image bounds for the caller to clip. fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, page: egui::Rect, k: f32) -> egui::Rect { let (x, y, w, h) = l.rect; let x = if l.emulsion_down { l.paper.0 - x - w } else { x }; egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k)) } +/// Draws the print controls and paper-clipped preview using the engine's shared layout. +/// Dragging the visible image updates dialog offsets live from a fixed gesture origin; +/// the position row stays present while centered so switching to manual cannot move the page. fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; @@ -1298,6 +1314,8 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { mod tests { use super::*; + /// Checks no-jump centering and nonaccumulating screen displacement against shared layout + /// across fit, percentage scaling, orientation and mirroring combinations. #[test] fn print_drag_uses_the_resolved_layout_and_screen_points_without_accumulation() { let (app, _) = app(); @@ -1334,6 +1352,8 @@ mod tests { } } + /// Checks rejected pointer geometry leaves fields untouched and extreme finite drags + /// clamp both inch offsets to the same safety limits as numeric positioning. #[test] fn print_drag_rejects_nonfinite_input_and_bounds_offsets() { let (app, _) = app(); diff --git a/crates/ui-egui/tests/custom_print_paper.rs b/crates/ui-egui/tests/custom_print_paper.rs index 6363464ef2..4aa53eb96d 100644 --- a/crates/ui-egui/tests/custom_print_paper.rs +++ b/crates/ui-egui/tests/custom_print_paper.rs @@ -28,6 +28,8 @@ fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { harness_at_scale(app, 1.0) } +/// Builds the real dialog at an explicit physical-pixels-per-egui-point ratio so pointer +/// events remain in egui points while exercising both standard and Retina display scales. fn harness_at_scale(app: PhotocraftApp, pixels_per_point: f32) -> Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(vec2(1000.0, 900.0)).with_pixels_per_point(pixels_per_point).with_max_steps(64).build_ui_state(show, app); PhotocraftApp::setup_context(&h.ctx, Default::default()); @@ -67,6 +69,8 @@ fn fields(h: &Harness<'_, PhotocraftApp>, id: u64) -> Map { h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone() } +/// Finds the thumbnail's painted mesh bounds, rather than the earlier interaction bounds, +/// so drag assertions detect visible lag in the same frame as a Center transition. fn painted_image(h: &Harness<'_, PhotocraftApp>) -> egui::Rect { let active = h.state().session.active().unwrap(); let key = egui::Id::new(("print-thumb", active.doc.id.0, active.revision)); @@ -81,6 +85,8 @@ fn painted_image(h: &Harness<'_, PhotocraftApp>) -> egui::Rect { .expect("the print image must be painted") } +/// Exercises live painted movement at 1x/2x display scale, signed numeric entry and pointer +/// capture off-page and back, then verifies Center restores the shared layout's placement. #[test] fn preview_drag_and_negative_fields_work_at_standard_and_retina_scale() { for pixels_per_point in [1.0, 2.0] { From 3e44821c63790c8e7010e8cf276452b97de0b65a Mon Sep 17 00:00:00 2001 From: Mani Arasteh Date: Fri, 16 Oct 2026 16:36:27 +0330 Subject: [PATCH 25/27] test(ui): cover tool memory persistence --- crates/ui-egui/src/tool_memory.rs | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 80fefe8ad7..592f957a06 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -248,3 +248,50 @@ fn nulls(v: &Value) -> usize { _ => 0, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selected_tool_and_non_default_options_roundtrip() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Move; + app.ui.tool_options.tolerance = 42.5; + persist(&mut app, &egui::Context::default()); + + let saved = app.session.prefs(); + assert_eq!(saved.selected_tool, serde_json::to_value(Tool::Move).unwrap()); + assert_eq!(saved.tool_options["tolerance"], Value::from(42.5)); + assert!(saved.tool_options.get("contiguous").is_none(), "unchanged defaults are not written"); + + let mut restored = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + restored.session.prefs.edit(|p| { + p.selected_tool = saved.selected_tool.clone(); + p.tool_options = saved.tool_options.clone(); + }); + restore(&mut restored); + assert_eq!(restored.ui.tool, Tool::Move); + assert_eq!(restored.ui.tool_options.tolerance, 42.5); + } + + #[test] + fn restore_ignores_unknown_and_malformed_tool_options() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let original_tool = app.ui.tool; + let default_contiguous = ToolOptions::default().contiguous; + app.session.prefs.edit(|p| { + p.selected_tool = Value::from("not-a-tool"); + p.tool_options = serde_json::json!({ + "tolerance": 42.5, + "contiguous": "not a boolean", + "future_option": true + }); + }); + + restore(&mut app); + assert_eq!(app.ui.tool, original_tool, "an invalid selected tool leaves the current tool intact"); + assert_eq!(app.ui.tool_options.tolerance, 42.5, "valid fields still restore"); + assert_eq!(app.ui.tool_options.contiguous, default_contiguous, "a malformed field falls back to its default"); + } +} From 0edfe05f2c6019dc4f91e23302cf61c5434910d8 Mon Sep 17 00:00:00 2001 From: Ian Swope Date: Wed, 21 Oct 2026 13:42:06 -0500 Subject: [PATCH 26/27] Compose: effect maps that don't fit in the effect cache are built over the render rect, not rebuilt whole on every render (#8330) A render needs every layer's effect maps. On a large document whose ordinary layers' whole-region maps take more than the effect cache budget together, building one evicted the next one needed, so every render, of any size, built them all again: 1.8-4.4 s per render on a 9000x6000 document with three full drop-shadowed layers. When they don't fit, local maps are now built over the render rect padded by twice the effects' reach, as a shapeless layer's already are (#1909), which gives the same pixels there. --- crates/compose/src/lib.rs | 43 +++++++++++++++- crates/compose/src/tests.rs | 99 +++++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2ed1873a9d..3bf93c4c94 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -399,6 +399,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { vector_masks: RenderVectorMasks::default(), fx_maps: Default::default(), fx_clip: Default::default(), + fx_over_budget: false, tone_luts: prepare_tones(std::slice::from_ref(layer), 0), doc: None, layer_keys: Default::default(), @@ -749,6 +750,9 @@ struct Ctx<'a> { fx_maps: std::sync::Mutex, bool)>>, /// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`]. fx_clip: std::sync::Mutex>, + /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache + /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330). + fx_over_budget: bool, /// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer. doc: Option<&'a Document>, /// Effect-map identities of this render's document layers (see [`LayerKeys`]). @@ -820,6 +824,7 @@ impl<'a> Ctx<'a> { vector_masks: RenderVectorMasks::default(), fx_maps: Default::default(), fx_clip: Default::default(), + fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()), layer_keys: Default::default(), tone_luts: prepare_tones(&doc.layers, 0), } @@ -1973,7 +1978,9 @@ fn fx_cache() -> &'static std::sync::Mutex { /// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for /// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local /// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded -/// by twice the effect reach instead, which gives the same pixels there. Only when `rect`, what +/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local +/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]). +/// Only when `rect`, what /// the caller composites the layer over, lies within the render rectangle: a group's effect shape /// (or anything else rendering children over a wider area) gets the whole region. fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { @@ -1981,7 +1988,7 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m)); let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); match clip { - Some(c) if c.contains_rect(&rect) && advanced::shapeless(layer) && effects::maps_are_local(layer) => { + Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => { let part = region.intersect(&c.inflate(m.saturating_mul(2))); (part, part != region) } @@ -1989,6 +1996,38 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { } } +/// Whether the effect maps of the visible layers of `layers` (groups included), each over its +/// whole region, would take more than the effect cache budget together. A render needs all of +/// them, so when they don't fit, building one evicts the next one needed and every render builds +/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`] +/// counts them, with only the shape and one map per enabled effect: a lower bound. +fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool { + fx_region_bytes(layers, canvas) > effect_cache_budget() as u64 +} + +/// The lower bound [`fx_over_budget`] compares with the budget. +fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 { + fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 { + let mut total = 0u64; + for l in layers.iter().filter(|l| l.visible) { + if effects::has_effects(l) { + let m = effects::margin(l); + let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m)); + let maps = 1 + l.effects.items.iter().filter(|e| e.enabled()).count() as u64; + let px = u64::from(region.width()) * u64::from(region.height()); + total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4)); + } + if let LayerContent::Group(g) = &l.content + && depth < PREPARE_DEPTH + { + total = total.saturating_add(bytes(&g.children, canvas, depth + 1)); + } + } + total + } + bytes(layers, canvas, 0) +} + /// The layer's effect maps over its region (layer bounds grown by the effect reach, within the /// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every /// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 99823457fa..707ea98c8c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1665,6 +1665,105 @@ fn shapeless_effect_maps_cover_only_the_band_being_rendered() { ); } +/// [`shapeless_fx_doc`] with Transparency Shapes Layer back on everywhere: ordinary layers, whose +/// effect regions are their own bounds grown by the effects' reach. +fn ordinary_fx_doc(depth: SampleType) -> Document { + fn shaped(layers: &mut [Layer]) { + for l in layers { + l.advanced.transparency_shapes = true; + if let LayerContent::Group(g) = &mut l.content { + shaped(&mut g.children); + } + } + } + let mut d = shapeless_fx_doc(depth); + shaped(&mut d.layers); + d +} + +#[test] +fn effect_maps_over_the_cache_budget_are_built_over_the_render_rect() { + // #8330: an ordinary layer's maps cover its whole region, so on a large document a render's + // layers can need more than the effect cache holds; building one then evicts the next one + // needed, and every render, however small, builds them all again. Over the budget, local maps + // are built over the render rect (plus twice the reach), as a shapeless layer's are (#1909). + let d = ordinary_fx_doc(SampleType::U8); + let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES); + // A row through fx8 (pixels at y 552..570, an outside stroke and an inner glow). + let band = Rect::new(0, 561, 48, 562); + let mut cx = Ctx::for_doc(&d, &patterns); + assert!(!cx.fx_over_budget, "a small document fits"); + let l = &d.layers[9]; + let whole = effect_region(l, band, &cx); + cx.set_fx_clip(band); + assert_eq!(effect_region(l, band, &cx), whole, "under the budget: the whole region"); + cx.fx_over_budget = true; + let (part, clipped) = effect_region(l, band, &cx); + assert_eq!(part, whole.0.intersect(&band.inflate(2 * effects::margin(l)))); + assert!(clipped && part.height() < whole.0.height(), "{part:?} vs {:?}", whole.0); + let built = effect_maps(l, band, &cx).bytes(); + cx.fx_over_budget = false; + cx.set_fx_clip(Rect::new(0, 0, 1, 1)); + cx.set_fx_clip(band); + assert!(built < effect_maps(l, band, &cx).bytes()); + cx.fx_over_budget = true; + // Composited over more than the band, and maps that aren't local: the whole region. + assert_eq!(effect_region(l, Rect::new(0, 500, 48, 600), &cx), whole); + let noisy = &d.layers[2]; + assert!(!effects::maps_are_local(noisy)); + cx.set_fx_clip(Rect::new(0, 100, 48, 140)); + assert!(!effect_region(noisy, Rect::new(0, 100, 48, 140), &cx).1); +} + +#[test] +fn renders_with_maps_clipped_over_the_budget_match_the_whole_maps() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let d = ordinary_fx_doc(depth); + let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES); + purge_effect_cache(); + let whole = render(&d, d.bounds()); + let mut cx = Ctx::for_doc(&d, &patterns); + cx.fx_over_budget = true; + // Bands, edit-sized parts and single tiles, each from maps built over it alone. + purge_effect_cache(); + let bands = (0..10).map(|i| Rect::new(0, i * 64, 48, (i + 1) * 64)); + let parts = [Rect::new(3, 290, 41, 333), Rect::new(0, 0, 48, 20), Rect::new(20, 600, 48, 640), Rect::new(0, 296, 20, 312), Rect::new(10, 425, 40, 445)]; + for r in bands.chain(parts) { + let p = render_tiled_with(&d, r, RENDER_TILE, &cx); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + assert_eq!(p.get(x, y), whole.get(x, y), "{depth:?}: {r:?} differs at ({x},{y})"); + } + } + } + assert!(render_tiled_with(&d, d.bounds(), 16, &cx).px == whole.px, "{depth:?}: tiled render differs"); + } +} + +#[test] +fn the_effect_map_estimate_is_a_lower_bound() { + // fx_over_budget compares a lower bound of the maps' bytes with the budget: it must not + // exceed what building them takes, or a document that fits would lose its shared maps. + let d = ordinary_fx_doc(SampleType::U8); + let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES); + let cx = Ctx::for_doc(&d, &patterns); + let mut todo = Vec::new(); + effect_layers(&d.layers, d.bounds(), 0, &mut todo); + let built: usize = todo.iter().map(|l| effect_maps(l, d.bounds(), &cx).bytes()).sum(); + let estimate = fx_region_bytes(&d.layers, d.bounds()); + assert!(estimate > 0 && estimate <= built as u64, "estimate {estimate} B, built {built} B"); + // A 9000 x 6000 document with three full layers, each with a drop shadow (#8330's case): + // about 1.3 GB, over the default 768 MB. One such layer fits. + let mut big = Document::with_background("big", Size::new(9000, 6000), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("fill", big.pixel_format()); + l.surface_mut().unwrap().fill_rect(big.bounds(), &photocraft_raster::from_rgba(&big.pixel_format(), [0.8, 0.5, 0.3, 1.0])); + l.effects.items = vec![Effect::DropShadow(Shadow { size: 40.0, ..shadow(20.0, 120.0) })]; + big.layers.push(l.clone()); + assert!(fx_region_bytes(&big.layers, big.bounds()) < DEFAULT_FX_CACHE_BUDGET as u64); + big.layers.extend([l.clone(), l]); + assert!(fx_region_bytes(&big.layers, big.bounds()) > DEFAULT_FX_CACHE_BUDGET as u64); +} + // ---------- PSD-fidelity effect semantics (fitted on Photoshop composites) ---------- #[test] From 052c1c3ab7e5577a7bd032e1bb28830db102c541 Mon Sep 17 00:00:00 2001 From: Tom Ingling Date: Wed, 21 Oct 2026 17:03:02 -0400 Subject: [PATCH 27/27] Layers: per-layer XMP metadata, as Photoshop's layer.xmpMetadata A layer keeps its own XMP packet (Layer::xmp), where scripts and embedding apps store data about the layer under their own namespaces. - PSD/PSB/layered TIFF: read from and written to shmd > cust > layerXMP (UTF-16, NUL-terminated, after layerTime), laid out as Photoshop 2026 writes it; an unchanged Photoshop block round-trips byte for byte. - .pcraft: optional `xmp` on each layer. - layer.xmpMetadata {layer?, rawData?}: read, set (one undo step) or remove with null; refuses malformed XML, DTDs, NUL and > 4 MiB. - Duplicate Layer copies the packet; document.inspect reports hasXmp. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 5 + crates/engine/src/commands.rs | 1 + crates/engine/src/inspect.rs | 1 + crates/engine/src/layer_multi_cmds.rs | 3 +- crates/engine/src/layer_xmp_cmds.rs | 96 +++++++++++++ crates/engine/src/layer_xmp_cmds/tests.rs | 106 +++++++++++++++ crates/engine/src/lib.rs | 1 + crates/format/src/convert.rs | 2 + crates/format/src/manifest.rs | 3 + crates/io/src/psd_export.rs | 15 ++ crates/io/src/psd_import.rs | 13 ++ crates/io/tests/layer_xmp.rs | 102 ++++++++++++++ crates/psd/README.md | 1 + crates/psd/src/metadata.rs | 159 +++++++++++++++++++++- docs/file-format-parity.md | 2 +- 15 files changed, 507 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/layer_xmp_cmds.rs create mode 100644 crates/engine/src/layer_xmp_cmds/tests.rs create mode 100644 crates/io/tests/layer_xmp.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 268b0b6b43..f2ee0d3823 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -659,6 +659,10 @@ pub struct Layer { pub advanced: AdvancedBlending, /// Layer › Video Layers frame stack (None for a normal layer). pub video: Option, + /// The layer's own XMP packet (Photoshop's `layer.xmpMetadata.rawData`), where scripts and + /// embedding apps keep data about the layer under their own namespaces. Copied by + /// [`Layer::duplicate`], as in Photoshop. PSD `shmd` › `cust` › `layerXMP`. + pub xmp: Option>, } impl Layer { @@ -692,6 +696,7 @@ impl Layer { blend_if: BlendIf::default(), advanced: AdvancedBlending::default(), video: None, + xmp: None, } } pub fn raster(name: impl Into, format: PixelFormat) -> Self { diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index b7dff3e9fd..1e44edca2b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -1495,6 +1495,7 @@ fn build() -> Vec { v.extend(crate::adjust_cmds::specs()); v.extend(crate::layer_menu_cmds::specs()); v.extend(crate::layer_label_cmds::specs()); + v.extend(crate::layer_xmp_cmds::specs()); v.extend(crate::mode_cmds::specs()); v.extend(crate::multichannel_cmds::specs()); v.extend(crate::pattern_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 22696e9307..d2938b745e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -106,6 +106,7 @@ fn layer_sel(l: &Layer, selected: &[photocraft_doc::LayerId], instances: &HashMa "bounds": bounds, "selected": selected.contains(&l.id), "linkGroup": l.link_group, + "hasXmp": l.xmp.is_some(), }); match &l.content { LayerContent::Group(g) => { diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index a9f121c9fb..6276290f54 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -622,7 +622,7 @@ fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::Al /// compared here: the caller walks into them, so an edit inside a group damages only the /// edited child's extent, not the whole group's. The destructure is exhaustive, so a new /// `Layer` field fails to compile until it is classified: compared, or explicitly ignored -/// (name, locks, label, `psd_blocks`, `psd_id`, link group — none of them composite; video +/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video /// bails out earlier in the walk). fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { let Layer { @@ -647,6 +647,7 @@ fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { blend_if, advanced, video: _, + xmp: _, } = a; *id == b.id && *visible == b.visible diff --git a/crates/engine/src/layer_xmp_cmds.rs b/crates/engine/src/layer_xmp_cmds.rs new file mode 100644 index 0000000000..4fb4eda32f --- /dev/null +++ b/crates/engine/src/layer_xmp_cmds.rs @@ -0,0 +1,96 @@ +//! A layer's own XMP packet, as Photoshop scripts reach it through `layer.xmpMetadata.rawData`: +//! scripts and embedding apps keep data about a layer there under their own namespaces. It is +//! saved in PSD, PSB, layered TIFF and `.pcraft`, and copied when the layer is duplicated. + +use std::sync::Arc; + +use photocraft_doc::LayerId; +use serde_json::{Map, Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const ID: &str = "layer.xmpMetadata"; + +/// Largest packet accepted, in UTF-8 bytes. Every history state shares the packet, but a PSD +/// stores it as UTF-16 in each layer's record. +pub const MAX_LAYER_XMP: usize = 4 << 20; + +fn bad(message: impl Into) -> EngineError { + EngineError::BadParams { cmd: ID.into(), msg: message.into() } +} + +fn enabled(s: &Session) -> std::result::Result<(), String> { + crate::active_layer_of(s).map(|_| ()) +} + +/// `raw` if it is an XMP packet: well-formed XML (no DTD) whose root is `x:xmpmeta` or +/// `rdf:RDF`, without NUL characters (Photoshop stores the packet NUL-terminated). +fn check_packet(raw: &str) -> Result<()> { + if raw.len() > MAX_LAYER_XMP { + return Err(bad(format!("`rawData` is {} bytes; the most a layer holds is {MAX_LAYER_XMP}", raw.len()))); + } + if raw.contains('\0') { + return Err(bad("`rawData` can't contain NUL characters")); + } + let xml = roxmltree::Document::parse(raw).map_err(|e| bad(format!("`rawData` isn't well-formed XML: {e}")))?; + let root = xml.root_element().tag_name(); + let xmp = matches!((root.namespace(), root.name()), (Some("adobe:ns:meta/"), "xmpmeta") | (Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF")); + if !xmp { + return Err(bad("`rawData` must be an XMP packet: its root element is x:xmpmeta or rdf:RDF")); + } + Ok(()) +} + +fn xmp_metadata(s: &mut Session, p: &Value) -> Result { + let empty = Map::new(); + let p = match p { + Value::Null => &empty, + Value::Object(m) => m, + _ => return Err(bad("expected an object")), + }; + let st = s.active().ok_or(EngineError::NoDocument)?; + let id = match p.get("layer") { + Some(v) => LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?), + None => st.active_layer.ok_or_else(|| bad("no active layer"))?, + }; + let current = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?.xmp.clone(); + let new = match p.get("rawData") { + None => return Ok(json!({"layer": id.0, "rawData": current.as_deref(), "changed": false})), + Some(Value::Null) => None, + Some(Value::String(raw)) => { + check_packet(raw)?; + Some(raw.as_str()) + } + Some(_) => return Err(bad("`rawData` must be a string (an XMP packet) or null (remove it)")), + }; + let changed = current.as_deref() != new; + if changed { + let stored: Option> = new.map(Into::into); + s.edit("Layer Metadata", move |doc, _| { + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.xmp = stored; + Ok(()) + })?; + if let Some(st) = s.active_mut() { + // Saved metadata only; no canvas pixels need recompositing. + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + } + } + Ok(json!({"layer": id.0, "rawData": new, "changed": changed})) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: ID, + label: "Layer XMP Metadata", + menu: &[], + shortcut: None, + params: r#"{"layer":id?,"rawData":string|null?} → {"layer","rawData","changed"} (no layer: the active layer; no rawData: read it; a string sets the layer's XMP packet, null removes it; as Photoshop's layer.xmpMetadata.rawData)"#, + enabled, + run: xmp_metadata, + journal: true, + }] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/layer_xmp_cmds/tests.rs b/crates/engine/src/layer_xmp_cmds/tests.rs new file mode 100644 index 0000000000..015f739399 --- /dev/null +++ b/crates/engine/src/layer_xmp_cmds/tests.rs @@ -0,0 +1,106 @@ +use super::*; +use photocraft_doc::Layer; + +const PACKET: &str = r#"120"#; + +fn fixture(depth: u8) -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "depth": depth})).unwrap(); + let (a, b) = s + .edit("Fixture", |doc, _| { + let a = Layer::raster("A", doc.pixel_format()); + let b = Layer::group("B", vec![Layer::raster("Child", doc.pixel_format())]); + let ids = (a.id, b.id); + doc.layers = vec![a, b]; + Ok(ids) + }) + .unwrap(); + s.select_layer(a).unwrap(); + (s, a, b) +} + +fn xmp(s: &Session, id: LayerId) -> Option { + s.active().unwrap().doc.layer(id).unwrap().xmp.as_deref().map(str::to_string) +} + +#[test] +fn sets_reads_and_removes_as_one_undo_step_each() { + for depth in [8, 16, 32] { + let (mut s, a, b) = fixture(depth); + assert_eq!(s.execute(ID, json!({})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": false})); + let past = s.active().unwrap().history.past_len(); + let before = s.active().unwrap().doc.clone(); + + // The active layer by default; a group by id. + assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap(), json!({"layer": a.0, "rawData": PACKET, "changed": true})); + assert_eq!(s.execute(ID, json!({"layer": b.0, "rawData": PACKET})).unwrap()["changed"], true); + assert_eq!(s.active().unwrap().history.past_len(), past + 2); + assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY)); + assert_eq!(s.execute(ID, Value::Null).unwrap()["rawData"], PACKET); + assert_eq!(crate::inspect::layer(s.active().unwrap().doc.layer(b).unwrap())["hasXmp"], true); + + // Only the packets changed. + let mut expected = (*before).clone(); + for id in [a, b] { + expected.layer_mut(id).unwrap().xmp = Some(PACKET.into()); + } + assert_eq!(*s.active().unwrap().doc, expected, "depth {depth}"); + + // The same packet again is not an edit. + assert_eq!(s.execute(ID, json!({"rawData": PACKET})).unwrap()["changed"], false); + assert_eq!(s.active().unwrap().history.past_len(), past + 2); + + assert_eq!(s.execute(ID, json!({"rawData": null})).unwrap(), json!({"layer": a.0, "rawData": null, "changed": true})); + assert_eq!(xmp(&s, a), None); + assert!(s.undo()); + assert_eq!(xmp(&s, a).as_deref(), Some(PACKET)); + assert!(s.undo() && s.undo()); + assert_eq!(s.active().unwrap().doc, before); + assert!(s.redo()); + assert_eq!(xmp(&s, a).as_deref(), Some(PACKET)); + } +} + +#[test] +fn duplicating_a_layer_copies_its_packet() { + let (mut s, a, _) = fixture(8); + s.execute(ID, json!({"rawData": PACKET})).unwrap(); + s.execute("layer.duplicate", json!({})).unwrap(); + let copy = s.active().unwrap().active_layer.unwrap(); + assert_ne!(copy, a); + assert_eq!(xmp(&s, copy).as_deref(), Some(PACKET)); +} + +#[test] +fn refuses_what_is_not_an_xmp_packet() { + let (mut s, a, _) = fixture(8); + let refused = |s: &mut Session, p: Value| matches!(s.execute(ID, p), Err(EngineError::BadParams { .. })); + for p in [ + json!([]), + json!({"layer": "A"}), + json!({"rawData": 7}), + json!({"rawData": ""}), + json!({"rawData": ""}), + json!({"rawData": ""}), + json!({"rawData": "\u{0}"}), + json!({"rawData": "]>&a;"}), + json!({"rawData": format!("{}", "a".repeat(MAX_LAYER_XMP))}), + ] { + assert!(refused(&mut s, p.clone()), "{p:.80}"); + } + let r = s.execute(ID, json!({"layer": 999_999_999})); + assert!(matches!(r, Err(EngineError::UnknownLayer { .. })), "{r:?}"); + assert_eq!(xmp(&s, a), None); + // A bare RDF root and a packet wrapper are packets. + let rdf = r#""#; + assert_eq!(s.execute(ID, json!({"rawData": rdf})).unwrap()["changed"], true); + let wrapped = format!("{PACKET}"); + assert_eq!(s.execute(ID, json!({"rawData": wrapped})).unwrap()["changed"], true); +} + +#[test] +fn needs_a_document_and_a_layer() { + let mut s = Session::new(); + assert!(matches!(s.execute(ID, json!({})), Err(EngineError::Disabled(..)))); + assert!(enabled(&s).is_err()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5a7aa83dfb..ed1ab49113 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,6 +74,7 @@ pub mod layer_menu_cmds; pub mod layer_multi_cmds; pub mod layer_nav_cmds; pub mod layer_style; +pub mod layer_xmp_cmds; pub mod lens_cmds; pub mod link_watch; pub mod magnetic_cmds; diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 3f21e7e47c..fda505dcff 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -211,6 +211,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { blend_if: l.blend_if.clone(), advanced: l.advanced, video: l.video.as_ref().map(|v| video_m(v, sink)), + xmp: l.xmp.as_deref().map(str::to_string), } } @@ -547,6 +548,7 @@ impl Loader<'_> { blend_if: m.blend_if.clone(), advanced: m.advanced, video: m.video.as_ref().map(|v| self.video(v)).transpose()?, + xmp: m.xmp.as_deref().map(Arc::from), }) } diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 8cb31f653e..72192c79f6 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -242,6 +242,9 @@ pub struct LayerM { pub advanced: photocraft_doc::AdvancedBlending, #[serde(default)] pub video: Option, + /// The layer's own XMP packet (missing in older files = none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub xmp: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4c3ec0047b..baf4c0e9cd 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -726,9 +726,24 @@ impl Ex { let id = self.layer_ids.get(&l.id).copied().unwrap_or(0); crate::comps_map::set_cmls(&mut raw, crate::comps_map::write_cmls(comps, last.as_ref(), l, id)); } + self.layer_xmp_block(l, &mut raw); regenerated.into_iter().chain(raw).map(|(k, d)| TaggedBlock::new(k, d)).collect() } + /// Writes the layer's XMP packet into its `shmd` block (created when it has none). Import + /// takes the packet out of `shmd`, so a layer without one keeps the block as it was. + fn layer_xmp_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec)>) { + let Some(xmp) = l.xmp.as_deref() else { return }; + let pos = raw.iter().position(|(k, _)| k == b"shmd"); + match photocraft_psd::metadata::put_layer_xmp(pos.map(|i| raw[i].1.as_slice()), xmp) { + Ok(data) => match pos { + Some(i) => raw[i].1 = data, + None => raw.push((*b"shmd", data)), + }, + Err(e) => self.warnings.push(format!("layer \"{}\": its XMP metadata was not saved (its metadata block can't be read: {e})", l.name)), + } + } + /// Keeps, regenerates or removes the `vmsk`/`vsms` block of a non-shape layer. fn vector_mask_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec)>) { let (w, h) = (self.canvas.width(), self.canvas.height()); diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 8a948aa6e2..ace640affc 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -330,6 +330,19 @@ impl Ctx<'_> { // Blend If lives in the layer record's blending ranges. l.blend_if = crate::blocks::blend_if_from_ranges(&rec.blending_ranges); l.psd_id = rec.layer_id(); + // The layer's XMP packet (`shmd` › `cust` › `layerXMP`) becomes the field; the rest of + // `shmd` stays in `psd_blocks`, where export puts the packet back. + if let Some(i) = l.psd_blocks.iter().position(|(k, _)| k == b"shmd") + && let Some((xmp, rest)) = photocraft_psd::metadata::take_layer_xmp(&l.psd_blocks[i].1) + { + l.xmp = Some(Arc::from(xmp)); + match rest { + Some(data) => l.psd_blocks[i].1 = Arc::new(data), + None => { + l.psd_blocks.remove(i); + } + } + } let name = l.name.clone(); l.mask = self.record_mask(rec, &name); } diff --git a/crates/io/tests/layer_xmp.rs b/crates/io/tests/layer_xmp.rs new file mode 100644 index 0000000000..87a02b0876 --- /dev/null +++ b/crates/io/tests/layer_xmp.rs @@ -0,0 +1,102 @@ +//! A layer's own XMP packet (`Layer::xmp`, PSD `shmd` › `cust` › `layerXMP`) survives every +//! layered format and keeps the rest of a Photoshop `shmd` block as it was. + +use std::sync::Arc; + +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, Size}; +use photocraft_io::{ExportOptions, export, import}; +use photocraft_psd::PsdFile; +use photocraft_psd::metadata::{layer_xmp, put_layer_xmp}; + +const A: &str = r#"120"#; +const G: &str = r#"Café 🎨"#; + +/// `shmd` of a Photoshop 2026 layer without XMP: a `cust` item holding only `layerTime`. +const PS_WITHOUT_XMP: &str = + "000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00"; + +fn unhex(h: &str) -> Vec { + (0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect() +} + +fn xmps(d: &Document) -> Vec<(String, Option)> { + d.walk().into_iter().map(|(_, _, l)| (l.name.clone(), l.xmp.as_deref().map(str::to_string))).collect() +} + +fn layer_shmd<'a>(f: &'a PsdFile, name: &str) -> Option<&'a [u8]> { + f.layers().iter().find(|r| r.name() == name).and_then(|r| r.block(b"shmd")).map(|b| b.data.as_slice()) +} + +fn sample(depth: SampleType) -> Document { + let mut doc = Document::new("Layer XMP", Size::new(4, 4), ColorMode::Rgb, depth); + let mut a = Layer::raster("A", doc.pixel_format()); + a.xmp = Some(Arc::from(A)); + let plain = Layer::raster("Plain", doc.pixel_format()); + let mut g = Layer::group("G", vec![plain]); + g.xmp = Some(Arc::from(G)); + doc.layers.extend([a, g]); + doc +} + +#[test] +fn layer_xmp_round_trips_through_every_layered_format_and_depth() { + let psb = ExportOptions { force_psb: true, ..Default::default() }; + let tiff = ExportOptions { tiff_layers: true, ..Default::default() }; + for depth in SampleType::ALL { + let doc = sample(depth); + for (path, opts) in [("x.psd", &ExportOptions::default()), ("x.psb", &psb), ("x.tif", &tiff), ("x.pcraft", &ExportOptions::default())] { + let bytes = export(&doc, path, opts).unwrap().bytes; + let back = import(path, &bytes).unwrap().document; + assert_eq!(xmps(&back), xmps(&doc), "{path} {depth:?}"); + } + // Stored as Photoshop stores it; a layer without XMP gets no block. + let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes; + let f = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(layer_shmd(&f, "A").and_then(layer_xmp).as_deref(), Some(A)); + assert_eq!(layer_shmd(&f, "G").and_then(layer_xmp).as_deref(), Some(G)); + assert!(layer_shmd(&f, "Plain").is_none()); + } +} + +#[test] +fn photoshop_shmd_keeps_its_other_data() { + let without = unhex(PS_WITHOUT_XMP); + let with = put_layer_xmp(Some(&without), A).unwrap(); + // A layer as an older PhotoCraft kept it: Photoshop's block verbatim, no field. + let mut doc = Document::new("PS", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + let mut l = Layer::raster("L", doc.pixel_format()); + l.psd_blocks.push((*b"shmd", Arc::new(with.clone()))); + doc.layers.push(l); + let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes; + + // Opening it gives the packet to the field and keeps the rest of the block. + let mut back = import("x.psd", &bytes).unwrap().document; + let l = &back.layers[0]; + assert_eq!(l.xmp.as_deref(), Some(A)); + assert_eq!(l.psd_blocks.iter().find(|(k, _)| k == b"shmd").map(|(_, d)| d.as_slice()), Some(without.as_slice())); + + // Unchanged, the block is written back byte for byte. + let again = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes; + assert_eq!(layer_shmd(&PsdFile::from_bytes(&again).unwrap(), "L"), Some(with.as_slice())); + + // Edited, `layerTime` stays; removed, the block is Photoshop's block without XMP. + back.layers[0].xmp = Some(Arc::from(G)); + let edited = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes; + assert_eq!(layer_shmd(&PsdFile::from_bytes(&edited).unwrap(), "L"), Some(put_layer_xmp(Some(&without), G).unwrap().as_slice())); + back.layers[0].xmp = None; + let removed = export(&back, "x.psd", &ExportOptions::default()).unwrap().bytes; + assert_eq!(layer_shmd(&PsdFile::from_bytes(&removed).unwrap(), "L"), Some(without.as_slice())); +} + +#[test] +fn an_unreadable_shmd_is_kept_and_reported() { + let mut doc = Document::new("Bad", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + let mut l = Layer::raster("L", doc.pixel_format()); + l.psd_blocks.push((*b"shmd", Arc::new(vec![0, 0, 0, 9]))); + l.xmp = Some(Arc::from(A)); + doc.layers.push(l); + let out = export(&doc, "x.psd", &ExportOptions::default()).unwrap(); + assert!(out.warnings.iter().any(|w| w.contains("XMP metadata was not saved")), "{:?}", out.warnings); + assert_eq!(layer_shmd(&PsdFile::from_bytes(&out.bytes).unwrap(), "L"), Some([0, 0, 0, 9].as_slice())); +} diff --git a/crates/psd/README.md b/crates/psd/README.md index d745fd5bd8..b26a33dff6 100644 --- a/crates/psd/README.md +++ b/crates/psd/README.md @@ -106,6 +106,7 @@ testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_pla | PSB 8-byte-length keys | ✓ | ✓ | – | LMsk Lr16 Lr32 Layr Mt16 Mt32 Mtrn Alph FMsk lnk2 FEid FXid PxSD | | Lr16 / Lr32 / Layr layer info | ✓ | ✓ | ✓ | lifted into `layer_info`; re-inserted at its original position | | luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` | +| Layer XMP (`shmd` › `cust` › `layerXMP`) | ✓ | ✓ | ✓ | `metadata::layer_xmp` / `take_layer_xmp` / `put_layer_xmp`, laid out as Photoshop 2026 writes it | | ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper | | Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting | | RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone | diff --git a/crates/psd/src/metadata.rs b/crates/psd/src/metadata.rs index 9e85d8cee7..24d2eebca6 100644 --- a/crates/psd/src/metadata.rs +++ b/crates/psd/src/metadata.rs @@ -1,11 +1,12 @@ //! `shmd` (metadata setting) layer block: a list of keyed sub-blocks, such as `cmls` (layer comp -//! state, a versioned descriptor), `cust` and `mlst`. +//! state, a versioned descriptor), `cust` (the layer's modify time and XMP packet) and `mlst`. //! //! Layout (Adobe PSD spec, "Metadata setting"): u32 count, then per item the signature `8BIM`, //! a 4-byte key, a copy-on-sheet-duplication byte, 3 padding bytes, a u32 length and the data. //! Photoshop pads item data to an even length (the padding is part of the stored length), so //! parsing and writing are exact: `write(parse(b)) == b`. +use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt}; @@ -71,10 +72,166 @@ pub fn write_shmd(items: &[MetadataItem]) -> Vec { out } +/// The `shmd` item that holds a layer's own metadata (its modify time and XMP). +const CUST: [u8; 4] = *b"cust"; +/// Key of a layer's XMP packet in the `cust` descriptor. +const LAYER_XMP: &str = "layerXMP"; + +// A layer's XMP packet (Photoshop's `layer.xmpMetadata.rawData`), as observed in files Photoshop +// 2026 saves: a `TEXT` item `layerXMP` (UTF-16 with a terminating NUL) in the `metadata` +// descriptor (version 16, class name a lone NUL) of the `shmd` item `cust`, after the +// `layerTime` double that every Photoshop layer has. A layer without XMP has no `layerXMP` item. + +fn pad_even(mut v: Vec) -> Vec { + if v.len() % 2 == 1 { + v.push(0); + } + v +} + +/// The `cust` descriptor of `item`, or `None` when it isn't one. +fn cust_descriptor(item: &MetadataItem) -> Option { + (item.key == CUST).then(|| VersionedDescriptor::parse_prefix(&item.data).ok().map(|(d, _)| d)).flatten() +} + +/// The XMP packet stored on a layer whose `shmd` block data is `shmd`, or `None` when it has +/// none (or the block can't be read). +pub fn layer_xmp(shmd: &[u8]) -> Option { + let items = parse_shmd(shmd).ok()?; + items.iter().filter_map(cust_descriptor).find_map(|d| match d.descriptor.get(LAYER_XMP) { + Some(Value::Text(t)) => Some(t.to_string_lossy()), + _ => None, + }) +} + +/// Splits a layer's XMP packet out of its `shmd` block data: the packet, and the block without +/// it (`None` when nothing is left). `None` when the block holds no packet, so the caller keeps +/// the original bytes. A `cust` item left empty is dropped, the other items are kept as stored. +pub fn take_layer_xmp(shmd: &[u8]) -> Option<(String, Option>)> { + let mut items = parse_shmd(shmd).ok()?; + let (i, mut vd) = items.iter().enumerate().find_map(|(i, it)| cust_descriptor(it).filter(|d| d.descriptor.get(LAYER_XMP).is_some()).map(|d| (i, d)))?; + let at = vd.descriptor.items.iter().position(|(k, _)| k.is(LAYER_XMP))?; + let xmp = match vd.descriptor.items.remove(at).1 { + Value::Text(t) => t.to_string_lossy(), + _ => return None, + }; + if vd.descriptor.items.is_empty() { + items.remove(i); + } else { + items[i].data = pad_even(vd.to_bytes()); + } + Some((xmp, (!items.is_empty()).then(|| write_shmd(&items)))) +} + +/// `shmd` block data (`shmd`, or a new block when `None`) with `xmp` as the layer's XMP packet, +/// written as Photoshop writes it: it replaces an existing packet in place, or is appended to +/// the `cust` descriptor (a new `cust` item when there is none). An unreadable block is an +/// error, so the caller never replaces data it couldn't read. +pub fn put_layer_xmp(shmd: Option<&[u8]>, xmp: &str) -> Result> { + let mut items = match shmd { + Some(b) => parse_shmd(b)?, + None => Vec::new(), + }; + let value = Value::Text(UnicodeString::new_nul(xmp)); + match items.iter().position(|it| it.key == CUST) { + Some(i) => { + let (mut vd, _) = VersionedDescriptor::parse_prefix(&items[i].data)?; + match vd.descriptor.items.iter_mut().find(|(k, _)| k.is(LAYER_XMP)) { + Some(entry) => entry.1 = value, + None => vd.descriptor.items.push((Id::new(LAYER_XMP), value)), + } + items[i].data = pad_even(vd.to_bytes()); + } + None => { + let d = Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("metadata"), items: vec![(Id::new(LAYER_XMP), value)] }; + items.push(MetadataItem::new(CUST, VersionedDescriptor::new(d).to_bytes())); + } + } + Ok(write_shmd(&items)) +} + #[cfg(test)] mod tests { use super::*; + fn unhex(lines: &[&str]) -> Vec { + let h: String = lines.concat(); + (0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect() + } + + /// `shmd` of a layer saved by Photoshop 2026 after a script set its XMP to [`PS_PACKET`]. + const PS_WITH_XMP: &[&str] = &[ + "000000013842494d63757374000000000000024800000010000000010000000000086d65746164617461000000020000", + "00096c6179657254696d65646f756241dab643ffd54363000000086c61796572584d505445585400000100003c007800", + "3a0078006d0070006d00650074006100200078006d006c006e0073003a0078003d002200610064006f00620065003a00", + "6e0073003a006d006500740061002f0022003e003c007200640066003a00520044004600200078006d006c006e007300", + "3a007200640066003d00220068007400740070003a002f002f007700770077002e00770033002e006f00720067002f00", + "31003900390039002f00300032002f00320032002d007200640066002d00730079006e007400610078002d006e007300", + "230022003e003c007200640066003a004400650073006300720069007000740069006f006e0020007200640066003a00", + "610062006f00750074003d0022002200200078006d006c006e0073003a00730061006d0070006c0065003d0022006800", + "7400740070003a002f002f006500780061006d0070006c0065002e0063006f006d002f00730061006d0070006c006500", + "2f0031002e0030002f0022003e003c00730061006d0070006c0065003a00760061006c00750065003e0061006c007000", + "680061002d003100320033003c002f00730061006d0070006c0065003a00760061006c00750065003e003c002f007200", + "640066003a004400650073006300720069007000740069006f006e003e003c002f007200640066003a00520044004600", + "3e003c002f0078003a0078006d0070006d006500740061003e000000", + ]; + /// `shmd` of a layer without XMP in the same file (its own `layerTime` only). + const PS_WITHOUT_XMP: &[&str] = + &["000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00"]; + const PS_PACKET: &str = concat!( + r#""#, + r#"alpha-123"#, + r#""# + ); + + #[test] + fn reads_photoshop_layer_xmp() { + assert_eq!(layer_xmp(&unhex(PS_WITH_XMP)).as_deref(), Some(PS_PACKET)); + assert_eq!(layer_xmp(&unhex(PS_WITHOUT_XMP)), None); + assert!(take_layer_xmp(&unhex(PS_WITHOUT_XMP)).is_none()); + } + + #[test] + fn take_then_put_is_exact() { + let ps = unhex(PS_WITH_XMP); + let (xmp, rest) = take_layer_xmp(&ps).unwrap(); + assert_eq!(xmp, PS_PACKET); + let rest = rest.unwrap(); + // What's left is a layer without XMP, shaped as Photoshop writes one. + assert_eq!(rest.len(), unhex(PS_WITHOUT_XMP).len()); + assert_eq!(layer_xmp(&rest), None); + assert_eq!(put_layer_xmp(Some(&rest), &xmp).unwrap(), ps); + } + + #[test] + fn put_replaces_in_place_and_creates_a_block() { + let ps = unhex(PS_WITH_XMP); + let edited = put_layer_xmp(Some(&ps), "").unwrap(); + assert_eq!(layer_xmp(&edited).as_deref(), Some("")); + // `layerTime` is kept, still first. + let items = parse_shmd(&edited).unwrap(); + let d = cust_descriptor(&items[0]).unwrap().descriptor; + assert!(d.items[0].0.is("layerTime") && d.items[1].0.is(LAYER_XMP) && d.items.len() == 2); + + let fresh = put_layer_xmp(None, PS_PACKET).unwrap(); + assert_eq!(layer_xmp(&fresh).as_deref(), Some(PS_PACKET)); + assert_eq!(take_layer_xmp(&fresh), Some((PS_PACKET.to_string(), None))); + // Other items (here a layer comp state) stay as they were. + let comps = write_shmd(&[MetadataItem::new(*b"cmls", vec![1, 2])]); + let both = put_layer_xmp(Some(&comps), PS_PACKET).unwrap(); + assert_eq!(parse_shmd(&both).unwrap()[0], parse_shmd(&comps).unwrap()[0]); + assert_eq!(take_layer_xmp(&both).unwrap().1.unwrap(), comps); + } + + #[test] + fn put_refuses_an_unreadable_block() { + assert!(put_layer_xmp(Some(&[0, 0, 0, 9]), PS_PACKET).is_err()); + let bad_cust = write_shmd(&[MetadataItem::new(CUST, vec![0, 0, 0, 16, 1])]); + assert!(put_layer_xmp(Some(&bad_cust), PS_PACKET).is_err()); + assert_eq!(layer_xmp(&bad_cust), None); + assert!(take_layer_xmp(&bad_cust).is_none()); + } + #[test] fn roundtrip_exact() { let items = vec![MetadataItem::new(*b"cmls", vec![1, 2, 3]), MetadataItem { copy: true, ..MetadataItem::new(*b"cust", vec![9; 4]) }]; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0a80894db1..e41c6e580a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -21,7 +21,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Format | Photoshop | PhotoCraft read | PhotoCraft write | Fidelity and tests | |---|---|---|---|---| -| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (41 mapped plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) | +| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (41 mapped plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending, each layer's XMP packet (`layer.xmpMetadata`). Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) | | PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 | | Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) | | TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) |