From 4165c57f92b90cb5308d812620d54078ee2c9452 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 11 Oct 2026 16:13:40 +0200 Subject: [PATCH 001/113] xtask: check that every panel button routes through a command id (#3495) `cargo xtask panel-commands` scans crates/ui-egui/src (test code skipped) for click handlers -- the block of an `if` whose condition calls .clicked()/.changed()/.dragged() and friends, a local bound from one, or a widget fn taking a Ui and returning bool -- that change the document or session directly: active_mut(), Arc::make_mut on a doc, session.undo/redo/select_layer/add_document/close(), or an assignment to a session field. Lexical, std-only scanner; reports file:line and function. Existing violations sit in a commented allowlist (file + function + reason); stale entries are errors so the list only shrinks. Two today: panels.rs color_picker and color_field assign the foreground/background colour instead of dispatching tools.setColors. Runs from `cargo xtask ci` and as a CI step. Documented in docs/development.md and the AGENTS.md checklist; AUTO-219-8 is partial. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 6 + AGENTS.md | 1 + docs/development.md | 14 + docs/scorecard.md | 4 +- scorecard/automation.toml | 4 +- xtask/src/main.rs | 7 +- xtask/src/panel_commands.rs | 678 ++++++++++++++++++++++++++++++++++++ 7 files changed, 709 insertions(+), 5 deletions(-) create mode 100644 xtask/src/panel_commands.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3116e3e941..3dca7be0d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,6 +147,12 @@ jobs: - name: Dependency layering run: cargo xtask layers + # AGENTS.md rule 1: shell click handlers dispatch command ids (allowlist in + # xtask/src/panel_commands.rs). Static source scan, so one OS is enough. + - name: Panel buttons route through command ids + if: runner.os == 'Linux' + run: cargo xtask panel-commands + # docs/scorecard.md must match its sources (checklists, budgets, baseline, corpus floors, # prefs audit). Static: it reads committed files only, no benchmarks run here. - name: Scorecard up to date diff --git a/AGENTS.md b/AGENTS.md index e44dbe32a8..6942745852 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,6 +94,7 @@ When parity rises, raise `FLOOR` in `crates/ui-egui/src/parity.rs` (never lower cargo test -p cargo clippy -p --all-targets -- -D warnings cargo xtask layers +cargo xtask panel-commands # if you touched ui-egui: click handlers dispatch command ids (rule 1) cargo xtask wasm # if you touched L0–L6 cargo xtask parity # if you added commands; commit the regenerated docs/parity-checklist.md cargo test -p photocraft-engine --test panic_hunt -- --ignored # if you added/changed commands: no panic on adversarial input (Rule 9) diff --git a/docs/development.md b/docs/development.md index 7d9dac3c7a..38418749dd 100644 --- a/docs/development.md +++ b/docs/development.md @@ -262,6 +262,20 @@ derived from UI `tl!` literals, the menu catalog and UI command table, and menu the engine source. Catalog rows are validated for malformed and duplicate keys; unused legacy translations do not affect the denominator. Unregistered locale TSV files are ignored. +## Panel command routing + +Every panel button must dispatch an engine command by id (AGENTS.md rule 1), so the UI, CLI, +control channel and MCP stay equivalent. `cargo xtask panel-commands` (also a step of +`cargo xtask ci` and of CI) scans `crates/ui-egui/src` outside test code for click handlers: the +block of an `if` whose condition calls `.clicked()`, `.changed()`, `.dragged()` and friends, or a +widget function that takes a `Ui` and returns `bool`. Inside one it fails, with file:line, on a +direct document or session change: `active_mut()`, `Arc::make_mut` on a doc, +`session.undo/redo/select_layer/add_document/close(…)` or an assignment to a session field +(`app.session.tools.foreground = …`). Dispatch the command instead (`app.run`, `menus::invoke`). +The scanner is lexical and does not follow calls into helpers. Existing violations are listed in +`ALLOWLIST` in `xtask/src/panel_commands.rs` by file and function, each with its reason; an entry +that matches nothing any more is an error, so the list only shrinks. + ## Testing strategy - **Unit and property tests** in every crate. proptest is used for tile COW, regions and codecs. diff --git a/docs/scorecard.md b/docs/scorecard.md index 3357d5465e..f189fd9cc6 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 25 | 16 | 2 | | | [Workspace and UI](#workspace-and-ui) | 9 | 8 | 6 | settings that do nothing: 33 of 154 (target 0) | | [Type](#type) | 1 | 4 | 4 | | -| [Automation](#automation) | 3 | 2 | 6 | 630 of 630 menu items live (100.0%) | +| [Automation](#automation) | 3 | 3 | 5 | 630 of 630 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 29 | 2 | 1 | | @@ -234,7 +234,7 @@ Menu wiring (`docs/parity-checklist.md`): 630 of 630 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs color_picker, color_field assign the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/agent_tasks.rs runs 10 workflows over MCP | diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 002adc76db..872e7fce31 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -63,9 +63,9 @@ note = "No ONNX runtime dependency" [[item]] id = "AUTO-219-8" target = "xtask check that every panel button routes through a command id" -status = "missing" +status = "partial" issue = 219 -note = "No such xtask check" +note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs color_picker, color_field assign the foreground/background colour instead of tools.setColors)" [[item]] id = "AUTO-219-9" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6c0f016464..17252d6b29 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -8,6 +8,7 @@ mod corpus_pins; mod i18n_coverage; mod ico; mod layers; +mod panel_commands; mod perf; mod pinned; mod scorecard; @@ -23,8 +24,10 @@ usage: cargo xtask commands: layers enforce the crate dependency layering (plan/architecture.md §3) + panel-commands fail on a shell click handler that changes the document or session directly instead of + dispatching a command id (allowlist: xtask/src/panel_commands.rs) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates - ci fmt --check, clippy -D warnings, test, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, layers, panel-commands, wasm (stops at first failure) corpus [--all | --pngsuite | --psd | --psd-tools | --pixls | --photoshop] [--local] [--update-manifest] show where test corpora live and their pins (xtask/src/corpus_pins.rs), or fetch them into corpus/ (pinned commits, sha256-verified; --all = every corpus but pixls, @@ -53,6 +56,7 @@ fn main() -> ExitCode { let rest: Vec<&str> = args.iter().skip(1).map(String::as_str).collect(); let result = match args.first().map(String::as_str) { Some("layers") => cmd_layers(), + Some("panel-commands") => panel_commands::run(&root()), Some("wasm") => cmd_wasm(), Some("ci") => cmd_ci(), Some("corpus") => corpus::cmd(&rest), @@ -214,6 +218,7 @@ fn cmd_ci() -> Result<(), String> { }), ), ("layers", Box::new(cmd_layers)), + ("panel-commands", Box::new(|| panel_commands::run(&root()))), ("wasm", Box::new(cmd_wasm)), ]; let mut done = Vec::new(); diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs new file mode 100644 index 0000000000..e986512fc8 --- /dev/null +++ b/xtask/src/panel_commands.rs @@ -0,0 +1,678 @@ +//! `cargo xtask panel-commands`: every panel button routes through a command id (AGENTS.md rule 1). +//! +//! The UI, CLI, control channel and MCP stay equivalent only while panels dispatch engine commands +//! by id (`app.run`, `menus::invoke`, `session.execute`, the shell's `UI_COMMANDS`). This check +//! scans the egui shell's source for click handlers that change the document or its history +//! directly instead. +//! +//! It is a lexical scanner, not a type checker (std only, no `syn`): +//! +//! * a **click handler** is the block of an `if` whose condition calls `.clicked()` (or +//! `double_clicked`, `secondary_clicked`, `triple_clicked`, `middle_clicked`, `changed`, +//! `dragged`, `drag_stopped`), reads a local bound by `let x = … .clicked() …;` in the same file, +//! or calls a widget function (one that takes a `Ui` and returns `bool`, like `color_readout`); +//! * inside it, a **direct mutation** is `active_mut()` (the mutable document state), +//! `Arc::make_mut` on a `doc`, `session.undo/redo/select_layer/add_document/close(…)`, or an +//! assignment to a session field (`app.session.tools.foreground = …`); +//! * test code is skipped: `*_tests.rs`, `tests.rs`, files under `tests/` and `#[cfg(test)]` items. +//! +//! Out of scope: preferences (`edit_prefs`), shell view state (`app.ui`, the `UI_COMMANDS`) and +//! switching the active document. Calls into helper functions are not followed, so a handler that calls a helper which mutates the +//! document passes; the check catches the inline pattern, which is how such shortcuts start. +//! +//! Existing violations are listed in [`ALLOWLIST`] by file and enclosing function, each with the +//! reason it is still there. An entry that no longer matches anything is an error, so the list only +//! shrinks: fix the handler (dispatch a command id), then delete its entry. + +use std::path::{Path, PathBuf}; + +/// The shell source the check scans, relative to the workspace root. +pub const SCAN_ROOT: &str = "crates/ui-egui/src"; + +/// A known violation that is tolerated until its handler routes through a command. +#[derive(Debug, Clone, Copy)] +pub struct Allowed { + /// Path relative to the workspace root, with `/` separators. + pub file: &'static str, + /// Enclosing function of the click handler (`` outside any function). + pub func: &'static str, + /// Why it still mutates directly (and what the fix is). + pub reason: &'static str, +} + +/// Existing click handlers that change the document directly. Shrink only: each entry is a +/// follow-up (route it through an engine command), never a place to park new code. +pub const ALLOWLIST: &[Allowed] = &[ + // Window › Color: the HSB sliders and the hex/RGB readout set the foreground colour by + // assignment, so the change never reaches the journal, action recording or the control + // channel's event log. Fix: dispatch `tools.setColors` (it already exists). + Allowed { + file: "crates/ui-egui/src/panels.rs", + func: "color_picker", + reason: "Color panel sliders and readout assign session.tools.foreground; dispatch tools.setColors", + }, + // The Color panel's colour field and hue strip (and their readout) assign the foreground or + // background colour on every drag frame. Fix: dispatch `tools.setColors`. + Allowed { + file: "crates/ui-egui/src/panels.rs", + func: "color_field", + reason: "Color panel field, hue strip and readout assign session.tools.foreground/background; dispatch tools.setColors", + }, +]; + +/// A click handler that changes the document or its history without a command id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Violation { + pub file: String, + pub line: usize, + pub func: String, + pub what: String, +} + +const TRIGGERS: &[&str] = &["clicked", "double_clicked", "secondary_clicked", "triple_clicked", "middle_clicked", "changed", "dragged", "drag_stopped"]; + +/// Session methods that change documents or history behind the command registry's back. +const SESSION_MUTATORS: &[&str] = &["undo", "redo", "select_layer", "add_document", "close"]; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Kind { + Ident(String), + Punct(char), + /// Literals and lifetimes: never part of a pattern. + Other, +} + +#[derive(Debug, Clone)] +struct Token { + kind: Kind, + line: usize, +} + +impl Token { + fn is_ident(&self, s: &str) -> bool { + matches!(&self.kind, Kind::Ident(i) if i == s) + } + fn is_punct(&self, c: char) -> bool { + self.kind == Kind::Punct(c) + } + fn ident(&self) -> Option<&str> { + match &self.kind { + Kind::Ident(i) => Some(i), + _ => None, + } + } +} + +/// Split Rust source into identifiers and punctuation, dropping comments and literals. +fn lex(src: &str) -> Vec { + let c: Vec = src.chars().collect(); + let at = |i: usize| c.get(i).copied().unwrap_or('\0'); + let mut out = Vec::new(); + let mut line = 1; + let mut i = 0; + while i < c.len() { + let ch = at(i); + if ch == '\n' { + line += 1; + i += 1; + } else if ch.is_whitespace() { + i += 1; + } else if ch == '/' && at(i + 1) == '/' { + while i < c.len() && at(i) != '\n' { + i += 1; + } + } else if ch == '/' && at(i + 1) == '*' { + let mut depth = 0usize; + while i < c.len() { + if at(i) == '/' && at(i + 1) == '*' { + depth += 1; + i += 2; + } else if at(i) == '*' && at(i + 1) == '/' { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + break; + } + } else { + if at(i) == '\n' { + line += 1; + } + i += 1; + } + } + } else if let Some(hashes) = raw_string_start(&c, i) { + // r"…", r#"…"#, br#"…"#: skip to the quote followed by the same number of hashes. + let start_line = line; + i += hashes.prefix; + while i < c.len() { + if at(i) == '"' && (1..=hashes.count).all(|k| at(i + k) == '#') { + i += 1 + hashes.count; + break; + } + if at(i) == '\n' { + line += 1; + } + i += 1; + } + out.push(Token { kind: Kind::Other, line: start_line }); + } else if ch == '"' || (ch == 'b' && at(i + 1) == '"') || (ch == 'c' && at(i + 1) == '"') { + let start_line = line; + i += if ch == '"' { 1 } else { 2 }; + while i < c.len() { + match at(i) { + '\\' => i += 2, + '"' => { + i += 1; + break; + } + '\n' => { + line += 1; + i += 1; + } + _ => i += 1, + } + } + out.push(Token { kind: Kind::Other, line: start_line }); + } else if ch == '\'' || (ch == 'b' && at(i + 1) == '\'') { + // Char literal ('a', '\n', b'x') or lifetime/label ('a, 'static). + let q = if ch == 'b' { i + 1 } else { i }; + if at(q + 1) == '\\' { + i = q + 2; + while i < c.len() && at(i) != '\'' && at(i) != '\n' { + i += 1; + } + i += 1; + } else if at(q + 2) == '\'' { + i = q + 3; + } else { + i = q + 1; + while i < c.len() && (at(i).is_alphanumeric() || at(i) == '_') { + i += 1; + } + } + out.push(Token { kind: Kind::Other, line }); + } else if ch.is_alphabetic() || ch == '_' { + let s = i; + while i < c.len() && (at(i).is_alphanumeric() || at(i) == '_') { + i += 1; + } + out.push(Token { kind: Kind::Ident(c.get(s..i).unwrap_or_default().iter().collect()), line }); + } else if ch.is_ascii_digit() { + while i < c.len() && (at(i).is_alphanumeric() || at(i) == '_' || (at(i) == '.' && at(i + 1).is_ascii_digit())) { + i += 1; + } + out.push(Token { kind: Kind::Other, line }); + } else { + out.push(Token { kind: Kind::Punct(ch), line }); + i += 1; + } + } + out +} + +struct RawStart { + /// Characters before the body (`r#"` is 3). + prefix: usize, + count: usize, +} + +fn raw_string_start(c: &[char], i: usize) -> Option { + let at = |k: usize| c.get(k).copied().unwrap_or('\0'); + // Not the tail of an identifier such as `for` or `bar`. + if i > 0 && (at(i - 1).is_alphanumeric() || at(i - 1) == '_') { + return None; + } + let mut j = i; + if at(j) == 'b' || at(j) == 'c' { + j += 1; + } + if at(j) != 'r' { + return None; + } + j += 1; + let mut count = 0; + while at(j) == '#' { + count += 1; + j += 1; + } + (at(j) == '"').then_some(RawStart { prefix: j + 1 - i, count }) +} + +/// Index of the bracket closing the one at `open` (`{`, `(` or `[`), or the last token. +fn matching(toks: &[Token], open: usize) -> usize { + let mut depth = 0usize; + for (k, t) in toks.iter().enumerate().skip(open) { + match t.kind { + Kind::Punct('{' | '(' | '[') => depth += 1, + Kind::Punct('}' | ')' | ']') => { + depth = depth.saturating_sub(1); + if depth == 0 { + return k; + } + } + _ => {} + } + } + toks.len().saturating_sub(1) +} + +/// First `{` (or `;`) after `from` outside parentheses and brackets. +fn next_block_or_semi(toks: &[Token], from: usize) -> Option { + let mut depth = 0usize; + for (k, t) in toks.iter().enumerate().skip(from) { + match t.kind { + Kind::Punct('(' | '[') => depth += 1, + Kind::Punct(')' | ']') => depth = depth.saturating_sub(1), + Kind::Punct('{' | ';') if depth == 0 => return Some(k), + _ => {} + } + } + None +} + +/// Drop every item under `#[cfg(test)]` (or a `cfg(all(test, …))`), keeping `cfg(not(test))`. +fn strip_cfg_test(toks: Vec) -> Vec { + let mut out = Vec::with_capacity(toks.len()); + let mut i = 0; + while i < toks.len() { + if is_test_attr(&toks, i) { + // Skip this attribute, any further attributes, then the item itself. + let mut k = i; + while toks.get(k).is_some_and(|t| t.is_punct('#')) && toks.get(k + 1).is_some_and(|t| t.is_punct('[')) { + k = matching(&toks, k + 1) + 1; + } + i = match next_block_or_semi(&toks, k) { + Some(e) if toks.get(e).is_some_and(|t| t.is_punct('{')) => matching(&toks, e) + 1, + Some(e) => e + 1, + None => toks.len(), + }; + continue; + } + if let Some(t) = toks.get(i) { + out.push(t.clone()); + } + i += 1; + } + out +} + +fn is_test_attr(toks: &[Token], i: usize) -> bool { + let (Some(hash), Some(open), Some(cfg)) = (toks.get(i), toks.get(i + 1), toks.get(i + 2)) else { return false }; + if !hash.is_punct('#') || !open.is_punct('[') || !cfg.is_ident("cfg") { + return false; + } + let close = matching(toks, i + 1); + let inner = toks.get(i + 3..close).unwrap_or_default(); + inner.iter().any(|t| t.is_ident("test")) && !inner.iter().any(|t| t.is_ident("not")) +} + +/// `(body open, body close, name)` of every function with a body. +fn functions(toks: &[Token]) -> Vec<(usize, usize, String)> { + let mut out = Vec::new(); + for (i, t) in toks.iter().enumerate() { + if !t.is_ident("fn") { + continue; + } + let Some(name) = toks.get(i + 1).and_then(Token::ident) else { continue }; + if let Some(open) = next_block_or_semi(toks, i + 2).filter(|&o| toks.get(o).is_some_and(|t| t.is_punct('{'))) { + out.push((open, matching(toks, open), name.to_string())); + } + } + out +} + +/// Does `toks` call `.trigger(` for one of the click triggers? +fn calls_trigger(toks: &[Token]) -> bool { + toks.windows(3).any(|w| { + w.first().is_some_and(|t| t.is_punct('.')) + && w.get(1).and_then(Token::ident).is_some_and(|n| TRIGGERS.contains(&n)) + && w.get(2).is_some_and(|t| t.is_punct('(')) + }) +} + +/// Locals bound by `let name = … .clicked() …;`. +fn click_locals(toks: &[Token]) -> Vec { + let mut out = Vec::new(); + for (i, t) in toks.iter().enumerate() { + if !t.is_ident("let") { + continue; + } + let mut n = i + 1; + if toks.get(n).is_some_and(|t| t.is_ident("mut")) { + n += 1; + } + let (Some(name), Some(eq)) = (toks.get(n).and_then(Token::ident), toks.get(n + 1)) else { continue }; + if !eq.is_punct('=') { + continue; + } + let Some(end) = next_block_or_semi(toks, n + 2) else { continue }; + // A `{` before the `;` (a block or closure value) is out of scope for this heuristic. + if toks.get(end).is_some_and(|t| t.is_punct(';')) && calls_trigger(toks.get(n + 2..end).unwrap_or_default()) { + out.push(name.to_string()); + } + } + out +} + +/// Direct document/history mutations in `toks`: `(token index, description)`. +fn mutations(toks: &[Token]) -> Vec<(usize, String)> { + let mut out = Vec::new(); + for (i, t) in toks.iter().enumerate() { + let next = |k: usize| toks.get(i + k); + let Some(name) = t.ident() else { continue }; + let call = next(1).is_some_and(|t| t.is_punct('(')); + if name == "active_mut" && call && i > 0 && toks.get(i - 1).is_some_and(|p| p.is_punct('.')) { + out.push((i, "`active_mut()` changes the document directly".to_string())); + } else if name == "make_mut" && call { + let close = matching(toks, i + 1); + let args = toks.get(i + 2..close).unwrap_or_default(); + if args.iter().any(|a| a.ident().is_some_and(|n| n == "doc" || n.ends_with("_doc") || n == "document")) { + out.push((i, "`Arc::make_mut` on a document changes it directly".to_string())); + } + } else if name == "session" + && next(1).is_some_and(|t| t.is_punct('.')) + && let Some(m) = next(2).and_then(Token::ident).filter(|m| SESSION_MUTATORS.contains(m)) + && next(3).is_some_and(|t| t.is_punct('(')) + { + out.push((i, format!("`session.{m}()` bypasses the command registry"))); + } else if name == "session" + && let Some(field) = assigned_field(toks, i) + { + out.push((i, format!("`session.{field} = …` changes session state directly"))); + } + } + out +} + +/// `a.b` when `toks[i]` (`session`) starts `session.a.b = …` or a compound assignment (`+=`, …). +fn assigned_field(toks: &[Token], i: usize) -> Option { + let mut path = Vec::new(); + let mut k = i + 1; + while toks.get(k).is_some_and(|t| t.is_punct('.')) { + path.push(toks.get(k + 1)?.ident()?.to_string()); + k += 2; + } + let first = toks.get(k)?; + let second = toks.get(k + 1); + let plain = first.is_punct('=') && !second.is_some_and(|t| t.is_punct('=') || t.is_punct('>')); + let compound = matches!(first.kind, Kind::Punct('+' | '-' | '*' | '/' | '|' | '&' | '^')) && second.is_some_and(|t| t.is_punct('=')); + (!path.is_empty() && (plain || compound)).then(|| path.join(".")) +} + +/// Names of functions that draw a widget and report an edit: they take a `Ui` and return `bool` +/// (`fn color_readout(ui: &mut Ui, …) -> bool`). `if widget(…) { … }` is a click handler too. +pub fn widget_fns(src: &str) -> Vec { + let toks = strip_cfg_test(lex(src)); + let mut out = Vec::new(); + for (i, t) in toks.iter().enumerate() { + if !t.is_ident("fn") { + continue; + } + let Some(name) = toks.get(i + 1).and_then(Token::ident) else { continue }; + let Some(open) = toks.iter().enumerate().skip(i + 2).find(|(_, t)| t.is_punct('(')).map(|(k, _)| k) else { continue }; + let close = matching(&toks, open); + let takes_ui = toks.get(open..close).unwrap_or_default().iter().any(|t| t.is_ident("Ui")); + let returns_bool = toks.get(close + 1).is_some_and(|t| t.is_punct('-')) + && toks.get(close + 2).is_some_and(|t| t.is_punct('>')) + && toks.get(close + 3).is_some_and(|t| t.is_ident("bool")); + if takes_ui && returns_bool && !out.iter().any(|n| n == name) { + out.push(name.to_string()); + } + } + out +} + +/// Every click handler in `src` that changes the document directly. `file` labels the results. +/// `widgets` lists the widget functions of the whole tree (see [`widget_fns`]). +pub fn scan(file: &str, src: &str, widgets: &[String]) -> Vec { + let toks = strip_cfg_test(lex(src)); + let fns = functions(&toks); + let locals = click_locals(&toks); + let mut out: Vec = Vec::new(); + for (i, t) in toks.iter().enumerate() { + if !t.is_ident("if") { + continue; + } + let Some(open) = next_block_or_semi(&toks, i + 1) else { continue }; + if !toks.get(open).is_some_and(|t| t.is_punct('{')) { + continue; + } + let cond = toks.get(i + 1..open).unwrap_or_default(); + let is_click = calls_trigger(cond) + || cond.iter().any(|c| c.ident().is_some_and(|n| locals.iter().any(|l| l == n))) + || cond + .windows(2) + .any(|w| w.first().and_then(Token::ident).is_some_and(|n| widgets.iter().any(|f| f == n)) && w.get(1).is_some_and(|t| t.is_punct('('))); + if !is_click { + continue; + } + let close = matching(&toks, open); + let body = toks.get(open..=close).unwrap_or_default(); + for (k, what) in mutations(body) { + let at = open + k; + let line = toks.get(at).map_or(0, |t| t.line); + let func = fns.iter().filter(|(o, c, _)| *o < at && at < *c).min_by_key(|(o, c, _)| c - o).map_or("", |f| f.2.as_str()); + let v = Violation { file: file.to_string(), line, func: func.to_string(), what }; + if !out.contains(&v) { + out.push(v); + } + } + } + out.sort_by_key(|v| v.line); + out +} + +/// Is `path` (relative, `/`-separated) test code? +fn is_test_file(path: &str) -> bool { + path.ends_with("_tests.rs") || path.ends_with("/tests.rs") || path == "tests.rs" || path.contains("/tests/") || path.starts_with("tests/") +} + +/// Violations not covered by `allow`, and allowlist entries that match nothing (stale). +pub fn check<'a>(violations: &[Violation], allow: &'a [Allowed]) -> (Vec, Vec<&'a Allowed>) { + let covered = |v: &Violation, a: &Allowed| v.file == a.file && v.func == a.func; + let new = violations.iter().filter(|v| !allow.iter().any(|a| covered(v, a))).cloned().collect(); + let stale = allow.iter().filter(|a| !violations.iter().any(|v| covered(v, a))).collect(); + (new, stale) +} + +fn rust_files(dir: &Path, out: &mut Vec) -> Result<(), String> { + let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for e in entries { + let p = e.map_err(|e| format!("{}: {e}", dir.display()))?.path(); + if p.is_dir() { + rust_files(&p, out)?; + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } + Ok(()) +} + +/// Scan the shell source under `root` (the workspace root). +pub fn scan_tree(root: &Path) -> Result, String> { + let base = root.join(SCAN_ROOT); + let mut files = Vec::new(); + rust_files(&base, &mut files)?; + files.sort(); + let mut sources = Vec::new(); + for f in files { + let rel = f.strip_prefix(&base).map_err(|e| e.to_string())?.to_string_lossy().replace('\\', "/"); + if is_test_file(&rel) { + continue; + } + let src = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?; + sources.push((format!("{SCAN_ROOT}/{rel}"), src)); + } + let mut widgets = Vec::new(); + for (_, src) in &sources { + for name in widget_fns(src) { + if !widgets.contains(&name) { + widgets.push(name); + } + } + } + Ok(sources.iter().flat_map(|(file, src)| scan(file, src, &widgets)).collect()) +} + +pub fn run(root: &Path) -> Result<(), String> { + let violations = scan_tree(root)?; + let (new, stale) = check(&violations, ALLOWLIST); + println!("Panel command routing (AGENTS.md rule 1): click handlers in {SCAN_ROOT} must dispatch a command id\n"); + println!("{} direct mutation(s) in click handlers, {} allowlisted function(s)", violations.len(), ALLOWLIST.len()); + for v in &new { + println!(" {}:{}: in `{}`: {}; dispatch an engine command by id instead", v.file, v.line, v.func, v.what); + } + for a in ALLOWLIST.iter().filter(|a| !stale.iter().any(|s| s.file == a.file && s.func == a.func)) { + println!(" allowlisted {} `{}`: {}", a.file, a.func, a.reason); + } + for a in &stale { + println!(" stale allowlist entry {} `{}`: no direct mutation left there; delete it from xtask/src/panel_commands.rs", a.file, a.func); + } + if new.is_empty() && stale.is_empty() { + println!("OK: every other click handler routes through a command id."); + Ok(()) + } else { + Err(format!("{} unrouted click handler(s), {} stale allowlist entr(y/ies)", new.len(), stale.len())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(src: &str) -> Vec<(usize, String)> { + scan("f.rs", src, &[]).into_iter().map(|v| (v.line, v.func)).collect() + } + + #[test] + fn routed_button_passes() { + let src = r#" +fn panel(app: &mut App, ui: &mut Ui) { + if ui.button("Flatten").clicked() { + let _ = app.run("layer.flatten", json!({})); + } + if ui.button("Undo").clicked() { + menus::invoke(app, ctx, "edit.undo", Value::Null); + } +} +"#; + assert!(scan("f.rs", src, &[]).is_empty()); + } + + #[test] + fn direct_mutation_fails_with_file_line_and_function() { + let src = r#" +fn panel(app: &mut App, ui: &mut Ui) { + if ui.button("Hide").clicked() { + if let Some(st) = app.session.active_mut() { + st.active_layer = None; + } + } +} +"#; + let v = scan("crates/ui-egui/src/x.rs", src, &[]); + assert_eq!(v.len(), 1); + assert_eq!((v[0].file.as_str(), v[0].line, v[0].func.as_str()), ("crates/ui-egui/src/x.rs", 4, "panel")); + assert!(v[0].what.contains("active_mut")); + } + + #[test] + fn every_mutation_kind_and_trigger_is_caught() { + let src = r#" +fn a(app: &mut App, ui: &mut Ui) { + if ui.button("x").secondary_clicked() { app.session.undo(); } + if resp.double_clicked() && ok { Arc::make_mut(&mut st.doc).layers.clear(); } + let pressed = ui.button("y").clicked(); + if pressed { app.session.close(0); } + if slider.changed() { app.session.select_layer(id); } +} +"#; + assert_eq!(lines(src), vec![(3, "a".into()), (4, "a".into()), (6, "a".into()), (7, "a".into())]); + } + + #[test] + fn mutation_outside_click_handlers_test_code_comments_and_strings_pass() { + let src = r##" +fn sync(app: &mut App) { + if let Some(st) = app.session.active_mut() { st.dirty = true; } +} +fn panel(app: &mut App, ui: &mut Ui) { + if ui.button("x").clicked() { + // app.session.active_mut() + let s = "app.session.undo()"; + let r = r#"session.close(0)"#; + let c = '{'; + let _ = app.run("edit.undo", Value::Null); + } + if ui.button("y").clicked() { theme(Arc::make_mut(&mut fonts)); } +} +#[cfg(test)] +mod tests { + fn t(app: &mut App, ui: &mut Ui) { + if ui.button("x").clicked() { app.session.undo(); } + } +} +"##; + assert!(scan("f.rs", src, &[]).is_empty(), "{:?}", scan("f.rs", src, &[])); + } + + #[test] + fn widget_functions_and_session_assignments_count() { + let widgets = widget_fns("fn color_readout(ui: &mut egui::Ui, c: &mut [f32; 4]) -> bool { false }\nfn label(ui: &mut Ui) {}"); + assert_eq!(widgets, vec!["color_readout".to_string()]); + let src = r#" +fn field(app: &mut App, ui: &mut Ui) { + if color_readout(ui, &mut c) { app.session.tools.foreground = c; } + if r.dragged() { app.session.tools.brush.size += 1.0; } + if r.clicked() { let same = app.session.tools.foreground == c; app.ui.show = true; } + if r.clicked() { let _ = app.run("tools.setColors", json!({"foreground": "red"})); } +} +"#; + let v = scan("f.rs", src, &widgets); + assert_eq!(v.iter().map(|v| v.line).collect::>(), vec![3, 4]); + assert!(v[0].what.contains("session.tools.foreground"), "{}", v[0].what); + assert!(v[1].what.contains("session.tools.brush.size"), "{}", v[1].what); + } + + #[test] + fn cfg_not_test_is_scanned_and_lifetimes_do_not_confuse_the_lexer() { + let src = r#" +#[cfg(not(test))] +fn panel<'a>(app: &'a mut App, ui: &mut Ui) { + if ui.button("x").clicked() { app.session.redo(); } +} +"#; + assert_eq!(lines(src), vec![(4, "panel".into())]); + } + + #[test] + fn allowlisted_passes_and_stale_entry_is_reported() { + let v = vec![Violation { file: "a.rs".into(), line: 3, func: "panel".into(), what: "x".into() }]; + let allow = [Allowed { file: "a.rs", func: "panel", reason: "known" }, Allowed { file: "a.rs", func: "gone", reason: "fixed already" }]; + let (new, stale) = check(&v, &allow); + assert!(new.is_empty()); + assert_eq!(stale.len(), 1); + assert_eq!(stale[0].func, "gone"); + let (new, stale) = check(&v, &[]); + assert_eq!(new, v); + assert!(stale.is_empty()); + } + + #[test] + fn test_files_are_recognised() { + assert!(is_test_file("panels_tests.rs")); + assert!(is_test_file("file_dialog/tests.rs")); + assert!(is_test_file("discard_ui/tests/tiff_tests.rs")); + assert!(!is_test_file("panels.rs")); + assert!(!is_test_file("tests_ui.rs")); + } + + #[test] + fn the_allowlist_has_reasons_and_no_duplicates() { + for (i, a) in ALLOWLIST.iter().enumerate() { + assert!(!a.reason.trim().is_empty(), "{} `{}` needs a reason", a.file, a.func); + assert!(a.file.starts_with(SCAN_ROOT), "{} is outside {SCAN_ROOT}", a.file); + assert!(!ALLOWLIST.iter().skip(i + 1).any(|b| b.file == a.file && b.func == a.func), "duplicate {} `{}`", a.file, a.func); + } + } +} From d71e6dab0f5b0f28da0fb4cddd7295f022f62f56 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 01:42:55 +0200 Subject: [PATCH 002/113] Regenerate docs/scorecard.md after merging main Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index d2ee641b1e..350733493b 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 28 | 14 | 1 | | | [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 26 of 156 (target 0) | | [Type](#type) | 4 | 2 | 3 | | -| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | +| [Automation](#automation) | 5 | 3 | 3 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 29 | 2 | 1 | | @@ -234,7 +234,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs color_picker, color_field assign the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/agent_tasks.rs runs 10 workflows over MCP | From 6ceb0dbae22e81efec2856a75fa663e2f501738c Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 14:06:39 +0200 Subject: [PATCH 003/113] panel-commands: follow main's move of the HSB sliders into hsb_sliders Main split the Color panel's HSB sliders out of color_picker (#4399), so the allowlist entry moves with them; regenerate docs/scorecard.md after the merge. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- scorecard/automation.toml | 2 +- xtask/src/panel_commands.rs | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 1ad3f3aa3d..5008607ec1 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 28 | 14 | 1 | | | [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) | | [Type](#type) | 4 | 3 | 2 | | -| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | +| [Automation](#automation) | 5 | 3 | 3 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 29 | 2 | 1 | | @@ -234,7 +234,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs hsb_sliders, color_field assign the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/agent_tasks.rs runs 10 workflows over MCP | diff --git a/scorecard/automation.toml b/scorecard/automation.toml index e0f977d210..32d1d5fcf2 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -65,7 +65,7 @@ id = "AUTO-219-8" target = "xtask check that every panel button routes through a command id" status = "partial" issue = 219 -note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs color_picker, color_field assign the foreground/background colour instead of tools.setColors)" +note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs hsb_sliders, color_field assign the foreground/background colour instead of tools.setColors)" [[item]] id = "AUTO-219-9" diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index e986512fc8..ec76ff9f86 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -43,13 +43,13 @@ pub struct Allowed { /// Existing click handlers that change the document directly. Shrink only: each entry is a /// follow-up (route it through an engine command), never a place to park new code. pub const ALLOWLIST: &[Allowed] = &[ - // Window › Color: the HSB sliders and the hex/RGB readout set the foreground colour by - // assignment, so the change never reaches the journal, action recording or the control - // channel's event log. Fix: dispatch `tools.setColors` (it already exists). + // Window › Color: the HSB sliders set the foreground colour by assignment, so the change + // never reaches the journal, action recording or the control channel's event log. + // Fix: dispatch `tools.setColors` (it already exists). Allowed { file: "crates/ui-egui/src/panels.rs", - func: "color_picker", - reason: "Color panel sliders and readout assign session.tools.foreground; dispatch tools.setColors", + func: "hsb_sliders", + reason: "Color panel HSB sliders assign session.tools.foreground; dispatch tools.setColors", }, // The Color panel's colour field and hue strip (and their readout) assign the foreground or // background colour on every drag frame. Fix: dispatch `tools.setColors`. From fe083602a4fcff30159257c89af699f561bbaef3 Mon Sep 17 00:00:00 2001 From: augrclk <217665348+augrclk@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:29:15 +0300 Subject: [PATCH 004/113] Brush Settings: place Both Axes on the Scatter header Share the header layout between Scattering and Dual Brush, retaining label scrubbing, percentage limits, fractional values and tools.setBrush routing. Cover layout in all themes and guard disabled input and independent brush blocks. Addresses only the Both Axes placement subsection of #3825. Co-authored-by: GPT-6 --- crates/ui-egui/src/brush_panel_tests.rs | 63 ++++++++++++ crates/ui-egui/src/brush_sections.rs | 126 +++++++++++++++++++++++- crates/ui-egui/src/widgets.rs | 3 +- docs/brush-parity.md | 4 +- docs/gaps.md | 7 +- 5 files changed, 196 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rs index 750a9d5506..94cc3e4f4b 100644 --- a/crates/ui-egui/src/brush_panel_tests.rs +++ b/crates/ui-egui/src/brush_panel_tests.rs @@ -547,6 +547,69 @@ fn harness(tab: usize, section: usize) -> Harness<'static, PhotocraftApp> { h } +#[test] +fn scatter_header_edits_route_to_the_correct_brush_block_and_disabled_sections_ignore_input() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + + for section in [2, 4] { + let block = if section == 2 { "scattering" } else { "dualBrush" }; + let mut h = harness(0, section); + let mut initial = json!({}); + initial[block] = if section == 2 { + json!({"enabled": true, "bothAxes": false, "scatter": {"jitter": 2.137, "control": "penPressure"}, "count": 5}) + } else { + json!({"enabled": true, "bothAxes": false, "scatter": 2.137, "count": 7}) + }; + h.state_mut().run("tools.setBrush", json!({"brush": initial})).unwrap(); + h.run_steps(3); + let journal = h.state().session.journal.len(); + let before = h.state().session.tools.brush.clone(); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + let mut expected = json!({}); + expected[block] = json!({"bothAxes": true}); + assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush"); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], expected); + let mut after = before; + if section == 2 { + after.scattering.both_axes = true; + } else { + after.dual_brush.both_axes = true; + } + assert_eq!(h.state().session.tools.brush, after, "toggle changes only the matching axis flag"); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + expected[block] = if section == 2 { json!({"scatter": {"jitter": 2.15_f32}}) } else { json!({"scatter": 2.15_f32}) }; + assert_eq!(last_journal(h.state()).unwrap().1["brush"], expected); + if section == 2 { + after.scattering.scatter.jitter = 2.15; + } else { + after.dual_brush.scatter = 2.15; + } + assert_eq!(h.state().session.tools.brush, after); + assert_eq!(h.state().session.journal.len(), journal + 2); + let mut off = json!({}); + off[block] = json!({"enabled": false}); + h.state_mut().run("tools.setBrush", json!({"brush": off})).unwrap(); + h.run_steps(2); + let before = h.state().session.tools.brush.clone(); + let journal = h.state().session.journal.len(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(215.0)).unwrap(); + assert!(field.accesskit_node().is_disabled()); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.event(egui::Event::Text("999".into())); + h.key_press(egui::Key::Enter); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush, before, "the disabled header retains both values"); + assert_eq!(h.state().session.journal.len(), journal, "disabled edits add no command"); + } +} + fn toggle_value(app: &PhotocraftApp, section: usize) -> bool { let brush = serde_json::to_value(&app.session.tools.brush).unwrap(); let path = match section { diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/brush_sections.rs index ff7ca5d292..c79ec8d7ed 100644 --- a/crates/ui-egui/src/brush_sections.rs +++ b/crates/ui-egui/src/brush_sections.rs @@ -353,10 +353,29 @@ fn shape_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) { widgets::checkbox(ui, &mut sd.brush_projection, tl!("Brush Projection")).on_hover_text(tl!("Apply the pen's tilt and rotation to the tip shape")); } +/// Both scatter controls put their axis switch between the label and percentage field. +fn scatter_row(ui: &mut egui::Ui, amount: &mut f32, both_axes: &mut bool) { + let t = Tokens::get(ui.ctx()); + let mut percent = (*amount * 100.0).round(); + let mut changed = false; + ui.horizontal(|ui| { + let label = ui.label(RichText::new(tl!("Scatter")).color(t.text_dim)); + widgets::scrub_label_within(ui, &label, f32::INFINITY); + widgets::checkbox(ui, both_axes, tl!("Both Axes")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed = widgets::value_field(ui, &mut percent, 0.0..=1000.0, "%", 74.0).changed(); + }); + }); + changed |= widgets::slider(ui, &mut percent, 0.0..=1000.0, None).changed(); + if changed { + *amount = (percent.round() / 100.0).clamp(0.0, 10.0); + } + ui.add_space(4.0); +} + fn scattering(ui: &mut egui::Ui, b: &mut BrushSettings) { let sc = &mut b.scattering; - pct(ui, tl!("Scatter"), &mut sc.scatter.jitter, 10.0); - widgets::checkbox(ui, &mut sc.both_axes, tl!("Both Axes")); + scatter_row(ui, &mut sc.scatter.jitter, &mut sc.both_axes); ui.add_space(2.0); control_row(ui, "brush-scatter-ctl", &mut sc.scatter, false); ui.add_space(6.0); @@ -498,8 +517,7 @@ fn dual_brush(ui: &mut egui::Ui, b: &mut BrushSettings, presets: &[BrushPreset]) let orig = d.tip.bitmap_size().map(|(w, h)| w.max(h) as f32); size_row(ui, tl!("Size"), &mut d.size, 2500.0, orig); signed_pct(ui, tl!("Spacing"), &mut d.spacing, 0.01, 10.0); - pct(ui, tl!("Scatter"), &mut d.scatter, 10.0); - widgets::checkbox(ui, &mut d.both_axes, tl!("Both Axes")); + scatter_row(ui, &mut d.scatter, &mut d.both_axes); ui.add_space(4.0); let mut c = d.count as f32; if num(ui, tl!("Count"), &mut c, 1.0..=16.0, "") { @@ -645,6 +663,106 @@ mod tests { h } + fn check_scatter_header(section: usize) { + for kind in theme::ThemeKind::ALL { + for both_axes in [false, true] { + let mut b = BrushSettings::default(); + b.scattering.scatter.jitter = 2.137; + b.scattering.both_axes = both_axes; + b.dual_brush.scatter = 2.137; + b.dual_brush.both_axes = both_axes; + let mut h = section_harness(section, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let label = h.get_by_label("Scatter").rect(); + let axes = h.get_by_label("Both Axes").rect(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap().rect(); + assert!((label.center().y - axes.center().y).abs() < 2.0, "{kind:?}, section {section}: axes belongs on the Scatter header"); + assert!((axes.center().y - field.center().y).abs() < 2.0, "{kind:?}, section {section}: axes and percentage share a row"); + assert!(label.right() < axes.left() && axes.right() < field.left(), "{kind:?}, section {section}: label, checkbox, percentage order"); + assert_eq!(h.state(), &b, "rendering retains fractional scatter and other settings"); + } + } + } + + #[test] + fn scatter_header_scattering_places_axes_between_label_and_percentage_in_all_themes() { + check_scatter_header(2); + } + + #[test] + fn scatter_header_dual_brush_places_axes_between_label_and_percentage_in_all_themes() { + check_scatter_header(4); + } + + #[test] + fn scatter_header_preserves_values_percentage_limits_and_label_scrubbing() { + for section in [2, 4] { + let mut b = BrushSettings::default(); + b.scattering.scatter.jitter = 2.137; + b.scattering.scatter.control = Control::PenPressure; + b.scattering.count = 5; + b.dual_brush.scatter = 2.137; + b.dual_brush.count = 7; + let mut h = section_harness(section, b.clone()); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + if section == 2 { + b.scattering.both_axes = true; + } else { + b.dual_brush.both_axes = true; + } + assert_eq!(h.state(), &b, "a toggle does not round scatter or change unrelated fields"); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + if section == 2 { + b.scattering.scatter.jitter = 2.15; + } else { + b.dual_brush.scatter = 2.15; + } + assert_eq!(h.state(), &b, "percentage edits preserve the other brush block"); + let label = h.get_by_label("Scatter").rect().center(); + drag(&mut h, label, label + vec2(18.0, 0.0)); + let amount = if section == 2 { h.state().scattering.scatter.jitter } else { h.state().dual_brush.scatter }; + assert!(amount > 2.15, "the label still scrubs the percentage across the checkbox"); + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + assert_eq!(h.state(), &b, "scrubbing changes only the scatter amount"); + let field = + h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(f64::from((amount * 100.0).round()))).unwrap(); + let from = pos2(field.rect().left() - 100.0, field.rect().bottom() + 9.0); + let to = pos2(field.rect().right() - 25.0, from.y); + drag(&mut h, from, to); + let amount = if section == 2 { h.state().scattering.scatter.jitter } else { h.state().dual_brush.scatter }; + assert!(amount > 5.0, "the existing amount track remains editable"); + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + assert_eq!(h.state(), &b); + for (amount, value, key) in [(0.0, 0.0, egui::Key::ArrowDown), (10.0, 1000.0, egui::Key::ArrowUp)] { + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + *h.state_mut() = b.clone(); + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); + field.click(); + h.key_press(key); + h.run_steps(2); + assert_eq!(h.state(), &b, "the percentage stays within 0..1000"); + } + } + } + /// #3825: jitter is an amount, not a hue selector; it uses the themed amount track. #[test] fn hue_jitter_paints_an_amount_track_in_every_theme() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9e56022cef..9850453c77 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -400,7 +400,8 @@ pub fn scrub_label(ui: &Ui, label: &Response) -> Response { scrub_label_within(ui, label, 24.0) } -fn scrub_label_within(ui: &Ui, label: &Response, max_gap: f32) -> Response { +// Shared headers may put a control between the label and its field. +pub(crate) fn scrub_label_within(ui: &Ui, label: &Response, max_gap: f32) -> Response { // Drag only, not focusable: Tab goes to the value field, not to its label as well. let resp = label.interact(Sense::DRAG); // Whether a field took this label's drags last frame: only then is it scrubby. diff --git a/docs/brush-parity.md b/docs/brush-parity.md index 7a5e499820..ed11de5bf0 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Both Axes on Scatter headers; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -21,6 +21,7 @@ tablets against Photoshop side by side. | Brush Tip Shape: size, angle, roundness, hardness, spacing, flip X/Y | done | `brush.rs` | | Shape Dynamics (size/angle/roundness jitter, pen pressure/tilt/rotation/wheel controls, minimums, flip jitter, brush projection) | done | #174 | | Scattering (both axes, count, count jitter) | done | | +| Scattering and Dual Brush place Both Axes between the Scatter label and percentage | done | #3825 (Both Axes header placement only); all-theme UI regressions cover both axis values, fractional-value retention, percentage limits, label scrubbing, amount-track edits and existing command routing. | | Texture (pattern, scale, brightness, contrast, mode, depth, each tip) | done | | | Dual Brush | done | | | Color Dynamics (FG/BG, hue/sat/brightness jitter, purity, per tip) | done | | @@ -121,3 +122,4 @@ tablets against Photoshop side by side. | 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction | | 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. | +| 2026-10-13 | minor | Scattering and Dual Brush place Both Axes on the shared Scatter header (#3825, partial), preserving label scrubbing and values. No brush-feel estimate changed. | diff --git a/docs/gaps.md b/docs/gaps.md index 25a286aab8..da01374bc6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: Both Axes on Scatter headers, #3825 partial; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -156,6 +156,10 @@ what an agent can't finish alone. - **Estimate:** 250–400 h (many overlap with other gaps; count each fix once). ### G4. Brush feel +- **Progress (2026-10-13, #3825 partial):** Scattering and Dual Brush place Both Axes + between the Scatter label and percentage field. The existing amount track, label + scrubbing, percentage limits and disabled-section value retention are preserved. + The assessment's remaining layout and control gaps stay open. - **Progress (2026-10-13, #3825 partial):** Hue Jitter shows a standard themed percentage-amount track rather than a hue spectrum. Other Brush Settings layout and brush-behaviour gaps remain open. @@ -264,6 +268,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| | 2026-10-13 | minor | G4: Hue Jitter amount-track appearance (#3825, partial); no readiness percentage or estimate changed | +| 2026-10-13 | minor | G4: Scattering and Dual Brush Both Axes header placement (#3825, partial); label scrubbing and value retention preserved; no readiness percentage or estimate changed | | 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed | | 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done | | 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) | From 01e4ef5ef59fae458735baa717b234d196dd4cd6 Mon Sep 17 00:00:00 2001 From: augrclk <217665348+augrclk@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:12:44 +0300 Subject: [PATCH 005/113] test(autosave): wait for the retried snapshot metadata Recovery discovery can list a committed bundle before its sidecar is published. Wait for the expected revision rather than treating a fallback entry as write completion. Keep all failure, retry, revision and pixel assertions. Co-authored-by: GPT-6 --- apps/photocraft/src/services.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index d4a3869f31..b7a5a4cb85 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -932,7 +932,9 @@ mod tests { while std::time::Instant::now() < deadline { prefs_ui::tick(&mut app, &ctx); recovered = list_recovery(&recovery); - if !recovered.is_empty() { + // A committed bundle is recoverable before its sidecar is published. Wait for + // the sidecar's revision, not the early fallback entry (revision 0). + if recovered.len() == 1 && recovered[0].info.revision == revision { break; } std::thread::sleep(std::time::Duration::from_millis(10)); From 2813f5e348a02e0fc9e054a33b105bf71fb4f5b9 Mon Sep 17 00:00:00 2001 From: augrclk <217665348+augrclk@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:20:54 +0300 Subject: [PATCH 006/113] test(autosave): align retry coverage with upstream Upstream 7250e6e2 independently fixed the same manifest/sidecar race. Adopt its canonical test, including the nonzero revision guard, to clear the conflict while preserving the Brush Settings changes. Co-authored-by: GPT-6 --- apps/photocraft/src/services.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index b7a5a4cb85..e6c882d198 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -907,6 +907,7 @@ mod tests { let mut app = launch(&recovery); new_doc(&mut app, "#ff0000"); let revision = app.session.active().unwrap().revision; + assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0"); autosave(&mut app, &ctx); let mut failed = false; @@ -927,14 +928,16 @@ mod tests { std::fs::remove_file(&recovery).unwrap(); std::fs::create_dir(&recovery).unwrap(); autosave(&mut app, &ctx); + // The worker commits the bundle's manifest before it publishes the sidecar, and + // `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so + // the first non-empty listing can come from the middle of the write. Wait for the write + // to finish: the entry then carries the sidecar's revision. let mut recovered = Vec::new(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); while std::time::Instant::now() < deadline { prefs_ui::tick(&mut app, &ctx); recovered = list_recovery(&recovery); - // A committed bundle is recoverable before its sidecar is published. Wait for - // the sidecar's revision, not the early fallback entry (revision 0). - if recovered.len() == 1 && recovered[0].info.revision == revision { + if recovered.iter().any(|e| e.info.revision == revision) { break; } std::thread::sleep(std::time::Duration::from_millis(10)); From b45be327b66dd4f31c82d65ffa52e9c90f806966 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 11:37:15 +0200 Subject: [PATCH 007/113] Address CodeRabbit review: count line continuations in string literals A backslash before a newline inside a string skipped the newline without counting it, so every later violation reported a line one too low. Co-Authored-By: Claude Opus 5.5 --- xtask/src/panel_commands.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index ec76ff9f86..82da2154f4 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -160,7 +160,13 @@ fn lex(src: &str) -> Vec { i += if ch == '"' { 1 } else { 2 }; while i < c.len() { match at(i) { - '\\' => i += 2, + '\\' => { + // A line continuation (`\` before a newline) still ends a source line. + if at(i + 1) == '\n' { + line += 1; + } + i += 2; + } '"' => { i += 1; break; @@ -576,6 +582,25 @@ fn panel(app: &mut App, ui: &mut Ui) { assert!(v[0].what.contains("active_mut")); } + #[test] + fn line_continuations_in_strings_keep_line_numbers() { + let src = " +fn panel(app: &mut App, ui: &mut Ui) { + ui.label(\"first \\ + second \\ + third\"); + if ui.button(\"Hide\").clicked() { + if let Some(st) = app.session.active_mut() { + st.active_layer = None; + } + } +} +"; + let v = scan("f.rs", src, &[]); + assert_eq!(v.len(), 1); + assert_eq!(v[0].line, 7); + } + #[test] fn every_mutation_kind_and_trigger_is_caught() { let src = r#" From 9b213580353b7a8adeb9b28a0ccf0246b3abc3e4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 12:43:58 +0200 Subject: [PATCH 008/113] Address CodeRabbit review: document the panel scan's blind spots Co-Authored-By: Claude Opus 5.5 --- docs/development.md | 7 ++++++- xtask/src/panel_commands.rs | 22 ++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/docs/development.md b/docs/development.md index d4e42d83ed..6167239639 100644 --- a/docs/development.md +++ b/docs/development.md @@ -307,7 +307,12 @@ widget function that takes a `Ui` and returns `bool`. Inside one it fails, with direct document or session change: `active_mut()`, `Arc::make_mut` on a doc, `session.undo/redo/select_layer/add_document/close(…)` or an assignment to a session field (`app.session.tools.foreground = …`). Dispatch the command instead (`app.run`, `menus::invoke`). -The scanner is lexical and does not follow calls into helpers. Existing violations are listed in +A passing scan is not complete coverage. The scanner is lexical: it does not follow calls into +helpers, and it only recognises an `if` block (a `match` arm guard with a block counts) or a +`let` local holding a response, so a `match` on a response without such a guard, a response kept +in a struct field and tested later, or a closure callback is not checked. Preferences +(`edit_prefs`), shell view state (`app.ui`, the `UI_COMMANDS`) and switching the active document +are out of scope. Existing violations are listed in `ALLOWLIST` in `xtask/src/panel_commands.rs` by file and function, each with its reason; an entry that matches nothing any more is an error, so the list only shrinks. diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index 82da2154f4..76d28a83e5 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -17,8 +17,11 @@ //! * test code is skipped: `*_tests.rs`, `tests.rs`, files under `tests/` and `#[cfg(test)]` items. //! //! Out of scope: preferences (`edit_prefs`), shell view state (`app.ui`, the `UI_COMMANDS`) and -//! switching the active document. Calls into helper functions are not followed, so a handler that calls a helper which mutates the -//! document passes; the check catches the inline pattern, which is how such shortcuts start. +//! switching the active document. Calls into helper functions are not followed, so a handler +//! that calls a helper which mutates the document passes; the check catches the inline pattern, +//! which is how such shortcuts start. Only `if` blocks (also a `match` arm guard with a block) +//! and `let` locals count as handlers: a `match` on a response without one, a response kept in a +//! struct field and tested later, or a closure callback is not scanned. //! //! Existing violations are listed in [`ALLOWLIST`] by file and enclosing function, each with the //! reason it is still there. An entry that no longer matches anything is an error, so the list only @@ -601,6 +604,21 @@ fn panel(app: &mut App, ui: &mut Ui) { assert_eq!(v[0].line, 7); } + #[test] + fn a_match_arm_guard_with_a_block_is_a_click_handler() { + let src = " +fn panel(app: &mut App, ui: &mut Ui) { + match ui.button(\"Hide\") { + r if r.clicked() => { + app.session.active_mut(); + } + _ => {} + } +} +"; + assert_eq!(lines(src), [(5, "panel".to_string())]); + } + #[test] fn every_mutation_kind_and_trigger_is_caught() { let src = r#" From beb50a43d371c2f7dbe813797b3a45abb70fcdbe Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 23 Oct 2026 00:06:24 +0200 Subject: [PATCH 009/113] Allowlist main's Color panel RGB sliders in panel-commands; regenerate scorecard Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- xtask/src/panel_commands.rs | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 6e84b9847e..5895456bcd 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 36 | 8 | 0 | | | [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 21 of 176 (target 0) | | [Type](#type) | 5 | 4 | 0 | | -| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | +| [Automation](#automation) | 5 | 3 | 3 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 4 | 2 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -239,7 +239,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial, Include All Subfolders (includeSubfolders: depth/loop/file-count bounded, results keep their subfolder; Batch and Image Processor dialogs, #3753); no open-documents source, cancel or error-log file | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs hsb_sliders, color_field assign the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index 76d28a83e5..06777140af 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -54,6 +54,13 @@ pub const ALLOWLIST: &[Allowed] = &[ func: "hsb_sliders", reason: "Color panel HSB sliders assign session.tools.foreground; dispatch tools.setColors", }, + // The Color panel's RGB sliders assign the foreground or background colour the same way. + // Fix: dispatch `tools.setColors`. + Allowed { + file: "crates/ui-egui/src/panels.rs", + func: "rgb_sliders", + reason: "Color panel RGB sliders assign session.tools.foreground/background; dispatch tools.setColors", + }, // The Color panel's colour field and hue strip (and their readout) assign the foreground or // background colour on every drag frame. Fix: dispatch `tools.setColors`. Allowed { From f26bd3e2570d31c3fed00b10cd99068e64dfe644 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 24 Oct 2026 02:57:09 +0200 Subject: [PATCH 010/113] xtask: drop the panel-commands allowlist entries main fixed Main's Color panel rework removed hsb_sliders and rgb_sliders, so their allowlist entries were stale (the check fails on stale entries). One allowlisted function is left; the scorecard note and docs/scorecard.md follow. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/scorecard.md | 4 ++-- scorecard/automation.toml | 2 +- xtask/src/panel_commands.rs | 20 +++----------------- 3 files changed, 6 insertions(+), 20 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 09f8c61ab9..862720c536 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 36 | 8 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 20 of 177 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | +| [Automation](#automation) | 5 | 3 | 3 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -244,7 +244,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial, Include All Subfolders (includeSubfolders: depth/loop/file-count bounded, results keep their subfolder; Batch and Image Processor dialogs, #3753); no open-documents source, cancel or error-log file | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 60ba6f8729..573d1e7ec2 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -65,7 +65,7 @@ id = "AUTO-219-8" target = "xtask check that every panel button routes through a command id" status = "partial" issue = 219 -note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 2 allowlisted functions left (panels.rs hsb_sliders, color_field assign the foreground/background colour instead of tools.setColors)" +note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels.rs color_field assigns the foreground/background colour instead of tools.setColors)" [[item]] id = "AUTO-219-9" diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index 06777140af..5fd82abeb5 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -46,23 +46,9 @@ pub struct Allowed { /// Existing click handlers that change the document directly. Shrink only: each entry is a /// follow-up (route it through an engine command), never a place to park new code. pub const ALLOWLIST: &[Allowed] = &[ - // Window › Color: the HSB sliders set the foreground colour by assignment, so the change - // never reaches the journal, action recording or the control channel's event log. - // Fix: dispatch `tools.setColors` (it already exists). - Allowed { - file: "crates/ui-egui/src/panels.rs", - func: "hsb_sliders", - reason: "Color panel HSB sliders assign session.tools.foreground; dispatch tools.setColors", - }, - // The Color panel's RGB sliders assign the foreground or background colour the same way. - // Fix: dispatch `tools.setColors`. - Allowed { - file: "crates/ui-egui/src/panels.rs", - func: "rgb_sliders", - reason: "Color panel RGB sliders assign session.tools.foreground/background; dispatch tools.setColors", - }, - // The Color panel's colour field and hue strip (and their readout) assign the foreground or - // background colour on every drag frame. Fix: dispatch `tools.setColors`. + // Window › Color: the colour field and hue strip (and their readout) assign the foreground or + // background colour on every drag frame, so the change never reaches the journal, action + // recording or the control channel's event log. Fix: dispatch `tools.setColors` (it already exists). Allowed { file: "crates/ui-egui/src/panels.rs", func: "color_field", From 239f5604a0a0c63a548444fbcef32cfc150cb73d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 01:31:26 +0200 Subject: [PATCH 011/113] Crop: Shift+H, Shift+P and Shift+I switch tools again (#9232) egui's consume_key ignores an extra Shift, so the Crop tool's plain H/P/I checks also took Shift+H/P/I before the tool-switch loop saw them. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_shield.rs | 24 ++++++++++++++++++++++-- crates/ui-egui/src/crop_size.rs | 19 +++++++++++++++++-- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/crop_shield.rs b/crates/ui-egui/src/crop_shield.rs index aef70e5afb..29588199fb 100644 --- a/crates/ui-egui/src/crop_shield.rs +++ b/crates/ui-egui/src/crop_shield.rs @@ -122,18 +122,19 @@ pub fn hides_outside(app: &PhotocraftApp) -> bool { /// H with the Crop tool showing a box and no drag in progress toggles Show Cropped Area (in /// Classic Mode, where the option is greyed out, H is taken and does nothing), and P Use Classic /// Mode. Returns true when a key was used; otherwise H stays the Hand tool key and P the Pen's. +/// ⇧H and ⇧P are always the tool keys (`consume_key` would also take them: it ignores ⇧). pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::Crop || app.ui.crop_rect.is_none() || app.crop.drag.is_some() { return false; } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::H)) { + if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::H)) { let s = &mut app.ui.tool_options.crop_shield; if !s.classic_mode { s.show_cropped_area = !s.show_cropped_area; } return true; } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::P)) { + if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::P)) { let s = &mut app.ui.tool_options.crop_shield; s.classic_mode = !s.classic_mode; // The view follows at once, about its own centre: default mode turns it with the frame, @@ -342,6 +343,25 @@ mod tests { assert!(app.ui.tool_options.crop_shield.show_cropped_area); } + /// ⇧H and ⇧P are the Hand and Pen tool keys even with a crop box: egui's `consume_key` ignores + /// an extra ⇧, so the plain-key checks must refuse it. + #[test] + fn shift_h_and_shift_p_switch_tools_instead_of_crop_options() { + for (key, tool) in [(Key::H, Tool::Hand), (Key::P, Tool::Pen)] { + let mut app = crop_app(); + assert!(app.session.prefs().tools.use_shift_key_for_tool_switch); + let before = app.ui.tool_options.crop_shield.clone(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.modifiers = Modifiers::SHIFT; + i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + }); + crate::shortcuts::handle(&mut app, &ctx); + assert_eq!(app.ui.tool, tool, "{key:?}"); + assert_eq!(app.ui.tool_options.crop_shield, before, "{key:?} leaves Show Cropped Area and Classic Mode alone"); + } + } + #[test] fn the_color_picker_sets_the_custom_colour() { let mut app = crop_app(); diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs index 71fc57f495..df1fcc19fe 100644 --- a/crates/ui-egui/src/crop_size.rs +++ b/crates/ui-egui/src/crop_size.rs @@ -260,12 +260,12 @@ pub fn chosen(app: &mut PhotocraftApp) { } /// I with the Crop tool (no text field focused, which the caller checks): Front Image. Returns -/// true when the key was used; otherwise I stays the Eyedropper tool key. +/// true when the key was used; otherwise I (and always ⇧I) stays the Eyedropper tool key. pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::Crop || app.crop.drag.is_some() || app.session.active().is_none() { return false; } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, egui::Key::I)) { + if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, egui::Key::I)) { front_image(app); crate::crop_ui::apply_ratio(app); return true; @@ -497,6 +497,21 @@ mod tests { assert!(!keys(&mut app2, &ctx)); } + /// ⇧I is the Eyedropper group's key even with the Crop tool, not Front Image. + #[test] + fn shift_i_with_the_crop_tool_switches_to_the_eyedropper() { + let mut app = app(SampleType::U8); + let ratio = app.ui.tool_options.crop_ratio.clone(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.modifiers = Modifiers::SHIFT; + i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + }); + crate::shortcuts::handle(&mut app, &ctx); + assert_eq!(app.ui.tool, Tool::Eyedropper); + assert_eq!(app.ui.tool_options.crop_ratio, ratio); + } + /// Committing a W x H x Resolution crop resamples the frame's area to exactly W x H px and sets /// the resolution, in one undo step, at 8 and 16 bits. #[test] From 5988587b22cb3695cbcc8a050e178c881ed69f17 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 01:49:50 +0200 Subject: [PATCH 012/113] Crop: check each key event's own Shift, so control-channel keys are covered (#9232) Synthetic keys from the control channel carry their modifiers on the event only; the frame's modifier state doesn't see them. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_shield.rs | 17 +++++++++++++---- crates/ui-egui/src/crop_size.rs | 7 ++++--- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/crop_shield.rs b/crates/ui-egui/src/crop_shield.rs index 29588199fb..2acdd18c63 100644 --- a/crates/ui-egui/src/crop_shield.rs +++ b/crates/ui-egui/src/crop_shield.rs @@ -122,19 +122,19 @@ pub fn hides_outside(app: &PhotocraftApp) -> bool { /// H with the Crop tool showing a box and no drag in progress toggles Show Cropped Area (in /// Classic Mode, where the option is greyed out, H is taken and does nothing), and P Use Classic /// Mode. Returns true when a key was used; otherwise H stays the Hand tool key and P the Pen's. -/// ⇧H and ⇧P are always the tool keys (`consume_key` would also take them: it ignores ⇧). +/// ⇧H and ⇧P are always the tool keys. pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::Crop || app.ui.crop_rect.is_none() || app.crop.drag.is_some() { return false; } - if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::H)) { + if ctx.input_mut(|i| consume_unshifted(i, Key::H)) { let s = &mut app.ui.tool_options.crop_shield; if !s.classic_mode { s.show_cropped_area = !s.show_cropped_area; } return true; } - if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::P)) { + if ctx.input_mut(|i| consume_unshifted(i, Key::P)) { let s = &mut app.ui.tool_options.crop_shield; s.classic_mode = !s.classic_mode; // The view follows at once, about its own centre: default mode turns it with the frame, @@ -145,6 +145,15 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { false } +/// `consume_key(Modifiers::NONE, key)` without the presses that hold ⇧: egui ignores an extra ⇧ +/// there, but ⇧+letter is the tool key. Reads each event's own modifiers, which synthetic +/// (control channel) keys carry without changing the frame's. +pub(crate) fn consume_unshifted(i: &mut egui::InputState, key: Key) -> bool { + let before = i.events.len(); + i.events.retain(|e| !matches!(e, egui::Event::Key { key: k, pressed: true, modifiers, .. } if *k == key && !modifiers.shift && modifiers.matches_logically(Modifiers::NONE))); + i.events.len() != before +} + /// The options bar's gear button and its menu. Returns true when Custom… asks for the Color /// Picker ([`pick_custom_color`], which needs the app). pub fn options_button(s: &mut CropShield, ui: &mut egui::Ui) -> bool { @@ -353,7 +362,7 @@ mod tests { let before = app.ui.tool_options.crop_shield.clone(); let ctx = egui::Context::default(); ctx.input_mut(|i| { - i.modifiers = Modifiers::SHIFT; + // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); }); crate::shortcuts::handle(&mut app, &ctx); diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs index df1fcc19fe..90662997c9 100644 --- a/crates/ui-egui/src/crop_size.rs +++ b/crates/ui-egui/src/crop_size.rs @@ -15,7 +15,7 @@ //! with the Crop tool, [`keys`]) fills them with the active document's size in px and its //! resolution; Clear empties them; ⇄ and X swap W and H. -use egui::{Modifiers, Stroke, StrokeKind, vec2}; +use egui::{Stroke, StrokeKind, vec2}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -265,7 +265,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.tool != Tool::Crop || app.crop.drag.is_some() || app.session.active().is_none() { return false; } - if ctx.input_mut(|i| !i.modifiers.shift && i.consume_key(Modifiers::NONE, egui::Key::I)) { + if ctx.input_mut(|i| crate::crop_shield::consume_unshifted(i, egui::Key::I)) { front_image(app); crate::crop_ui::apply_ratio(app); return true; @@ -322,6 +322,7 @@ pub fn fields(o: &mut ToolOptions, ui: &mut egui::Ui) { #[cfg(test)] mod tests { use super::*; + use egui::Modifiers; use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; #[test] @@ -504,7 +505,7 @@ mod tests { let ratio = app.ui.tool_options.crop_ratio.clone(); let ctx = egui::Context::default(); ctx.input_mut(|i| { - i.modifiers = Modifiers::SHIFT; + // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); }); crate::shortcuts::handle(&mut app, &ctx); From 79f9ff4cdea688eb5b39696c2a5db5cb4e4f1a1d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:28:49 +0200 Subject: [PATCH 013/113] Scale Effects and Image Size scale Bevel & Emboss Texture's scale (#9254) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scale_effects scaled Pattern Overlay's and a pattern Stroke's scale but left Bevel & Emboss › Texture at its old size, so a texture aligned with the overlay drifted after Scale Effects, Image Size or Crop W x H. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/layer_menu_cmds/tests.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/layer_menu_cmds/tests.rs index b0cceb72a8..4a388c29e1 100644 --- a/crates/engine/src/layer_menu_cmds/tests.rs +++ b/crates/engine/src/layer_menu_cmds/tests.rs @@ -140,6 +140,26 @@ fn global_light_blending_options_scale_effects() { } } +#[test] +fn scale_effects_scales_the_bevel_texture_with_the_pattern_overlay() { + let mut s = session(8, "rgb"); + paint(&mut s, disc); + s.execute("layer.layerStyle.patternOverlay", json!({"scale": 100})).unwrap(); + s.execute("layer.layerStyle.bevelEmboss", json!({"texture": "Bubbles", "textureScale": 100})).unwrap(); + s.execute("layer.layerStyle.scaleEffects", json!({"scale": 50})).unwrap(); + let fx = &active(&s).effects.items; + let overlay = fx.iter().find_map(|e| match e { + Effect::PatternOverlay { scale, .. } => Some(*scale), + _ => None, + }); + let texture = fx.iter().find_map(|e| match e { + Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale), + _ => None, + }); + // Both patterns tile at half size, so a texture aligned with the overlay stays aligned. + assert_eq!((overlay, texture), (Some(0.5), Some(0.5))); +} + #[test] fn global_light_rejects_numbers_beyond_f32() { let mut s = session(8, "rgb"); From 42ec692355a1b842c94dfd9c3104c7250d00d3db Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:34:00 +0200 Subject: [PATCH 014/113] Scale Effects and Image Size scale Bevel & Emboss Texture's scale (#9254) Multiply BevelTexture::scale by the effects factor in scale_effects, as Pattern Overlay's and a pattern Stroke's scale already are. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..32eadaed41 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -150,6 +150,9 @@ pub fn scale_effects(fx: &mut Effects, k: f32) { Effect::BevelEmboss(b) => { b.size *= k; b.soften *= k; + if let Some(t) = &mut b.texture { + t.scale *= k; + } } Effect::PatternOverlay { scale, .. } => *scale *= k, Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {} From 46ac4fc8f3af8579ee7dbfe6d323bacbcbbfd650 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 02:28:59 +0100 Subject: [PATCH 015/113] Crop: refuse an invalid explicit rectangle instead of cropping to the selection (#9279) image.crop built an explicit rectangle only when x, y, width and height were all integers with width and height above 0; anything else fell back to the selection's bounds, so width 0, a negative or string size, or only some of the four keys cropped to the selection and reported success. A rectangle that is passed (any of the four keys non-null) but incomplete or empty is now a bad-params error and the document is unchanged; {} still crops to the selection. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_cmds.rs | 53 ++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 6353f1f2cc..24f39f2184 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -567,6 +567,7 @@ fn crop(s: &mut Session, p: &Value) -> Result { }; // Values beyond i32 would wrap through the narrowing casts into a rectangle unrelated to // the numbers passed; reject them (see `commands::int_i32`). + let given = ["x", "y", "width", "height"].into_iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())); let explicit = match ( crate::commands::int_i32("image.crop", p, "x")?, crate::commands::int_i32("image.crop", p, "y")?, @@ -587,6 +588,14 @@ fn crop(s: &mut Session, p: &Value) -> Result { }; Some(Rect::new(x, y, end(x, w, "x", "width")?, end(y, h, "y", "height")?)) } + // A rectangle that is passed but incomplete or empty is refused: falling back to the + // selection would crop somewhere the caller didn't ask for (#9279). + _ if given => { + return Err(bad( + "image.crop", + "`x`, `y`, `width` and `height` go together: pass all four as numbers of pixels, with `width` and `height` rounding to at least 1", + )); + } _ => None, }; let target = crop_target(p)?; @@ -975,7 +984,7 @@ pub fn specs() -> Vec { "image.crop", "Crop", ["Image"], - r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; contentAware: the Crop tool's Fill › Content-Aware Fill, the area a rotated or extending crop uncovers filled from its surroundings on the Background, else the active pixel layer)"##, + r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (x/y/width/height, all four or none: without them the selection's bounds are cropped to; targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; contentAware: the Crop tool's Fill › Content-Aware Fill, the area a rotated or extending crop uncovers filled from its surroundings on the Background, else the active pixel layer)"##, has_doc, crop ), @@ -1423,6 +1432,48 @@ mod tests { assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]); } + /// A rectangle that is passed but invalid is refused, not replaced by the selection (#9279). + #[test] + fn crop_refuses_a_bad_explicit_rect_instead_of_cropping_to_the_selection() { + let bad = [ + json!({"x": 10, "y": 10, "width": 0, "height": 50}), + json!({"x": 10, "y": 10, "width": 20, "height": 0}), + json!({"x": 10, "y": 10, "width": -50, "height": 50}), + json!({"x": 10, "y": 10, "width": "100", "height": 50}), + json!({"x": 10, "y": 10, "width": true, "height": 50}), + json!({"width": 20, "height": 10}), + json!({"x": 1, "y": 1}), + json!({"x": 1, "y": null, "width": 20, "height": 10}), + json!({"height": 10}), + ]; + for p in bad { + for selection in [true, false] { + let mut s = session(); + if selection { + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + } + let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len()); + let err = s.execute("image.crop", p.clone()).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{p} (selection: {selection}): {err:?}"); + assert_eq!(doc(&s).size, size, "{p} (selection: {selection})"); + assert_eq!(doc(&s).selection.is_some(), selection, "{p}: the selection stays"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{p} (selection: {selection})"); + } + } + // No rectangle at all (or every side null) still crops to the selection. + for p in [json!({}), json!({"x": null, "y": null, "width": null, "height": null})] { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + s.execute("image.crop", p.clone()).unwrap(); + assert_eq!(doc(&s).size, Size::new(20, 10), "{p}"); + } + // Whole-number floats, as the Crop tool sends them, are a valid rectangle. + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + s.execute("image.crop", json!({"x": 1.0, "y": 1.0, "width": 30.0, "height": 15.0})).unwrap(); + assert_eq!(doc(&s).size, Size::new(30, 15)); + } + #[test] fn crop_extension_fills_the_background_with_the_background_colour() { let mut shrink = Session::new(); From a9b878834d171b571d0d171cd111f1df0b6e2f49 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:50:32 +0100 Subject: [PATCH 016/113] Photo Filter opens at its last settings (#9879) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Image › Adjustments › Photo Filter… now opens at the filter, colour, density and Preserve Luminosity of its last OK, as Photoshop's does, without holding ⌥. The other adjustment dialogs keep opening at their neutral settings (⌥ still reopens them at the last ones, #8900). `adjust_dialog::open` picks the last settings for the kinds listed in `REMEMBERS_LAST`; the old neutral behaviour is `open_neutral`, which the smart filter editor now uses so a smart filter's dialog always shows that filter's own settings. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog.rs | 15 ++++++-- .../src/dialogs/adjust_dialog/tests.rs | 36 +++++++++++++++++++ crates/ui-egui/src/panels/smart_ui.rs | 3 +- docs/ui-parity.md | 4 ++- 4 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index e1d61ab659..1ac70db208 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -261,8 +261,19 @@ pub fn reset(app: &PhotocraftApp, ctx: &egui::Context, fields: &mut Map Option { + if command.strip_prefix(PREFIX).is_some_and(|kind| REMEMBERS_LAST.contains(&kind)) { open_last(app, command) } else { open_neutral(app, command) } +} + +/// Opens the dialog for `command` with the kind's neutral settings. +pub fn open_neutral(app: &mut PhotocraftApp, command: &str) -> Option { let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?; let spec = photocraft_engine::commands::find(command)?; let mode = curve_mode(app, kind); @@ -283,7 +294,7 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { /// adjustment's shortcut, ⌥⌘L / ⌥⌘M, #8900), or at the neutral ones when there are none or they /// don't fit the current colour mode. pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option { - let id = open(app, command)?; + let id = open_neutral(app, command)?; let kind = command.strip_prefix(PREFIX).unwrap_or_default(); let mode = curve_mode(app, kind); let Some(last) = app.session.prefs().dialogs.get(command).cloned() else { return Some(id) }; diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index d3bcf2b688..e2ba88ca61 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -849,3 +849,39 @@ fn curves_on_a_targeted_filter_mask_is_a_gray_plane() { assert!(h.ch[0][0] > 0 && h.ch[0][255] > 0, "black and white levels"); assert_eq!(curve_mode(&app, "curves"), photocraft_doc::ColorMode::Grayscale); } + +/// #9879: Photo Filter opens at the filter and density last confirmed in it, without ⌥; Levels +/// still opens at its neutral settings, and a smart filter's dialog never takes the last ones. +#[test] +fn photo_filter_opens_at_its_last_settings() { + let mut app = app_with_image(); + let cmd = "image.adjustments.photoFilter"; + let first = open_neutral(&mut app, cmd).unwrap(); + let neutral = crate::filter_dialog::params_of(&app.ui.dialog_mut(first).unwrap().fields.clone()); + app.ui.dialogs.clear(); + let id = open(&mut app, cmd).unwrap(); + let sample = photocraft_engine::adjust_params::to_params( + &photocraft_engine::adjust_params::from_params("photoFilter", &sample_params("photoFilter"), None, photocraft_doc::ColorMode::Rgb).unwrap(), + ); + assert_ne!(sample, neutral, "the sample differs from the neutral settings"); + if let Value::Object(p) = sample.clone() { + app.ui.dialog_mut(id).unwrap().fields.extend(p); + } + crate::dialogs::confirm(&mut app, id).unwrap(); + + let again = open(&mut app, cmd).unwrap(); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()), sample, "reopened at the last settings"); + app.ui.dialogs.clear(); + let smart = open_neutral(&mut app, cmd).unwrap(); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(smart).unwrap().fields.clone()), neutral, "open_neutral ignores them"); + app.ui.dialogs.clear(); + + let levels = "image.adjustments.levels"; + let id = open(&mut app, levels).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("inBlack".into(), json!(30)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let again = open(&mut app, levels).unwrap(); + let defaults = + photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for("levels", photocraft_doc::ColorMode::Rgb).unwrap()); + assert_eq!(app.ui.dialog_mut(again).unwrap().fields["inBlack"], defaults["inBlack"], "Levels opens neutral without ⌥"); +} diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index 8e531b47b6..c1b592be49 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -483,7 +483,8 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: return; } }; - let Some(id) = crate::adjust_dialog::open(app, &f.command).or_else(|| { + // A smart filter's dialog shows the filter's own settings, never the last-used ones. + let Some(id) = crate::adjust_dialog::open_neutral(app, &f.command).or_else(|| { let id = crate::filter_dialog::has_dialog(&f.command).then(|| crate::filter_dialog::open(app, &f.command)).flatten()?; // The filter dialog opens on the user's last-used values; a recorded filter that lacks a // key must show (and save) the schema default instead. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4490d693c2..660ad19448 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (Image › Adjustments › Photo Filter… opens at the filter and density of its last OK, #9879; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; 12 of 181 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -208,6 +208,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Tool keys: ← / → turn the brush tip (1°, ⇧ 15°), ⇧-click with Type starts new text over old, Space+F / ⇧Space+F cycle the pasteboard colour | done (2026-10-11) | | | Type formatting keys while editing text | done: ⇧⌘K, U, B, I and / toggle All Caps, Underline, Faux Bold, Faux Italic, Strikethrough (off when every selected character has it, else on); ⌥↑/↓ leading ∓2 pt, ⇧⌥↑/↓ baseline shift ±2 pt (10 with ⌘); ⌥←/→ tracking ±20 over a selection (100 with ⌘; a collapsed caret still kerns); ⌥⇧⌘H toggles Hyphenate for the touched paragraphs. One `type.setStyle` step per press (new `leadingBy`/`baselineShiftBy`/`trackingBy`; auto leading starts from its laid-out value); the global ⇧⌘K/U/B/I never fire while typing. Differs: a collapsed caret in non-empty text changes nothing, since the model can't hold a pending style for the next characters typed (empty text takes it as its typing style) (`type_tool.rs`, `input_tests.rs` `type_tool_format_keys_*`) | | | ⌥ + an adjustment's shortcut opens it at its last settings (⌥⌘L Levels, ⌥⌘M Curves, and so ⌥⌘U, ⌥⌘B) | done (#8900): the settings of the last OK, kept in the preferences; Cancel and smart filter edits keep nothing; a key assigned to another command stays that command's. ⌥ while choosing the item from Image › Adjustments does the same | `shortcut_dispatch/tests.rs` `alt_adjustment_shortcut_reopens_the_last_confirmed_settings`, `alt_choosing_an_adjustment_from_the_menu_reopens_the_last_settings` | +| Photo Filter remembers its last settings: Image › Adjustments › Photo Filter… opens at the filter, colour, density and Preserve Luminosity of its last OK | done (#9879): the other adjustments still open at their neutral settings and take the last ones with ⌥; a smart filter's dialog shows that filter's own settings | `adjust_dialog/tests.rs` `photo_filter_opens_at_its_last_settings` | | Guides: click selects, Delete deletes, right-click menu, ⌥-click turns a guide, double-click opens Guides, Grid & Slices | done (2026-10-12) | a guide let go over either ruler is removed, not only off the canvas (#6286) | | Blend mode keys: ⇧⌥ + letter picks a mode (N Normal, I Dissolve, R Clear, P Pass Through, K M B A darken, G S D W lighten, O F H V J Z L contrast, E X difference, U T C Y component), ⇧+ / ⇧− step through them | done (2026-10-14): Brush, Pencil and Gradient take them as their own mode (Clear on Brush, Pencil and Paint Bucket only), any non-painting tool sets every selected layer in one undo step (Pass Through on groups only; the Background is skipped); the typed letter wins, the physical key is the fallback for ⌥ characters on a Mac. ⇧⌥ letters no longer switch tools. While a Free Transform box is open they, and the number keys, still reach the tool (or the layers) without closing it; Puppet Warp and Perspective Warp keep them to themselves. Clone Stamp, Pattern Stamp, History Brush, Healing (its own short list) and Paint Bucket (with Clear) take them as their own mode; tools without a blend mode (the Erasers, Mixer Brush) set the layers. Differs: Behind (⇧⌥Q) is not implemented; Spot Healing, Color Replacement, Blur, Sharpen and Smudge ignore the keys until their options bar has a Mode, and Dodge, Burn and Sponge ignore them until their Range and mode keys (⇧⌥S/M/H, ⇧⌥D/S) exist | `blend_keys.rs` | @@ -252,6 +253,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-28 | minor | Image › Adjustments › Photo Filter… opens at the filter and density of its last OK, without ⌥, as in Photoshop (#9879); no percentage changed | | 2026-10-27 | minor | Every preference takes effect: 12 of 181 do nothing, the scorecard's count with integration batch 9 (#9775) on main; new layers go above a group whose lock would refuse them (#4329) | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | From 744651bb4dd5bd4dce1a8662a2a1ca2cf7f06d21 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:08:52 +0100 Subject: [PATCH 017/113] Photo Filter: reopen with the choice its colour implies; complete recorded settings Review follow-ups for #9879: - Photo Filter's Filter / Color choice lives in the editor memory, so an opening that switched it and was cancelled left the next opening on Filter with a custom colour (the colour button disabled). Each opening now forgets it once, and the editor derives it from the colour again. - A smart filter's recorded adjustment settings are completed through the engine's parser before they fill the dialog, so a recorded Photo Filter that names only its `filter` shows and saves that preset's colour instead of the dialog's neutral one. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog.rs | 17 +++++++++ .../src/dialogs/adjust_dialog/tests.rs | 35 +++++++++++++++++++ crates/ui-egui/src/dialogs/adjust_editors.rs | 7 ++++ .../src/dialogs/adjust_editors/basic.rs | 6 +++- crates/ui-egui/src/panels/smart_ui.rs | 5 ++- 5 files changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index 1ac70db208..a1199ccea2 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -17,6 +17,8 @@ use crate::tone::{self, HistSource}; const PREFIX: &str = "image.adjustments."; const CURVE_PICKER: &str = "__curvePicker"; const CURVE_PICKER_BASE: &str = "__curvePickerBase"; +/// Set once a Photo Filter dialog has drawn: its editor memory was refreshed for this opening. +const PHOTO_FILTER_FRESH: &str = "__photoFilterFresh"; fn picker(value: Option<&Value>) -> Option { use photocraft_engine::adjust_params::CurvesEyedropper; @@ -306,6 +308,15 @@ pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option { Some(id) } +/// `params` of the adjustment `command` with every key filled in as the engine reads them: a +/// recorded Photo Filter that names only its `filter` gets that preset's `color`, not the dialog's +/// neutral one. `None` for other commands and for params the engine rejects. +pub(crate) fn complete_params(app: &PhotocraftApp, command: &str, params: &Value) -> Option { + let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?; + let adjustment = photocraft_engine::adjust_params::from_params(kind, params, None, curve_mode(app, kind)).ok()?; + Some(photocraft_engine::adjust_params::to_params(&adjustment)) +} + /// Remember an adjustment dialog's settings after a successful OK, for [`open_last`]. Editing a /// smart filter's settings is not a use of the dialog's own (as `filter_dialog::remember`). pub(crate) fn remember(app: &mut PhotocraftApp, fields: &Map) { @@ -340,6 +351,12 @@ fn curve_mode(app: &PhotocraftApp, kind: &str) -> photocraft_doc::ColorMode { pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map) { let kind = fields.get("__adjust").and_then(Value::as_str).unwrap_or_default().to_string(); let mode = curve_mode(app, &kind); + // Each opening starts from the settings it opened at: Photo Filter's Filter / Color choice + // follows its colour, whatever a cancelled opening left in the editor memory. + if kind == "photoFilter" && !fields.contains_key(PHOTO_FILTER_FRESH) { + adjust_editors::forget_photo_filter_mode(ui.ctx(), dialog_mem(&kind)); + fields.insert(PHOTO_FILTER_FRESH.into(), json!(false)); + } if matches!(kind.as_str(), "levels" | "curves") { picker_controls(ui, fields, mode); ui.add_space(4.0); diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index e2ba88ca61..d94f783a85 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -885,3 +885,38 @@ fn photo_filter_opens_at_its_last_settings() { photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for("levels", photocraft_doc::ColorMode::Rgb).unwrap()); assert_eq!(app.ui.dialog_mut(again).unwrap().fields["inBlack"], defaults["inBlack"], "Levels opens neutral without ⌥"); } + +/// #9879 review: a custom colour confirmed in Photo Filter reopens with Color chosen, even after an +/// opening that switched to Filter and was cancelled (the choice lives in the editor memory). +#[test] +fn photo_filter_reopens_with_the_choice_its_colour_implies() { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let cmd = "image.adjustments.photoFilter"; + let id = open(h.state_mut(), cmd).unwrap(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456")); + h.run_steps(2); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + // The next opening chooses Filter (what clicking its radio stores), then is cancelled. + let mode = dialog_mem("photoFilter").with(crate::adjust_editors::PHOTO_FILTER_MODE); + let id = open(h.state_mut(), cmd).unwrap(); + h.run_steps(2); + h.ctx.data_mut(|d| d.insert_temp(mode, false)); + h.state_mut().ui.close_dialog(id); + h.run_steps(1); + let id = open(h.state_mut(), cmd).unwrap(); + h.run_steps(2); + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["color"], json!("#123456")); + assert_eq!(h.ctx.data(|d| d.get_temp::(mode)), Some(true), "Color is chosen for the custom colour"); +} + +/// #9879 review: a recorded Photo Filter that names only its preset completes to that preset's +/// colour, so editing it as a smart filter doesn't swap in the dialog's neutral colour. +#[test] +fn recorded_photo_filter_settings_complete_to_their_preset_colour() { + let app = app_with_image(); + let done = complete_params(&app, "image.adjustments.photoFilter", &json!({"filter": "cooling80", "density": 60})).unwrap(); + assert_eq!((done["color"].as_str(), done["density"].as_f64()), (Some("#006dff"), Some(60.0))); + assert!(complete_params(&app, "filter.blur.gaussian", &json!({"radius": 2})).is_none(), "not an adjustment"); + assert!(complete_params(&app, "image.adjustments.photoFilter", &json!({"filter": "nope"})).is_none(), "rejected params"); +} diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index cdee0d6502..522ed46705 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -30,6 +30,7 @@ mod hue_saturation; mod levels; mod session; +pub(crate) use basic::PHOTO_FILTER_MODE; #[cfg(test)] pub(crate) use basic::row_value; #[cfg(test)] @@ -71,6 +72,12 @@ pub fn has_editor(kind: &str) -> bool { KINDS.contains(&kind) } +/// Forget Photo Filter's Filter / Color choice in the editor memory `mem`, so the editor derives it +/// from the colour again: a choice changed and then cancelled must not outlive the dialog (#9879). +pub(crate) fn forget_photo_filter_mode(ctx: &egui::Context, mem: egui::Id) { + ctx.data_mut(|d| d.remove::(mem.with(PHOTO_FILTER_MODE))); +} + /// Kinds that draw a histogram behind their controls. pub fn needs_histogram(kind: &str) -> bool { matches!(kind, "levels" | "curves" | "threshold") diff --git a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs index 18c740ab80..8a7ea8ce8e 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs @@ -194,12 +194,16 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed // --------------------------------------------------------------------------------------------- // Photo Filter +/// The editor memory key of Photo Filter's Filter / Color choice (unset: Color for a colour that +/// is no preset). +pub(crate) const PHOTO_FILTER_MODE: &str = "pf-mode"; + pub(super) fn photo_filter(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { let mut e = Edit::default(); let mut c = rgb_of(v, "color", [236.0 / 255.0, 138.0 / 255.0, 0.0]); let hex = adjust_params::hex(c); let preset = PHOTO_FILTERS.iter().find(|f| adjust_params::hex(f.2.map(|x| f32::from(x) / 255.0)) == hex).map(|f| f.0); - let mode_id = cx.mem.with("pf-mode"); + let mode_id = cx.mem.with(PHOTO_FILTER_MODE); let mut use_color: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(preset.is_none()); ui.horizontal(|ui| { if ui.radio(!use_color, tl!("Filter:")).clicked() { diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index c1b592be49..ff32958bb0 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -495,9 +495,12 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: }) else { return; }; + // An adjustment's recorded settings are completed first, so a key the record lacks shows (and + // saves) what the engine reads for it rather than the dialog's neutral value. + let params = crate::adjust_dialog::complete_params(app, &f.command, &f.params).unwrap_or_else(|| f.params.clone()); if let Some(d) = app.ui.dialog_mut(id) { d.fields.insert("__smartFilter".into(), target); - if let Value::Object(p) = &f.params { + if let Value::Object(p) = ¶ms { for (k, v) in p { if !k.starts_with("__") { d.fields.insert(k.clone(), v.clone()); From e74c79d015321a89f849fd91f8e85035b2ce1c96 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:28:54 +0100 Subject: [PATCH 018/113] Smart filter: complete only a Photo Filter's missing colour, keep recorded values Review follow-up for #9879: round-tripping every recorded adjustment through the engine rewrote values it should keep (a float Photo Filter colour became hex, a pencil curve's map came back smoothed while its `smooth` stayed in the stored params, so each confirmation smoothed it again). `complete_params` now adds just the colour a Photo Filter that names only its `filter` lacks, and leaves every recorded value and every other adjustment untouched. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog.rs | 16 +++++++++++----- .../ui-egui/src/dialogs/adjust_dialog/tests.rs | 16 ++++++++++++---- crates/ui-egui/src/panels/smart_ui.rs | 4 ++-- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index a1199ccea2..22c47b2960 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -308,13 +308,19 @@ pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option { Some(id) } -/// `params` of the adjustment `command` with every key filled in as the engine reads them: a -/// recorded Photo Filter that names only its `filter` gets that preset's `color`, not the dialog's -/// neutral one. `None` for other commands and for params the engine rejects. +/// `params` of the adjustment `command` with the keys the dialog would otherwise fill in wrongly: +/// a recorded Photo Filter that names only its `filter` gets that preset's `color`, not the +/// dialog's neutral one. Every recorded value is kept as it was (a round trip through the engine +/// would rewrite them: float colours as hex, a pencil curve smoothed again). `None` when nothing +/// needs adding, or for params the engine rejects. pub(crate) fn complete_params(app: &PhotocraftApp, command: &str, params: &Value) -> Option { - let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?; + let kind = command.strip_prefix(PREFIX).filter(|k| *k == "photoFilter")?; + let recorded = params.as_object().filter(|p| p.contains_key("filter") && !p.contains_key("color"))?; let adjustment = photocraft_engine::adjust_params::from_params(kind, params, None, curve_mode(app, kind)).ok()?; - Some(photocraft_engine::adjust_params::to_params(&adjustment)) + let color = photocraft_engine::adjust_params::to_params(&adjustment).get("color").cloned()?; + let mut done = recorded.clone(); + done.insert("color".into(), color); + Some(Value::Object(done)) } /// Remember an adjustment dialog's settings after a successful OK, for [`open_last`]. Editing a diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index d94f783a85..999ccb5700 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -911,12 +911,20 @@ fn photo_filter_reopens_with_the_choice_its_colour_implies() { } /// #9879 review: a recorded Photo Filter that names only its preset completes to that preset's -/// colour, so editing it as a smart filter doesn't swap in the dialog's neutral colour. +/// colour, so editing it as a smart filter doesn't swap in the dialog's neutral colour. Recorded +/// values are kept as they were, and nothing else is rewritten. #[test] fn recorded_photo_filter_settings_complete_to_their_preset_colour() { let app = app_with_image(); - let done = complete_params(&app, "image.adjustments.photoFilter", &json!({"filter": "cooling80", "density": 60})).unwrap(); - assert_eq!((done["color"].as_str(), done["density"].as_f64()), (Some("#006dff"), Some(60.0))); + let pf = "image.adjustments.photoFilter"; + let done = complete_params(&app, pf, &json!({"filter": "cooling80", "density": 60, "extra": [1]})).unwrap(); + assert_eq!(done, json!({"filter": "cooling80", "density": 60, "extra": [1], "color": "#006dff"}), "only the colour is added"); + // A recorded colour (here a float triple the engine would rewrite as hex) is left alone. + assert!(complete_params(&app, pf, &json!({"filter": "cooling80", "color": [0.5, 0.0, 0.0]})).is_none()); + assert!(complete_params(&app, pf, &json!({"density": 60})).is_none(), "no preset to take a colour from"); + assert!(complete_params(&app, pf, &json!({"filter": "nope"})).is_none(), "rejected params"); + // Other adjustments keep their recorded values exactly (a pencil curve isn't smoothed again). + let curves = json!({"pencil": true, "smooth": 2, "rgb": [0, 255]}); + assert!(complete_params(&app, "image.adjustments.curves", &curves).is_none()); assert!(complete_params(&app, "filter.blur.gaussian", &json!({"radius": 2})).is_none(), "not an adjustment"); - assert!(complete_params(&app, "image.adjustments.photoFilter", &json!({"filter": "nope"})).is_none(), "rejected params"); } diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index ff32958bb0..9071bca7b1 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -495,8 +495,8 @@ pub fn open_editor(app: &mut PhotocraftApp, ctx: &egui::Context, layer: u64, sm: }) else { return; }; - // An adjustment's recorded settings are completed first, so a key the record lacks shows (and - // saves) what the engine reads for it rather than the dialog's neutral value. + // A recorded Photo Filter that names only its preset gets the preset's colour, which the + // dialog would otherwise fill in with its neutral one; recorded values stay as they were. let params = crate::adjust_dialog::complete_params(app, &f.command, &f.params).unwrap_or_else(|| f.params.clone()); if let Some(d) = app.ui.dialog_mut(id) { d.fields.insert("__smartFilter".into(), target); From f2a34f0326d958983917d1848131ad4e1be2f9ab Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:56:14 +0100 Subject: [PATCH 019/113] Smart filter: a null Photo Filter colour completes from its preset Review follow-up for #9879: the engine reads `"color": null` as no colour and uses the `filter` preset, so `complete_params` now completes it the same way instead of leaving the dialog on its neutral colour. Regression case added to `recorded_photo_filter_settings_complete_to_their_preset_colour`. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog.rs | 3 ++- crates/ui-egui/src/dialogs/adjust_dialog/tests.rs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index 22c47b2960..48e8b26210 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -315,7 +315,8 @@ pub fn open_last(app: &mut PhotocraftApp, command: &str) -> Option { /// needs adding, or for params the engine rejects. pub(crate) fn complete_params(app: &PhotocraftApp, command: &str, params: &Value) -> Option { let kind = command.strip_prefix(PREFIX).filter(|k| *k == "photoFilter")?; - let recorded = params.as_object().filter(|p| p.contains_key("filter") && !p.contains_key("color"))?; + // A `null` colour reads as none, as the engine reads it. + let recorded = params.as_object().filter(|p| p.contains_key("filter") && p.get("color").is_none_or(Value::is_null))?; let adjustment = photocraft_engine::adjust_params::from_params(kind, params, None, curve_mode(app, kind)).ok()?; let color = photocraft_engine::adjust_params::to_params(&adjustment).get("color").cloned()?; let mut done = recorded.clone(); diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index 999ccb5700..b675e3d769 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -921,6 +921,8 @@ fn recorded_photo_filter_settings_complete_to_their_preset_colour() { assert_eq!(done, json!({"filter": "cooling80", "density": 60, "extra": [1], "color": "#006dff"}), "only the colour is added"); // A recorded colour (here a float triple the engine would rewrite as hex) is left alone. assert!(complete_params(&app, pf, &json!({"filter": "cooling80", "color": [0.5, 0.0, 0.0]})).is_none()); + let null = complete_params(&app, pf, &json!({"filter": "cooling80", "color": null})).unwrap(); + assert_eq!(null["color"], json!("#006dff"), "a null colour completes from the preset, as the engine reads it"); assert!(complete_params(&app, pf, &json!({"density": 60})).is_none(), "no preset to take a colour from"); assert!(complete_params(&app, pf, &json!({"filter": "nope"})).is_none(), "rejected params"); // Other adjustments keep their recorded values exactly (a pencil curve isn't smoothed again). From 77339962cc12ccda3ea6df858b8c9fb210b06868 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 16:49:12 +0100 Subject: [PATCH 020/113] xtask: panel-commands allowlist follows main's panels/ split; lexer helpers keep clippy's complexity limit Main moved crates/ui-egui/src/panels.rs into panels/*.rs, so the color_field entry now names panels/color.rs (scorecard note too), and main's cognitive_complexity deny split lex()'s block comment and string skipping into helpers. Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 2 +- scorecard/automation.toml | 2 +- xtask/src/panel_commands.rs | 94 +++++++++++++++++++++---------------- 3 files changed, 56 insertions(+), 42 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 3ef2d3940c..2c9078f9ff 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -262,7 +262,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial, Include All Subfolders (includeSubfolders: depth/loop/file-count bounded, results keep their subfolder; Batch and Image Processor dialogs, #3753); no open-documents source, cancel or error-log file | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels.rs color_field assigns the foreground/background colour instead of tools.setColors) | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 573d1e7ec2..137864c30e 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -65,7 +65,7 @@ id = "AUTO-219-8" target = "xtask check that every panel button routes through a command id" status = "partial" issue = 219 -note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels.rs color_field assigns the foreground/background colour instead of tools.setColors)" +note = "cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors)" [[item]] id = "AUTO-219-9" diff --git a/xtask/src/panel_commands.rs b/xtask/src/panel_commands.rs index 5fd82abeb5..eb929acfc7 100644 --- a/xtask/src/panel_commands.rs +++ b/xtask/src/panel_commands.rs @@ -50,7 +50,7 @@ pub const ALLOWLIST: &[Allowed] = &[ // background colour on every drag frame, so the change never reaches the journal, action // recording or the control channel's event log. Fix: dispatch `tools.setColors` (it already exists). Allowed { - file: "crates/ui-egui/src/panels.rs", + file: "crates/ui-egui/src/panels/color.rs", func: "color_field", reason: "Color panel field, hue strip and readout assign session.tools.foreground/background; dispatch tools.setColors", }, @@ -118,24 +118,7 @@ fn lex(src: &str) -> Vec { i += 1; } } else if ch == '/' && at(i + 1) == '*' { - let mut depth = 0usize; - while i < c.len() { - if at(i) == '/' && at(i + 1) == '*' { - depth += 1; - i += 2; - } else if at(i) == '*' && at(i + 1) == '/' { - depth = depth.saturating_sub(1); - i += 2; - if depth == 0 { - break; - } - } else { - if at(i) == '\n' { - line += 1; - } - i += 1; - } - } + (i, line) = skip_block_comment(&c, i, line); } else if let Some(hashes) = raw_string_start(&c, i) { // r"…", r#"…"#, br#"…"#: skip to the quote followed by the same number of hashes. let start_line = line; @@ -153,27 +136,7 @@ fn lex(src: &str) -> Vec { out.push(Token { kind: Kind::Other, line: start_line }); } else if ch == '"' || (ch == 'b' && at(i + 1) == '"') || (ch == 'c' && at(i + 1) == '"') { let start_line = line; - i += if ch == '"' { 1 } else { 2 }; - while i < c.len() { - match at(i) { - '\\' => { - // A line continuation (`\` before a newline) still ends a source line. - if at(i + 1) == '\n' { - line += 1; - } - i += 2; - } - '"' => { - i += 1; - break; - } - '\n' => { - line += 1; - i += 1; - } - _ => i += 1, - } - } + (i, line) = skip_string(&c, i + if ch == '"' { 1 } else { 2 }, line); out.push(Token { kind: Kind::Other, line: start_line }); } else if ch == '\'' || (ch == 'b' && at(i + 1) == '\'') { // Char literal ('a', '\n', b'x') or lifetime/label ('a, 'static). @@ -212,6 +175,57 @@ fn lex(src: &str) -> Vec { out } +/// Skip a (nested) block comment starting at `i`; returns the index after it and the new line. +fn skip_block_comment(c: &[char], mut i: usize, mut line: usize) -> (usize, usize) { + let at = |k: usize| c.get(k).copied().unwrap_or('\0'); + let mut depth = 0usize; + while i < c.len() { + if at(i) == '/' && at(i + 1) == '*' { + depth += 1; + i += 2; + } else if at(i) == '*' && at(i + 1) == '/' { + depth = depth.saturating_sub(1); + i += 2; + if depth == 0 { + break; + } + } else { + if at(i) == '\n' { + line += 1; + } + i += 1; + } + } + (i, line) +} + +/// Skip a quoted string body starting just after its opening quote; returns the index after the +/// closing quote and the new line. +fn skip_string(c: &[char], mut i: usize, mut line: usize) -> (usize, usize) { + let at = |k: usize| c.get(k).copied().unwrap_or('\0'); + while i < c.len() { + match at(i) { + '\\' => { + // A line continuation (`\` before a newline) still ends a source line. + if at(i + 1) == '\n' { + line += 1; + } + i += 2; + } + '"' => { + i += 1; + break; + } + '\n' => { + line += 1; + i += 1; + } + _ => i += 1, + } + } + (i, line) +} + struct RawStart { /// Characters before the body (`r#"` is 3). prefix: usize, From 7a1d2dfd4c64bc19fca46cf8d5cefe1c88b9684a Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:27:14 +0100 Subject: [PATCH 021/113] Tests: image.crop rounds fractional rectangle sizes like its other pixel params Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index fb6f1ec883..d877e0270e 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -427,6 +427,14 @@ fn crop_refuses_a_bad_explicit_rect_instead_of_cropping_to_the_selection() { s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); s.execute("image.crop", json!({"x": 1.0, "y": 1.0, "width": 30.0, "height": 15.0})).unwrap(); assert_eq!(doc(&s).size, Size::new(30, 15)); + // Fractional pixels round, like the rectangle's `x`/`y` and every other pixel param + // (`commands::int`); a side that rounds to 0 is refused. + let mut s = session(); + s.execute("image.crop", json!({"x": 0.4, "y": 0.6, "width": 20.6, "height": 9.5})).unwrap(); + assert_eq!(doc(&s).size, Size::new(21, 10)); + let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": 0.4, "height": 5})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{err:?}"); + assert_eq!(doc(&s).size, Size::new(21, 10)); } #[test] From b309b2784471d94231745f07d0d76d7113734966 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 29 Oct 2026 17:27:22 +0100 Subject: [PATCH 022/113] Address CodeRabbit review: the crop box's H, P and I refuse Alt too egui's `matches_logically(Modifiers::NONE)` ignores Alt as well as Shift, so Alt+H, Alt+P and Alt+I toggled Show Cropped Area, Classic Mode and Front Image; they are now left for later handlers. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/crop_shield.rs | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tools/crop_shield.rs b/crates/ui-egui/src/tools/crop_shield.rs index eb8aeefacb..e7d91c4e82 100644 --- a/crates/ui-egui/src/tools/crop_shield.rs +++ b/crates/ui-egui/src/tools/crop_shield.rs @@ -146,12 +146,13 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { false } -/// `consume_key(Modifiers::NONE, key)` without the presses that hold ⇧: egui ignores an extra ⇧ -/// there, but ⇧+letter is the tool key. Reads each event's own modifiers, which synthetic +/// `consume_key(Modifiers::NONE, key)` without the presses that hold ⇧ or ⌥: egui ignores an +/// extra ⇧ and ⌥ there, but ⇧+letter is the tool key and Alt+letter opens the menu with that +/// mnemonic (Alt+H Help, Alt+I Image). Reads each event's own modifiers, which synthetic /// (control channel) keys carry without changing the frame's. pub(crate) fn consume_unshifted(i: &mut egui::InputState, key: Key) -> bool { let before = i.events.len(); - i.events.retain(|e| !matches!(e, egui::Event::Key { key: k, pressed: true, modifiers, .. } if *k == key && !modifiers.shift && modifiers.matches_logically(Modifiers::NONE))); + i.events.retain(|e| !matches!(e, egui::Event::Key { key: k, pressed: true, modifiers, .. } if *k == key && !modifiers.shift && !modifiers.alt && modifiers.matches_logically(Modifiers::NONE))); i.events.len() != before } @@ -398,6 +399,24 @@ mod tests { } } + /// Alt+H, Alt+P and Alt+I are not the crop box's H, P and I (Show Cropped Area, Classic Mode, + /// Front Image): egui's `consume_key` ignores an extra ⌥, so the plain-key checks must refuse + /// it and leave the press for later handlers. + #[test] + fn alt_letters_are_not_the_crop_box_keys() { + for key in [Key::H, Key::P, Key::I] { + let mut app = crop_app(); + let (shield, ratio) = (app.ui.tool_options.crop_shield.clone(), app.ui.tool_options.crop_ratio.clone()); + let ctx = egui::Context::default(); + let alt = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT }; + ctx.input_mut(|i| i.events.push(alt.clone())); + assert!(!keys(&mut app, &ctx) && !crate::crop_size::keys(&mut app, &ctx), "{key:?}"); + assert_eq!(app.ui.tool_options.crop_shield, shield, "{key:?}"); + assert_eq!(app.ui.tool_options.crop_ratio, ratio, "{key:?}"); + assert!(ctx.input(|i| i.events.contains(&alt)), "{key:?} is left for later handlers"); + } + } + #[test] fn the_color_picker_sets_the_custom_colour() { let mut app = crop_app(); From 13f84218e3cdcc2ca39159d32bf51bd34becc8e4 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:04:59 +0100 Subject: [PATCH 023/113] feat(ui-egui): export dialogs start in the last exported folder (#10192) Export As, Quick Export and Save for Web now start in the folder of the last successful export (new preference export.lastFolder, kept across restarts), falling back to the document's folder when none is remembered or the folder is gone. Save As and non-export save dialogs are unchanged. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/prefs.rs | 5 ++ crates/ui-egui/src/dialogs/export_dialog.rs | 8 +- crates/ui-egui/src/dialogs/file_ui/web.rs | 2 +- crates/ui-egui/src/file_dialog.rs | 70 ++++++++++++++-- crates/ui-egui/src/file_dialog/tests.rs | 92 +++++++++++++++++++++ 5 files changed, 166 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index f2445a2a54..6861adadad 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -543,6 +543,10 @@ pub struct Export { pub webp_quality: u32, pub metadata: ExportMetadata, pub convert_to_srgb: bool, + /// The folder the last successful export through a save dialog went to (Export As, Quick + /// Export, Save for Web, ...). The next export dialog starts there; empty until the first + /// export, and ignored while the folder no longer exists (#10192). + pub last_folder: String, } impl Default for Export { @@ -555,6 +559,7 @@ impl Default for Export { webp_quality: 85, metadata: ExportMetadata::Copyright, convert_to_srgb: true, + last_folder: String::new(), } } } diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 68f46af65f..66efd1503a 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -209,7 +209,7 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result = layers.into_iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, id).map_err(|e| e.to_string())).collect::>()?; let suggested = format!("{}.png", export_name(&st.doc.name)); - app.pick_save(&suggested, move |app, path| { + app.pick_export(&suggested, move |app, path| { if !path.to_ascii_lowercase().ends_with(".png") { return Err("Quick Export as PNG writes .png files".into()); } @@ -1046,7 +1046,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result, ids: &[photoc let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a); let suggested = format!("{}.{}", export_name(stem), s_fmt(f)); let (f, settings) = (f.clone(), settings(f)); - app.pick_save(&suggested, move |app, path| { + app.pick_export(&suggested, move |app, path| { let mut exported = Vec::new(); for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) { let out = export_document(doc, &f, None, &source_profile)?; @@ -1145,7 +1145,7 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result { let st = app.session.active().ok_or("no document")?; let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a); let (suggested, doc) = (format!("{stem}.{fmt}"), st.doc.id); - return app.pick_save(&suggested, move |app, path| { + return app.pick_export(&suggested, move |app, path| { app.refocus(doc)?; quick_export(app, json!({"path": path})) }); diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 62082b4f8d..3cca5f84e3 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -535,7 +535,7 @@ pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map) -> Re let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?; let base = photocraft_doc::slices::base_name(&doc); let suggested = if has_slices && html { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) }; - app.pick_save(&suggested, move |app, path| { + app.pick_export(&suggested, move |app, path| { app.refocus(doc.id)?; if has_slices { let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into()); diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index bddc6796d3..4a706970f2 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -148,17 +148,39 @@ impl PhotocraftApp { /// (#1826, #1866). A caller's explicit directory is kept. The chosen folder is remembered for /// the document the dialog was asked for. pub(crate) fn pick_save(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result + 'static) -> Result { + self.pick_save_in(suggested, false, then) + } + + /// [`Self::pick_save`] for the export flows (Export As, Quick Export, Save for Web, ...): a + /// bare file name starts in the folder of the last successful export (a preference, kept + /// across restarts), as in Photoshop, and beside the document where that folder is unset or + /// gone (#10192, [`export_start_dir`]). Once `then` has exported, the chosen file's folder is + /// remembered; a failed or cancelled export leaves the remembered folder alone. + pub(crate) fn pick_export(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result + 'static) -> Result { + self.pick_save_in(suggested, true, then) + } + + fn pick_save_in( + &mut self, + suggested: &str, + export: bool, + then: impl FnOnce(&mut Self, String) -> Result + 'static, + ) -> Result { let mut suggested = std::path::PathBuf::from(suggested); let doc = self.session.active().map(|d| d.doc.id); // Closed documents' folders are no longer needed. let open: Vec<_> = self.session.documents().iter().map(|d| d.doc.id).collect(); self.save_dirs.retain(|id, _| open.contains(id)); - if suggested.parent().is_some_and(|p| p.as_os_str().is_empty()) - && let Some(dir) = doc + if suggested.parent().is_some_and(|p| p.as_os_str().is_empty()) { + let document_dir = doc .and_then(|d| self.save_dirs.get(&d).cloned()) - .or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf)) - { - suggested = dir.join(suggested); + // An export doesn't start in a folder that is gone. + .filter(|dir| !export || folder_exists(dir)) + .or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf)); + let remembered = export.then(|| self.session.prefs().export.last_folder.clone()); + if let Some(dir) = export_start_dir(remembered.as_deref(), document_dir, folder_exists) { + suggested = dir.join(suggested); + } } // The format comes from the extension, so a name typed without one (common where file // extensions are hidden, #5039) gets the suggested file's extension, as Photoshop's @@ -174,7 +196,11 @@ impl PhotocraftApp { { app.save_dirs.insert(doc, dir.to_path_buf()); } - then(app, path) + let exported = then(app, path.clone())?; + if export { + app.remember_export_folder(&path); + } + Ok(exported) } _ => Err(UNEXPECTED.into()), })?; @@ -184,6 +210,16 @@ impl PhotocraftApp { Ok(asked) } + /// Remember the folder of an export that succeeded as where the next export dialog starts. + /// The web answers a download name, which has no folder, and leaves it alone. + fn remember_export_folder(&mut self, path: &str) { + let Some(dir) = Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()) else { return }; + let dir = dir.to_string_lossy().into_owned(); + if self.session.prefs().export.last_folder != dir { + self.session.prefs.edit(|p| p.export.last_folder = dir); + } + } + /// Whether a save to `path` replaces a file the save dialog didn't ask about: the dialog /// answered `answered`, and [`saved_path`] changed it. A file at `path` that /// [`Services::same_file`](crate::Services::same_file) finds is the same entry as `answered` (the @@ -370,6 +406,28 @@ fn saved_path(app: &PhotocraftApp, answered: &str, suggested_ext: Option<&str>) } } +/// Whether `dir` is a folder on disk. The web has no file system, so nothing is remembered there. +#[cfg(not(target_arch = "wasm32"))] +fn folder_exists(dir: &Path) -> bool { + dir.is_dir() +} + +#[cfg(target_arch = "wasm32")] +fn folder_exists(_dir: &Path) -> bool { + false +} + +/// The folder an export dialog starts in (#10192): the `remembered` folder of the last export +/// while `exists` finds it, else the document's own folder (`document_dir`, whatever it is), +/// else none, which leaves the choice to the system dialog. +pub(crate) fn export_start_dir( + remembered: Option<&str>, + document_dir: Option, + exists: impl Fn(&Path) -> bool, +) -> Option { + remembered.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).filter(|d| exists(d)).or(document_dir) +} + /// The folder an open dialog starts in: the directory of the most recent file (UI-217-3). pub(crate) fn last_used_dir(recent: &[String]) -> Option { let dir = std::path::Path::new(recent.first()?).parent()?; diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index 52149ab8e0..eed533891e 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -1484,3 +1484,95 @@ fn import_variable_data_sets_menu_asks_for_a_csv_and_imports_it() { app.poll_file_dialog(&ctx, None); assert_eq!(app.session.active().map(|d| d.doc.variables.data_sets.len()), Some(2)); } + +/// #10192: the folder an export dialog starts in, as a pure decision. +#[test] +fn export_start_dir_prefers_an_existing_remembered_folder() { + use std::path::PathBuf; + let doc = Some(PathBuf::from("/proj")); + let all_exist = |_: &Path| true; + let none_exist = |_: &Path| false; + // Remembered and present: used. + assert_eq!(export_start_dir(Some("/renders"), doc.clone(), all_exist), Some(PathBuf::from("/renders"))); + // Remembered but gone: the document's folder. + assert_eq!(export_start_dir(Some("/renders"), doc.clone(), none_exist), doc); + // Nothing remembered (unset or empty): the document's folder, or nothing for an untitled one. + assert_eq!(export_start_dir(None, doc.clone(), all_exist), doc); + assert_eq!(export_start_dir(Some(""), doc.clone(), all_exist), doc); + assert_eq!(export_start_dir(None, None, all_exist), None); + assert_eq!(export_start_dir(Some("/renders"), None, none_exist), None); +} + +/// #10192: exports start in the last successfully exported folder, across documents; a failed or +/// cancelled export, a folder that is gone and other save dialogs change nothing. +#[test] +fn exports_start_in_the_last_exported_folder() { + let (mut app, open, _) = app(); + let ctx = egui::Context::default(); + let root = tempfile::tempdir().unwrap(); + let renders = root.path().join("renders"); + std::fs::create_dir(&renders).unwrap(); + let renders_text = renders.to_string_lossy().into_owned(); + app.session.active_mut().unwrap().path = Some("/proj/original.psd".into()); + let suggested = |open: &Open| match &open.borrow()[0].0 { + FileDialogRequest::Save { suggested } => suggested.clone(), + other => panic!("save dialog expected, got {other:?}"), + }; + let remembered = |app: &PhotocraftApp| app.session.prefs().export.last_folder.clone(); + // No export yet: beside the document. Cancelled, nothing is remembered. + app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(suggested(&open), joined("/proj", "a.png")); + answer(&open, None); + app.poll_file_dialog(&ctx, None); + assert_eq!(remembered(&app), ""); + // The user picks another folder, but the export fails: nothing is remembered. + app.pick_export("a.png", |_, _| Err("disk full".into())).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png")))); + app.poll_file_dialog(&ctx, None); + assert_eq!(remembered(&app), ""); + // A successful export is remembered... + app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png")))); + app.poll_file_dialog(&ctx, None); + assert_eq!(remembered(&app), renders_text); + // ...and starts the next export, of any document, even an untitled one. + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + app.pick_export("b.png", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(suggested(&open), joined(&renders_text, "b.png")); + // A cancelled dialog changes nothing. + answer(&open, None); + app.poll_file_dialog(&ctx, None); + assert_eq!(remembered(&app), renders_text); + // Other save dialogs keep their own start. + app.pick_save("c.psd", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(suggested(&open), "c.psd"); + answer(&open, None); + app.poll_file_dialog(&ctx, None); + // The folder disappears: back to the document's folder. + std::fs::remove_dir(&renders).unwrap(); + app.session.set_active(0); + app.pick_export("d.png", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(suggested(&open), joined("/proj", "d.png")); + answer(&open, None); + app.poll_file_dialog(&ctx, None); +} + +#[test] +fn the_last_export_folder_is_a_preference_that_old_files_lack() { + let prefs = photocraft_engine::prefs::Preferences::default(); + assert_eq!(prefs.export.last_folder, ""); + let mut json = serde_json::to_value(&prefs).unwrap(); + json["export"]["lastFolder"] = "/renders".into(); + let loaded: photocraft_engine::prefs::Preferences = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(loaded.export.last_folder, "/renders"); + // Settings saved before the field existed still load. + json["export"].as_object_mut().unwrap().remove("lastFolder"); + let old: photocraft_engine::prefs::Preferences = serde_json::from_value(json).unwrap(); + assert_eq!(old.export.last_folder, ""); +} From 6f2fe52bb5387a680310a1bcb3b5cc00e081d916 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:38:51 +0100 Subject: [PATCH 024/113] fix(ui): a failed export doesn't change where the next export starts (#10192) The document's save folder is now stored for an export only once the export has succeeded; other saves keep storing it before writing, as before. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/file_dialog.rs | 12 ++++++++---- crates/ui-egui/src/file_dialog/tests.rs | 6 ++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 4a706970f2..e97318b2e2 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -191,13 +191,17 @@ impl PhotocraftApp { FileDialogAnswer::SaveTo(path) => { let path = saved_path(app, &path, suggested_ext.as_deref()); // The web answers a download name, which has no folder to remember. - if let Some(doc) = doc - && let Some(dir) = Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty()) - { - app.save_dirs.insert(doc, dir.to_path_buf()); + let dir = doc.zip(Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf)); + // An export's folder only once it has exported: a failed one doesn't move where + // the next export starts. + if !export && let Some((doc, dir)) = dir.clone() { + app.save_dirs.insert(doc, dir); } let exported = then(app, path.clone())?; if export { + if let Some((doc, dir)) = dir { + app.save_dirs.insert(doc, dir); + } app.remember_export_folder(&path); } Ok(exported) diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs index eed533891e..82ae0097aa 100644 --- a/crates/ui-egui/src/file_dialog/tests.rs +++ b/crates/ui-egui/src/file_dialog/tests.rs @@ -1532,6 +1532,12 @@ fn exports_start_in_the_last_exported_folder() { answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png")))); app.poll_file_dialog(&ctx, None); assert_eq!(remembered(&app), ""); + // ...and the next export still starts beside the document, not in the failed export's folder. + app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(suggested(&open), joined("/proj", "a.png")); + answer(&open, None); + app.poll_file_dialog(&ctx, None); // A successful export is remembered... app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap(); app.poll_file_dialog(&ctx, None); From 79ead9a4af28f76a93e20ac9951d2b7a8ac1f01f Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 09:12:10 +0100 Subject: [PATCH 025/113] docs: tidy comments (review) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/file_dialog.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index e97318b2e2..cb30df9a44 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -151,11 +151,9 @@ impl PhotocraftApp { self.pick_save_in(suggested, false, then) } - /// [`Self::pick_save`] for the export flows (Export As, Quick Export, Save for Web, ...): a - /// bare file name starts in the folder of the last successful export (a preference, kept - /// across restarts), as in Photoshop, and beside the document where that folder is unset or - /// gone (#10192, [`export_start_dir`]). Once `then` has exported, the chosen file's folder is - /// remembered; a failed or cancelled export leaves the remembered folder alone. + /// [`Self::pick_save`] for the export flows (Export As, Quick Export, Save for Web, ...): starts in + /// the folder [`export_start_dir`] picks (#10192), and once `then` has exported, remembers the + /// chosen file's folder in `export.lastFolder`; a failed or cancelled export leaves it alone. pub(crate) fn pick_export(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result + 'static) -> Result { self.pick_save_in(suggested, true, then) } From 52ba921651368e2195dcbcd705648d5d7cfb6001 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:29:56 +0100 Subject: [PATCH 026/113] Test: Photo Filter remembers Preserve Luminosity turned off photo_filter_opens_at_its_last_settings only confirmed a filter and density, so Preserve Luminosity kept its default (on) and a regression dropping it would still pass. It now turns Preserve Luminosity off, confirms, reopens and checks it stays off with the rest of the last settings (CodeRabbit review of #9970). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog/tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index 1f6090025c..a06c1dc800 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -959,6 +959,15 @@ fn photo_filter_opens_at_its_last_settings() { let again = open(&mut app, cmd).unwrap(); assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()), sample, "reopened at the last settings"); + // Preserve Luminosity is on by default; turned off and confirmed, it reopens off. + assert_eq!(neutral["preserveLuminosity"], json!(true)); + app.ui.dialog_mut(again).unwrap().fields.insert("preserveLuminosity".into(), json!(false)); + crate::dialogs::confirm(&mut app, again).unwrap(); + let again = open(&mut app, cmd).unwrap(); + let reopened = crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()); + assert_eq!(reopened["preserveLuminosity"], json!(false), "Preserve Luminosity off is remembered"); + assert_eq!(reopened["color"], sample["color"], "with the rest of the last settings"); + assert_eq!(reopened["density"], sample["density"]); app.ui.dialogs.clear(); let smart = open_neutral(&mut app, cmd).unwrap(); assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(smart).unwrap().fields.clone()), neutral, "open_neutral ignores them"); From dec95112a06a56480b408a566b28adc9c5f6de53 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:53:33 +0100 Subject: [PATCH 027/113] Remove gradient stops dragged off the bar in every stop editor (#10742) Dragging a colour stop down, or an opacity stop up, by about a marker's height off the gradient bar now removes it on release in every stop editor, as in Photoshop's Gradient Editor. At least two stops of that kind always stay. While the stop is off the bar the ramp and the preview show it gone, and dragging it back onto the bar cancels. The Gradient Editor, Properties and shape gradient strips already did this. Gradient Map had no drag-off at all, and Layer Style's Gradient Overlay only deleted after about 44 pt and showed nothing until release. All four now share stop_dragged_off() in gradient_ui.rs (26 pt past the bar edge, by kind). Gradient Map and Gradient Overlay take the stop out live and put it back if it returns. Adds harness tests for drag-off removal, the two-stop minimum, opacity stops dragged up and drag-back cancel, and updates docs/ui-parity.md. Co-Authored-By: Claude Opus 5.5 --- .../dialogs/adjust_editors/gradient_map.rs | 41 +++++- .../src/dialogs/adjust_editors/ui_tests.rs | 49 +++++++ .../src/dialogs/layer_style/gradient_field.rs | 112 ++++++++++++--- crates/ui-egui/src/tools/gradient_ui.rs | 21 ++- .../src/tools/gradient_ui/editor_tests.rs | 133 ++++++++++++++++++ crates/ui-egui/src/tools/shape_gradient_ui.rs | 4 +- docs/ui-parity.md | 4 +- 7 files changed, 330 insertions(+), 34 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs index 7079b11972..b15f06ba0c 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs @@ -57,6 +57,9 @@ struct MapStopDrag { index: usize, offset: f32, changed: bool, + /// The dragged stop while it is pulled off the bar (removed from the stops, so the preview + /// shows it gone); dragging back onto the bar puts it back. + removed: Option, } /// Keep selection on the same stop when it crosses another stop (including coincident stops). @@ -87,19 +90,43 @@ fn gradient_map_strip(ui: &mut egui::Ui, stops: &mut Vec, cx: &EditorCx, s { *selected = index; let offset = stops.get(index).map_or(0.0, |s| pos.x - x_of(s.0)); - ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false })); + ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false, removed: None })); } if let Some(mut drag) = ui.data(|d| d.get_temp::(key)) { if (resp.dragged() || resp.drag_stopped()) && let Some(pos) = resp.interact_pointer_pos() { let location = round(loc_of(pos.x - drag.offset), 0.001); - let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); - if let Some(index) = move_map_stop(stops, drag.index, location) { - drag.index = index; - drag.changed |= changed; - *selected = index; - edit.changed |= changed; + // Pulled down off the bar, the stop is removed while at least two remain, as in + // Photoshop; released there it stays deleted, dragged back it returns. + let off = crate::gradient_ui::stop_dragged_off(bar, pos, false); + match drag.removed { + None if off && stops.len() > 2 && drag.index < stops.len() => { + drag.removed = Some(stops.remove(drag.index)); + *selected = drag.index.min(stops.len().saturating_sub(1)); + drag.changed = true; + edit.changed = true; + } + Some(stop) if !off => { + stops.push(stop); + let index = stops.len() - 1; + drag.removed = None; + if let Some(index) = move_map_stop(stops, index, location) { + drag.index = index; + *selected = index; + } + edit.changed = true; + } + Some(_) => {} + None => { + let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); + if let Some(index) = move_map_stop(stops, drag.index, location) { + drag.index = index; + drag.changed |= changed; + *selected = index; + edit.changed |= changed; + } + } } } if resp.drag_stopped() { diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index f41fe4eca0..bb0f737265 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -560,6 +560,55 @@ fn gradient_map_strip_adds_selects_and_removes_stops_without_deleting_the_last_p assert_eq!(layer(&h).1, original, "keep two stops"); } +/// #10742: a Gradient Map stop dragged down off the bar is removed on release (one history step); +/// while it is off the bar the live preview already leaves it out, and dragging it back onto the +/// bar before release puts it back. The last two stops can't be dragged off. +#[test] +fn gradient_map_stop_dragged_down_off_the_bar_is_removed_and_dragging_back_cancels() { + let mut h = app_harness("gradientMap", "rgb", 8); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "stops": [[0, "#000000"], [0.5, "#ff0000"], [1, "#ffffff"]]})).unwrap(); + h.run_steps(3); + let three = layer(&h).1; + let live_stops = |h: &Harness<'_, PhotocraftApp>| h.state().live_adjust.as_ref().and_then(|(_, v)| v["stops"].as_array().map(Vec::len)); + // Off and back: nothing removed. + let start = map_handle(&h, 0.5); + let away = start + vec2(0.0, 30.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(start + vec2(0.0, 15.0)); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + assert_eq!(live_stops(&h), Some(2), "off the bar the preview leaves the stop out"); + h.hover_at(start); + h.run_steps(1); + assert_eq!(live_stops(&h), Some(3), "back on the bar the stop returns"); + h.drop_at(start); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1), map_stops(&three), "dragging back cancels the removal"); + // Off and released: removed in one step. + let steps = h.state().session.active().unwrap().history.past_len(); + drag(&mut h, start, away); + assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (1.0, [255, 255, 255])]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); + assert!(h.state().live_adjust.is_none()); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(layer(&h).1, three); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + // Two stops stay. + let two = layer(&h).1; + for at in [0.0, 1.0] { + let from = map_handle(&h, at); + drag(&mut h, from, from + vec2(0.0, 40.0)); + assert_eq!(map_stops(&layer(&h).1), map_stops(&two), "two stops always remain"); + } +} + #[test] fn gradient_map_drag_clamps_at_the_endpoints_and_reverse_keeps_stop_coordinates() { let mut h = app_harness("gradientMap", "rgb", 8); diff --git a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs index 8abbefbbd7..c59b666b3f 100644 --- a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs +++ b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs @@ -23,6 +23,16 @@ pub(super) const KEY: &str = "stops"; /// The dialog field holding the transparency stops. pub(super) const OPACITY_KEY: &str = "opacityStops"; +/// A colour stop being dragged on the page's ramp. +#[derive(Clone, Copy, Debug)] +struct StopDrag { + /// The stop's index (it changes as the stop passes others). + index: usize, + /// The stop while it is pulled off the bar: deleted from the gradient, so the ramp and the + /// canvas show it gone; dragging back onto the bar puts it back. + removed: Option<(f32, Color)>, +} + /// Where the last drawn ramp bar is, for tests that drive it: `(effect id, bar rect)`. pub(crate) fn bar_id() -> egui::Id { egui::Id::unique("fx-gradient-bar") @@ -207,39 +217,64 @@ pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map(drag_key)); + ui.data_mut(|d| d.remove::(drag_key)); } } - let dragging: Option = ui.data(|d| d.get_temp(drag_key)); - if let (Some(i), Some(p)) = (dragging, resp.interact_pointer_pos()) { - let away = p.y > outer.bottom() + 24.0 || p.y < bar.top() - 24.0; + let dragging: Option = ui.data(|d| d.get_temp(drag_key)); + if let (Some(mut drag), Some(p)) = (dragging, resp.interact_pointer_pos()) { + let off = crate::gradient_ui::stop_dragged_off(bar, p, false); + let loc = loc_of(p.x); if resp.drag_stopped() { - ui.data_mut(|d| d.remove::(drag_key)); - if away && stops.len() > 2 { - edit(app, f, effect, disp, json!({"action": "delete", "index": i})); - ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); - } - } else if resp.dragged() && !away { - let loc = loc_of(p.x); - if (loc - stops.get(i).map_or(loc, |s| s.0)).abs() > 1e-4 - && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": i, "location": loc})) - { - ui.data_mut(|d| d.insert_temp(drag_key, at)); - ui.data_mut(|d| d.insert_temp(sel_key, at)); + // Released off the strip, the stop is already gone. + ui.data_mut(|d| d.remove::(drag_key)); + } else if resp.dragged() { + match drag.removed { + None if off && stops.len() > 2 => { + if let Some(stop) = stops.get(drag.index).copied() + && edit(app, f, effect, disp, json!({"action": "delete", "index": drag.index})).is_some() + { + drag.removed = Some(stop); + ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + } + } + Some((_, color)) if !off => { + let mut back = stops.clone(); + back.push((loc, color)); + back.sort_by(|a, b| a.0.total_cmp(&b.0)); + let index = back.iter().rposition(|s| s.0 == loc).unwrap_or(0); + let mut fill = fill.clone(); + if let Fill::Gradient { stops, .. } = &mut fill { + *stops = back; + } + commit(f, effect, disp, &fill); + drag = StopDrag { index, removed: None }; + ui.data_mut(|d| d.insert_temp(sel_key, index)); + } + Some(_) => {} + None => { + if (loc - stops.get(drag.index).map_or(loc, |s| s.0)).abs() > 1e-4 + && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": drag.index, "location": loc})) + { + drag.index = at; + ui.data_mut(|d| d.insert_temp(sel_key, at)); + } + } } + ui.data_mut(|d| d.insert_temp(drag_key, drag)); } } else if resp.drag_stopped() { - ui.data_mut(|d| d.remove::(drag_key)); + ui.data_mut(|d| d.remove::(drag_key)); } if resp.double_clicked() && let Some(p) = resp.interact_pointer_pos() @@ -385,6 +420,41 @@ mod tests { assert_eq!(stops_in(h.state(), parent).len(), 2); } + /// #10742: on the Gradient Overlay page a colour stop dragged down off the bar (about a + /// marker's height) disappears while it is off, is gone on release, and comes back when + /// dragged back onto the bar first. + #[test] + fn a_stop_dragged_off_the_ramp_shows_gone_and_dragging_back_cancels() { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]])); + let mut h = harness(app, parent); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn"); + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + let away = pos2(mid.x, mid.y + 22.0); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(stops_in(h.state(), parent).len(), 2, "off the bar the stop is gone"); + h.event(egui::Event::PointerMoved(mid)); + h.run_steps(1); + let back = stops_in(h.state(), parent); + assert_eq!(back.len(), 3, "back on the bar it returns: {back:?}"); + release(&mut h, mid); + let back = stops_in(h.state(), parent); + assert!(back.len() == 3 && (back[1].0 - 0.5).abs() < 0.01 && super::super::hex(&back[1].1) == "#ff0000", "{back:?}"); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + release(&mut h, away); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.iter().map(|s| super::super::hex(&s.1)).collect::>(), ["#000000", "#ffffff"], "{stops:?}"); + } + /// A preset from the Gradients panel becomes the page's stops; the Delete button and the /// Location field work on the selected stop. #[test] diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 1978f27086..12d2faeedd 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -516,6 +516,19 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } } +/// How far past the gradient bar's edge (in points) a dragged stop comes off it: the stop marker +/// (about 15 pt) plus roughly its height again, as in Photoshop's Gradient Editor. +pub(crate) const STOP_OFF_BAR: f32 = 26.0; + +/// Whether a stop dragged to `pos` is pulled off `bar`, as in Photoshop's Gradient Editor: a +/// colour stop (under the bar) dragged down, an opacity stop (above it) dragged up, about a +/// marker's height past the marker. Every stop strip uses this, so the gesture is the same in +/// the Gradient Editor, Properties, the shape gradient popover, Gradient Map and Layer Style. +/// The caller removes the stop only while more than two of its kind remain. +pub(crate) fn stop_dragged_off(bar: Rect, pos: Pos2, opacity: bool) -> bool { + if opacity { pos.y < bar.top() - STOP_OFF_BAR } else { pos.y > bar.bottom() + STOP_OFF_BAR } +} + // ---------------------------------------------------------------- options bar /// A ramp of RGBA stops over a checkerboard in `r`. @@ -995,12 +1008,14 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi let dragging: Option = ui.data(|d| d.get_temp(key)); let mut preview = None; if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) { - let off = if pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0 { 1.0 } else { 0.0 }; + // Pulled off the bar, the stop is deleted (the preview shows it gone; dragging back + // cancels), while at least two of its kind remain. + let off = stop_dragged_off(bar, pos, matches!(m, Marker::Opacity(_))); let loc = loc_of(pos.x); let edit = match m { - Marker::Color(i) if off > 0.0 && stops.len() > 2 => json!({"action": "delete", "index": i}), + Marker::Color(i) if off && stops.len() > 2 => json!({"action": "delete", "index": i}), Marker::Color(i) => json!({"action": "move", "index": i, "location": loc}), - Marker::Opacity(i) if off > 0.0 && ops.len() > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), + Marker::Opacity(i) if off && ops.len() > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), Marker::Opacity(i) => json!({"action": "move", "kind": "opacity", "index": i, "location": loc}), Marker::Mid(i) => { let (a, b) = (sorted.get(i).map_or(0.0, |s| s.0), sorted.get(i + 1).map_or(1.0, |s| s.0)); diff --git a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs index 8bc5019ddf..c761838f36 100644 --- a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs +++ b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs @@ -144,3 +144,136 @@ fn preset_editor_opacity_fields_do_not_edit_document_history() { assert_eq!(h.state().session.active().unwrap().doc, before); assert_eq!(h.state().session.active().unwrap().history.past_len(), history); } + +/// Press at `points[0]`, move through the rest, then release at the last one; `during` runs while +/// the button is still down at the last point. +fn drag_through(h: &mut Harness, points: &[Pos2], during: impl FnOnce(&mut Harness)) { + let (Some(&from), Some(&to)) = (points.first(), points.last()) else { return }; + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for &p in &points[1..] { + // Two small steps per leg, as a real pointer reports. + let last = h.ctx.input(|i| i.pointer.latest_pos()).unwrap_or(p); + h.event(egui::Event::PointerMoved(last + (p - last) * 0.5)); + h.run_steps(1); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + during(h); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +/// A stop marker's centre on the strip: colour stops under the bar, opacity stops above it. +fn marker(h: &Harness, location: f32, opacity: bool) -> Pos2 { + let rect = h.get_by_label("Gradient stops").rect(); + pos2(rect.left() + 8.0 + location * (rect.width() - 16.0), rect.top() + if opacity { 6.0 } else { 50.0 }) +} + +fn counts(h: &Harness, sink: Sink) -> (usize, usize) { + let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + (stops.len(), opacity_stops.len()) +} + +/// The strip as drawn while the pointer is down: the pending edit applied to the gradient. +fn shown(h: &Harness, sink: Sink) -> (usize, usize) { + let f = sink.fill(h.state()).unwrap(); + let pending = match sink { + Sink::Layer(_) => h.state().gradient.panel.as_ref().map(|(.., p)| p.clone()), + Sink::Preset => h.state().gradient.preset_stop.clone(), + }; + let (fg, bg) = (h.state().session.tools.foreground, h.state().session.tools.background); + let f = pending.and_then(|p| cmds::apply_stop(&f, &p, fg, bg).ok()).unwrap_or(f); + let Fill::Gradient { stops, opacity_stops, .. } = f else { panic!() }; + (stops.len(), opacity_stops.len()) +} + +/// #10742: a colour stop dragged down off the bar (by about a marker's height) is removed on +/// release; while it is off the bar the strip already shows it gone; one undo step restores it. +#[test] +fn a_color_stop_dragged_down_off_the_bar_is_removed() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let history = h.state().session.active().unwrap().history.past_len(); + let before = sink.fill(h.state()).unwrap(); + let from = marker(&h, 0.5, false); + drag_through(&mut h, &[from, from + vec2(0.0, 22.0)], |h| { + assert_eq!(shown(h, sink), (2, 3), "layer {layer}: the dragged-off stop is gone from the preview"); + assert_eq!(sink.fill(h.state()).unwrap(), before, "layer {layer}: nothing is committed before release"); + }); + let Fill::Gradient { stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + assert_eq!(stops.iter().map(|s| s.0).collect::>(), [0.0, 1.0], "layer {layer}: the middle stop is removed"); + assert_eq!(counts(&h, sink), (2, 3), "layer {layer}: opacity stops are untouched"); + if layer { + assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1, "one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(sink.fill(h.state()).unwrap(), before); + } + } +} + +/// Dragging a stop off the bar and back onto it before releasing cancels the removal. +#[test] +fn dragging_a_stop_back_onto_the_bar_cancels_the_removal() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + for opacity in [false, true] { + let from = marker(&h, 0.5, opacity); + let away = from + vec2(0.0, if opacity { -30.0 } else { 30.0 }); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + (away - from) * 0.5)); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(shown(&h, sink), if opacity { (3, 2) } else { (2, 3) }, "layer {layer}: off the bar the stop is gone"); + // Back on the bar before release: the stop returns and stays where it was. + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + assert_eq!(shown(&h, sink), (3, 3), "layer {layer}: back on the bar, the stop is shown"); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + let locations: Vec = if opacity { opacity_stops.iter().map(|s| s.0).collect() } else { stops.iter().map(|s| s.0).collect() }; + assert_eq!((stops.len(), opacity_stops.len()), (3, 3), "layer {layer} opacity {opacity}: nothing removed"); + assert!((locations[1] - 0.5).abs() < 1e-3, "layer {layer} opacity {opacity}: {locations:?}"); + } + } +} + +/// The last two colour stops stay: dragging one off the bar leaves it where it is. +#[test] +fn the_last_two_color_stops_cannot_be_dragged_off() { + let (mut h, sink) = editor(true); + let from = marker(&h, 0.5, false); + drag_through(&mut h, &[from, from + vec2(0.0, 60.0)], |_| {}); + assert_eq!(counts(&h, sink), (2, 3)); + let after = sink.fill(h.state()).unwrap(); + for location in [0.0, 1.0] { + let from = marker(&h, location, false); + drag_through(&mut h, &[from, from + vec2(0.0, 60.0)], |h| assert_eq!(shown(h, sink).0, 2, "the preview keeps two stops")); + assert_eq!(sink.fill(h.state()).unwrap(), after, "two colour stops always remain"); + } +} + +/// An opacity stop dragged up off the bar is removed; dragging it down over the ramp is not. +#[test] +fn an_opacity_stop_dragged_up_off_the_bar_is_removed() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let from = marker(&h, 0.5, true); + drag_through(&mut h, &[from, from - vec2(0.0, 30.0)], |h| assert_eq!(shown(h, sink), (3, 2), "layer {layer}")); + let Fill::Gradient { opacity_stops, stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + assert_eq!(opacity_stops.iter().map(|s| s.0).collect::>(), [0.0, 1.0], "layer {layer}"); + assert_eq!(stops.len(), 3, "layer {layer}: colour stops are untouched"); + // Two opacity stops remain: the next one dragged up stays. + let before = sink.fill(h.state()).unwrap(); + let from = marker(&h, 0.0, true); + drag_through(&mut h, &[from, from - vec2(0.0, 30.0)], |_| {}); + assert_eq!(sink.fill(h.state()).unwrap(), before, "layer {layer}: two opacity stops always remain"); + } +} diff --git a/crates/ui-egui/src/tools/shape_gradient_ui.rs b/crates/ui-egui/src/tools/shape_gradient_ui.rs index e2fbfdb679..c4a6c9068a 100644 --- a/crates/ui-egui/src/tools/shape_gradient_ui.rs +++ b/crates/ui-egui/src/tools/shape_gradient_ui.rs @@ -347,8 +347,8 @@ fn stops_strip(ui: &mut egui::Ui, fill: &Fill, id: egui::Id, fg: [f32; 4], bg: [ let (start_cs, start_os, _) = sorted_stops(&drag.start); let pos = resp.interact_pointer_pos(); if let Some(pos) = pos { - // Dragged well off the strip, a stop is deleted (while at least two remain), as in Photoshop. - let off = pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0; + // Dragged off the strip, a stop is deleted (while at least two remain), as in Photoshop. + let off = crate::gradient_ui::stop_dragged_off(bar, pos, matches!(drag.marker, Marker::Opacity(_))); let loc = loc_of(pos.x); let edit = match drag.marker { Marker::Color(i) if off && start_cs.len() > 2 => json!({"action": "delete", "index": i}), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 56f26760e1..8bc4974646 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -240,6 +240,7 @@ Paragraph; the rest open as in-app floating windows. | Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | The Type tool's Color Picker (Text Color) and a gradient fill's Color Picker (Stop Color) preview the picked colour on the canvas before OK (the selected characters, every selected type layer, or the stop); Cancel restores the document with no history step, OK commits the previewed edit in one step (#5530) | done: `dialogs/color_picker_preview.rs`, `dialogs/color_picker_preview/tests.rs` | | +| Gradient stops come off the bar: a colour stop dragged down, or an opacity stop dragged up, by about a marker's height is removed on release while two of its kind remain; while it is off the ramp and canvas preview show it gone, and dragging it back onto the bar cancels; the selected stop's Delete button does the same. Gradient Editor, Properties, the shape gradient popover, Gradient Map and Layer Style (Gradient Overlay) share one rule (#10742) | done: `tools/gradient_ui.rs` `stop_dragged_off`, `tools/gradient_ui/editor_tests.rs`, `adjust_editors/ui_tests.rs`, `layer_style/gradient_field.rs`. Differs: Gradient Map and Layer Style show colour stops only; no Delete-key shortcut for the selected stop | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | @@ -266,6 +267,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | Gradient stops dragged off the bar are removed, with a live preview and drag-back cancel, in every stop editor: Gradient Map and Layer Style gained it, the Gradient Editor, Properties and shape popover share the same threshold (#10742); row added (done); no percentage changed | | 2026-11-01 | minor | Every preference takes effect: 11 of 183 do nothing (was 12); Graphics Adapter always worked, but startup read it by raw JSON key, which the scorecard audit can't see | | 2026-10-29 | minor | Paragraph box overflow: text a box can't hold enlarges the box's lower-right handle and shows a black + in it, as the reference application does (#8311); agents read `typeBoxOverflow` in `ui.inspect`. Not a new command, so no percentage changed | | 2026-10-28 | minor | The text and gradient stop Color Pickers preview the picked colour on the canvas before OK, as Photoshop's do (#5530); no percentage changed | From 2d30a2b669ae008915d02633bbcf0fa16ba09568 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:37:01 +0100 Subject: [PATCH 028/113] Gradient stops: the release frame decides drag-off; review fixes (#10742) The Gradient Editor/Properties strip and Layer Style's Gradient Overlay ramp ignored the release frame. When the last pointer move came in the same frame as the release, the stop stayed in the state the previous frame left it in. A stop flicked off the bar was kept, and one brought back onto the bar at release was deleted. Both now apply the same drag-off rule on that frame, as Gradient Map and the shape strip already did. The editor strip also counted opacity stops from its preview, which already leaves a dragged-off stop out. So while an opacity stop was off the bar, the preview flipped between deleting and moving it every frame. It now counts the committed stops, like colour stops. Tests: a quick release off the bar and back onto it (both editors); colour stops dragged up and opacity stops dragged down are kept; a cancelled Gradient Map drag adds no history step. The parity row names Gradient Map's control "Remove stop". Co-Authored-By: Claude Opus 5.5 --- .../src/dialogs/adjust_editors/ui_tests.rs | 2 + .../src/dialogs/layer_style/gradient_field.rs | 44 +++++++++++++-- crates/ui-egui/src/tools/gradient_ui.rs | 10 ++-- .../src/tools/gradient_ui/editor_tests.rs | 54 ++++++++++++++++++- docs/ui-parity.md | 2 +- 5 files changed, 102 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index bb0f737265..625039a692 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -570,6 +570,7 @@ fn gradient_map_stop_dragged_down_off_the_bar_is_removed_and_dragging_back_cance h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "stops": [[0, "#000000"], [0.5, "#ff0000"], [1, "#ffffff"]]})).unwrap(); h.run_steps(3); let three = layer(&h).1; + let before_cancel = h.state().session.active().unwrap().history.past_len(); let live_stops = |h: &Harness<'_, PhotocraftApp>| h.state().live_adjust.as_ref().and_then(|(_, v)| v["stops"].as_array().map(Vec::len)); // Off and back: nothing removed. let start = map_handle(&h, 0.5); @@ -589,6 +590,7 @@ fn gradient_map_stop_dragged_down_off_the_bar_is_removed_and_dragging_back_cance h.drop_at(start); h.run_steps(3); assert_eq!(map_stops(&layer(&h).1), map_stops(&three), "dragging back cancels the removal"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before_cancel, "a cancelled drag adds no history step"); // Off and released: removed in one step. let steps = h.state().session.active().unwrap().history.past_len(); drag(&mut h, start, away); diff --git a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs index c59b666b3f..e5e253caab 100644 --- a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs +++ b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs @@ -235,10 +235,9 @@ pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map(drag_key)); - } else if resp.dragged() { + // The release frame applies the same rule (its last move may cross the edge), then ends + // the drag. + if resp.dragged() || resp.drag_stopped() { match drag.removed { None if off && stops.len() > 2 => { if let Some(stop) = stops.get(drag.index).copied() @@ -271,7 +270,11 @@ pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map(drag_key)); + } else { + ui.data_mut(|d| d.insert_temp(drag_key, drag)); + } } } else if resp.drag_stopped() { ui.data_mut(|d| d.remove::(drag_key)); @@ -455,6 +458,37 @@ mod tests { assert_eq!(stops.iter().map(|s| super::super::hex(&s.1)).collect::>(), ["#000000", "#ffffff"], "{stops:?}"); } + /// The release frame counts: a stop that leaves the strip in the frame it is released is + /// removed, and one brought back onto the strip in that frame is kept. + #[test] + fn the_release_frame_decides_whether_a_stop_comes_off_the_ramp() { + for back in [true, false] { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]])); + let mut h = harness(app, parent); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn"); + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + let away = pos2(mid.x, mid.y + 30.0); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + if back { + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(stops_in(h.state(), parent).len(), 2, "off the strip the stop is gone"); + } + let to = if back { mid } else { away }; + // The last move and the release in one frame (`Harness::event` gives each its own). + let input = &mut h.input_mut().events; + input.push(egui::Event::PointerMoved(to)); + input.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.len(), if back { 3 } else { 2 }, "back {back}: {stops:?}"); + } + } + /// A preset from the Gradients panel becomes the page's stops; the Delete button and the /// Location field work on the selected stop. #[test] diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index 12d2faeedd..daa9a9344f 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -903,7 +903,10 @@ fn selection_after_edit(f: &Fill, p: &Value, previous: Option) -> Option } fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pending: Option<&Value>, colors: ([f32; 4], [f32; 4])) -> Option { - let Fill::Gradient { stops, .. } = f else { return None }; + // The stops as committed: a drag edit (and the two-stop minimum) addresses these, not the + // pending preview, which may already leave the dragged stop out. + let Fill::Gradient { stops, opacity_stops, .. } = f else { return None }; + let opacity_count = if opacity_stops.is_empty() { 2 } else { opacity_stops.len() }; let t = Tokens::get(ui.ctx()); let w = ui.available_width().max(120.0); let (outer, resp) = ui.allocate_exact_size(vec2(w, 58.0), Sense::click_and_drag()); @@ -1015,14 +1018,15 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi let edit = match m { Marker::Color(i) if off && stops.len() > 2 => json!({"action": "delete", "index": i}), Marker::Color(i) => json!({"action": "move", "index": i, "location": loc}), - Marker::Opacity(i) if off && ops.len() > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), + Marker::Opacity(i) if off && opacity_count > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), Marker::Opacity(i) => json!({"action": "move", "kind": "opacity", "index": i, "location": loc}), Marker::Mid(i) => { let (a, b) = (sorted.get(i).map_or(0.0, |s| s.0), sorted.get(i + 1).map_or(1.0, |s| s.0)); json!({"action": "midpoint", "index": i, "location": ((loc - a) / (b - a).max(1e-4)).clamp(0.05, 0.95)}) } }; - if resp.dragged() { + // The release frame counts too: its own last move decides whether the stop comes off. + if resp.dragged() || resp.drag_stopped() { preview = Some(edit); } } diff --git a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs index c761838f36..34636bd376 100644 --- a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs +++ b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs @@ -260,7 +260,7 @@ fn the_last_two_color_stops_cannot_be_dragged_off() { } } -/// An opacity stop dragged up off the bar is removed; dragging it down over the ramp is not. +/// An opacity stop dragged up off the bar is removed while two remain. #[test] fn an_opacity_stop_dragged_up_off_the_bar_is_removed() { for layer in [true, false] { @@ -277,3 +277,55 @@ fn an_opacity_stop_dragged_up_off_the_bar_is_removed() { assert_eq!(sink.fill(h.state()).unwrap(), before, "layer {layer}: two opacity stops always remain"); } } + +/// Only the stop's own direction takes it off: an opacity stop dragged down over the ramp and a +/// colour stop dragged up over it are kept, however far they go. +#[test] +fn a_stop_dragged_the_other_way_is_kept() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + for opacity in [true, false] { + let from = marker(&h, 0.5, opacity); + let to = from + vec2(0.0, if opacity { 70.0 } else { -70.0 }); + drag_through(&mut h, &[from, to], |h| assert_eq!(shown(h, sink), (3, 3), "layer {layer} opacity {opacity}: still shown")); + assert_eq!(counts(&h, sink), (3, 3), "layer {layer} opacity {opacity}: the stop is kept"); + } + } +} + +/// Press on a stop, drag a little along the bar, then move to each of `then` in its own frame; +/// the last move and the release arrive in the same frame, as a quick flick does. +fn flick(h: &mut Harness, from: Pos2, then: &[Pos2]) { + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + vec2(10.0, 0.0))); + h.run_steps(1); + let Some((&last, moves)) = then.split_last() else { return }; + for &p in moves { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + // `Harness::event` runs one frame per event, so both go straight into the next frame. + let input = &mut h.input_mut().events; + input.push(egui::Event::PointerMoved(last)); + input.push(egui::Event::PointerButton { pos: last, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +/// The release frame counts: a stop flicked off the bar and released in the same frame is +/// removed, and one brought back onto the bar in the release frame is kept. +#[test] +fn the_release_frame_decides_whether_the_stop_comes_off() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let from = marker(&h, 0.5, false); + let away = from + vec2(10.0, 40.0); + flick(&mut h, from, &[away, from]); + assert_eq!(counts(&h, sink), (3, 3), "layer {layer}: back on the bar at release, the stop is kept"); + let from = marker(&h, 0.5, false); + flick(&mut h, from, &[from + vec2(10.0, 40.0)]); + assert_eq!(counts(&h, sink), (2, 3), "layer {layer}: released off the bar in the same frame, the stop is removed"); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8bc4974646..abf9431ef4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -240,7 +240,7 @@ Paragraph; the rest open as in-app floating windows. | Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | The Type tool's Color Picker (Text Color) and a gradient fill's Color Picker (Stop Color) preview the picked colour on the canvas before OK (the selected characters, every selected type layer, or the stop); Cancel restores the document with no history step, OK commits the previewed edit in one step (#5530) | done: `dialogs/color_picker_preview.rs`, `dialogs/color_picker_preview/tests.rs` | | -| Gradient stops come off the bar: a colour stop dragged down, or an opacity stop dragged up, by about a marker's height is removed on release while two of its kind remain; while it is off the ramp and canvas preview show it gone, and dragging it back onto the bar cancels; the selected stop's Delete button does the same. Gradient Editor, Properties, the shape gradient popover, Gradient Map and Layer Style (Gradient Overlay) share one rule (#10742) | done: `tools/gradient_ui.rs` `stop_dragged_off`, `tools/gradient_ui/editor_tests.rs`, `adjust_editors/ui_tests.rs`, `layer_style/gradient_field.rs`. Differs: Gradient Map and Layer Style show colour stops only; no Delete-key shortcut for the selected stop | | +| Gradient stops come off the bar: a colour stop dragged down, or an opacity stop dragged up, by about a marker's height is removed on release while two of its kind remain; while it is off the ramp and canvas preview show it gone, and dragging it back onto the bar cancels; the selected stop's Delete button (Remove stop, the × beside the colour, in Gradient Map) does the same. Gradient Editor, Properties, the shape gradient popover, Gradient Map and Layer Style (Gradient Overlay) share one rule (#10742) | done: `tools/gradient_ui.rs` `stop_dragged_off`, `tools/gradient_ui/editor_tests.rs`, `adjust_editors/ui_tests.rs`, `layer_style/gradient_field.rs`. Differs: Gradient Map and Layer Style show colour stops only; no Delete-key shortcut for the selected stop | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | From b5770e42831371e19bcba700da923bdc49aa8d78 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:38:09 +0100 Subject: [PATCH 029/113] CLI: --metadata none|all for convert, run --out and batch (#9466) Since #733 a flat export from the CLI keeps the document's whole XMP packet and free-form text, as Save As does; only Export As starts at Metadata: None. Batch exports of Photoshop masters therefore carry the full DocumentAncestors list (and the text of every type layer), which can be many times larger than the image, with no way to leave it out. `--metadata` is a new export option shared by `convert`, `run --out` and `batch`. `none` sets ExportOptions::xmp to XmpEmbed::None, the same path Export As's Metadata: None and Quick Export use, so the XMP packet and free-form text are dropped while the ICC profile, EXIF and resolution are written as before; PSD, PSB and .pcraft keep the XMP either way. `all` is the default, so existing scripts write the same files. Any other value is a usage error (exit 2) naming the flag, before anything is read or written. Tested through the binary for PNG, WebP, JPEG and TIFF from all three subcommands (packet present by default and with `all`, absent with `none`; pixels, ICC and resolution unchanged), layered saves, and bad values. Documented in the CLI book page and file-format parity doc. --- apps/photocraft-cli/src/args.rs | 18 ++++++- apps/photocraft-cli/src/output.rs | 4 ++ apps/photocraft-cli/tests/it/cli.rs | 73 +++++++++++++++++++++++++++++ book/src/automation/cli.md | 16 +++++++ docs/file-format-parity.md | 9 ++-- 5 files changed, 115 insertions(+), 5 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 33175a15be..a5de7bbc68 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -16,7 +16,7 @@ use clap::parser::ValueSource; use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand}; use photocraft_automation::args::{AutomationArgs, ControlArgs, blank_env_is_unset, conflict, control_port, name_env_vars}; use photocraft_codecs::{JpegFormat, TiffCompression}; -use photocraft_io::{DdsCompression, DpxBits, TgaBits}; +use photocraft_io::{DdsCompression, DpxBits, TgaBits, XmpEmbed}; use serde_json::Value; /// photocraft-cli: headless PhotoCraft @@ -78,6 +78,12 @@ pub(crate) struct ExportArgs { /// composite/full.png; it may be omitted. Check the manifest's full_composite member. #[arg(long)] pub(crate) pcraft_full_composite: bool, + /// The document metadata a flat export embeds: all (the default) keeps the document's XMP + /// packet and free-form text, as Save As does; none leaves them out, as Export As's Metadata: + /// None. The ICC profile, EXIF and resolution are kept either way, and PSD, PSB and .pcraft + /// always keep the XMP + #[arg(long, value_name = "none|all", value_parser = metadata)] + pub(crate) metadata: Option, } /// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …) @@ -268,6 +274,8 @@ enum ValueError { TiffCompression, #[error("expected baseline, optimized or progressive")] JpegFormat, + #[error("expected none or all")] + Metadata, /// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused. #[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:)")] Bridge, @@ -326,6 +334,14 @@ fn jpeg_format(s: &str) -> Result { JpegFormat::parse(s).ok_or(ValueError::JpegFormat) } +fn metadata(s: &str) -> Result { + match s { + "none" => Ok(XmpEmbed::None), + "all" => Ok(XmpEmbed::All), + _ => Err(ValueError::Metadata), + } +} + /// Where `mcp --bridge` connects. Shown as the address: `127.0.0.1:` for a port. #[derive(Clone)] pub(crate) enum Bridge { diff --git a/apps/photocraft-cli/src/output.rs b/apps/photocraft-cli/src/output.rs index 831258b315..f296469655 100644 --- a/apps/photocraft-cli/src/output.rs +++ b/apps/photocraft-cli/src/output.rs @@ -26,6 +26,10 @@ impl From<&ExportArgs> for ExportOptions { o.encode.dds.compression = c; } o.encode.dds.mipmaps = a.dds_mipmaps; + // Conversions keep the whole packet unless asked, as Save As does (#733, #9466). + if let Some(m) = a.metadata { + o.xmp = m; + } o } } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 176fb970fd..caad46edc1 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -758,6 +758,79 @@ fn jpeg_format_chooses_the_scans() { } } +/// #9466: `--metadata none` leaves the document's XMP packet out of a flat export from `convert`, +/// `run --out` and `batch`, as Export As's Metadata: None does, and changes nothing else (pixels, +/// ICC profile, resolution). The default, and `all`, keep it as before, and a PSD or `.pcraft` +/// keeps it either way. A value it doesn't name is a usage error and nothing is written. +#[test] +fn metadata_none_leaves_out_the_document_xmp() { + const XMP: &str = "\ +\ +xmp.did:11111111-2222-3333-4444-555555555555\ +"; + let d = tmp("metadata"); + let input = d.join("in"); + std::fs::create_dir_all(&input).unwrap(); + let a = input.join("a.png"); + let data: Vec = (0..8 * 6 * 4).map(|i| (i as u8).wrapping_mul(7).wrapping_add(3)).collect(); + let mut img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgba, data).unwrap(); + img.meta.xmp = Some(XMP.into()); + img.meta.dpi = Some((300.0, 300.0)); + std::fs::write(&a, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + let ancestors = |p: &Path| String::from_utf8_lossy(&std::fs::read(p).unwrap()).contains("DocumentAncestors"); + let decoded = |p: &Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap(); + assert!(ancestors(&a), "the input carries the packet"); + let invert = r#"[{"command":"image.adjustments.invert"}]"#; + for ext in ["png", "webp", "jpg", "tif"] { + let mut converted_files = Vec::new(); + for flag in [None, Some("all"), Some("none")] { + let extra: Vec<&str> = flag.map(|f| vec!["--metadata", f]).unwrap_or_default(); + let name = format!("{ext}-{}", flag.unwrap_or("default")); + let converted = d.join(format!("convert-{name}.{ext}")); + ok(bin().arg("convert").arg(&a).arg(&converted).args(&extra)); + let ran = d.join(format!("run-{name}.{ext}")); + ok(bin().arg("run").arg(&a).arg("--out").arg(&ran).args(&extra)); + let o = batch_with(&d, &input, &format!("batch-{name}"), invert, &[&["--format", ext][..], &extra[..]].concat()); + assert!(o.status.success(), "batch {name}: {}", String::from_utf8_lossy(&o.stderr)); + let batched = d.join(format!("batch-{name}")).join(format!("a.{ext}")); + for out in [&converted, &ran, &batched] { + assert_eq!(ancestors(out), flag != Some("none"), "{name}: {}", out.display()); + } + converted_files.push(converted); + } + // Only the XMP goes: the pixels, profile and resolution are the default export's. + let (default, none) = (decoded(&converted_files[0]), decoded(&converted_files[2])); + assert_eq!(none.data(), default.data(), "{ext}: pixels"); + assert_eq!(none.icc, default.icc, "{ext}: ICC profile"); + assert_eq!(none.meta.dpi, default.meta.dpi, "{ext}: resolution"); + assert!(none.meta.dpi.is_some_and(|(x, y)| (x - 300.0).abs() < 0.5 && (y - 300.0).abs() < 0.5), "{ext}: {:?}", none.meta.dpi); + } + // A layered save keeps the document's XMP whatever the option. + for ext in ["psd", "pcraft"] { + let out = d.join(format!("layered.{ext}")); + ok(bin().arg("convert").arg(&a).arg(&out).args(["--metadata", "none"])); + let back = d.join(format!("layered-{ext}.png")); + ok(bin().arg("convert").arg(&out).arg(&back)); + assert!(ancestors(&back), "{ext} kept the packet"); + } + for bad in ["None", "exif", "0", ""] { + let out = d.join("bad.png"); + let (mut convert, mut run) = (bin(), bin()); + convert.arg("convert").arg(&a).arg(&out).args(["--metadata", bad]); + run.arg("run").arg(&a).arg("--out").arg(&out).args(["--metadata", bad]); + for cmd in [&mut convert, &mut run] { + let o = cmd.output().unwrap(); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!(o.status.code(), Some(2), "--metadata {bad}: {err}"); + assert!(err.contains("--metadata") && err.contains("expected none or all"), "--metadata {bad}: {err}"); + assert!(!out.exists(), "--metadata {bad} wrote a file"); + } + let o = batch_with(&d, &input, "bad-batch", invert, &["--metadata", bad]); + assert_eq!(o.status.code(), Some(2), "batch --metadata {bad}"); + assert!(!d.join("bad-batch").exists(), "batch --metadata {bad} wrote a folder"); + } +} + /// #492: an `--out` folder that is the `--in` folder, however it is spelt, is refused before /// anything is written, unless `--in-place` asks for it. #[test] diff --git a/book/src/automation/cli.md b/book/src/automation/cli.md index 6137b12466..2f8c3628d7 100644 --- a/book/src/automation/cli.md +++ b/book/src/automation/cli.md @@ -35,6 +35,22 @@ Warnings do not change the saved document's font declarations and do not stop the operation. To list or replace the missing families intentionally, use `type.resolveMissingFonts` on the document. +### Document metadata + +`convert`, `run --out` and `batch` keep the document's XMP packet and +free-form text in a flat export (PNG, JPEG, WebP, TIFF, …), as Save As does. +`--metadata none` leaves them out, as Export As's Metadata: None does: a +Photoshop file's XMP can list every placed document's id +(`DocumentAncestors`) and the text of every type layer, and can be far larger +than the image. `--metadata all` is the default. The option changes nothing +else: the ICC profile, EXIF and resolution are written either way, and PSD, +PSB and `.pcraft` saves always keep the XMP. It is not a full metadata scrub. + +```sh +photocraft-cli batch --actions resize.json --in masters/ --out web/ \ + --format webp --metadata none +``` + ### Export selected adjustment layers as a .cube LUT The engine command `file.export.colorLookupTables` creates a 3D LUT from an diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a0821f154e..c586cb0b60 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-31 · **Change:** minor (`.atn`: 144 supported events after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-03 · **Change:** minor (CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; `.atn`: 144 supported events after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -27,11 +27,11 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | 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/it/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, YCbCr read as RGB (JPEG-compressed with subsampled chroma, or uncompressed without subsampling; #10316), BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); no Save Transparency choice yet (channels are written as Photoshop does with it off) | -| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); File › Save, Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte, progressive Scans (3–5) or size preview | -| PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) | +| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP (the CLI's `--metadata none` leaves the document XMP out, #9466); Save keeps the opened file's quality (estimated from its quantisation tables, #2399); File › Save, Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte, progressive Scans (3–5) or size preview | +| PNG | R/W | yes | yes | 8/16-bit, ICC/text (the CLI's `--metadata none` leaves the document XMP and text out, #9466); APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) | | GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done | | BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode and Indexed Color documents save as palette BMPs (no transparency) | -| WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP; Save keeps an opened file lossy (at its quality) or lossless (#2399); Save for Web (Legacy) writes it too, lossy at its Quality or lossless, a format Photoshop's legacy dialog lacks (#6391). File › Open keeps an animation's first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the durations (#1198) | +| WebP | R/W | yes | yes | Lossless and our own lossy VP8 encoder; ICC/EXIF/XMP (the CLI's `--metadata none` leaves the document XMP out, #9466); Save keeps an opened file lossy (at its quality) or lossless (#2399); Save for Web (Legacy) writes it too, lossy at its Quality or lossless, a format Photoshop's legacy dialog lacks (#6391). File › Open keeps an animation's first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the durations (#1198) | | AVIF | R/W | no (#463) | optional feature, off by default | | | JPEG XL | R/W | inside DNG only | no | | | HEIF/HEIC | R/W(HEIF) | yes (pure-Rust heic-rs, `heif` feature, on in releases) | no | 8/16-bit | @@ -151,6 +151,7 @@ The original reference entry retains its source date and historical totals; curr | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | CLI `--metadata` (`none` or `all`) for `convert`, `run --out` and `batch`: `none` leaves the document's XMP packet and free-form text out of flat exports (PNG, JPEG, WebP, TIFF, …) through Export As's Metadata: None path; `all`, which keeps them as Save As does, stays the default. ICC, EXIF and resolution are written either way; PSD, PSB and `.pcraft` always keep the XMP (#9466) | | 2026-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 117 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet | | 2026-10-31 | minor | `.atn` Group B: four Render events load, play and save; 120 supported and 97 unmapped. Supported-table columns corrected against the event registry; the original 117/101 reference entry remains historical. | | 2026-10-31 | minor | `.atn`: Pinch (`Pnch`), Polar Coordinates (`Plr `), Spherize (`Sphr`), Twirl (`Twrl`), Wave (`Wave`) and ZigZag (`ZgZg`) map to `filter.distort.*` with every key in recorded order; out-of-range values clamped and missing keys given Photoshop's defaults on import; a Wave scaled below 100 % stays a Photoshop step (the command has no scale); Shear still kept verbatim (#10605) | From a99e8696fc720e2dd8050163d36cbf076fc83eba Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:59:20 +0100 Subject: [PATCH 030/113] CLI --metadata: qualify the docs per format, test text and ICC (#9466) Review follow-up on #9975. The help text and the CLI book page said the XMP and free-form text are kept in every flat export and the ICC profile, EXIF and resolution "either way". Not every format holds them: JPEG and WebP have no place for free-form text, TIFF writes only its named text tags, and an Indexed Color document's palette PNG carries no XMP, text, ICC or EXIF at all, only its resolution. The texts (and the parity-doc revision row) now say the XMP and text are kept where the format holds them and that the option leaves everything else as it is without it. The test fixture gains a free-form text entry and a Display P3 profile (from photocraft-cms, now a dev-dependency; no profile file committed), so it checks the text is gone with `none` and kept by a default PNG, and that the default export keeps a real ICC profile that `none` matches, instead of comparing None with None. --- Cargo.lock | 1 + apps/photocraft-cli/Cargo.toml | 2 ++ apps/photocraft-cli/src/args.rs | 6 +++--- apps/photocraft-cli/tests/it/cli.rs | 20 ++++++++++++++------ book/src/automation/cli.md | 17 +++++++++++------ docs/file-format-parity.md | 2 +- 6 files changed, 32 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab0417b79b..0fab1b2a97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5102,6 +5102,7 @@ dependencies = [ "clap_complete", "clap_mangen", "photocraft-automation", + "photocraft-cms", "photocraft-codecs", "photocraft-engine", "photocraft-format", diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index 94e04b518a..19ef8bfa92 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -34,6 +34,8 @@ thiserror = { workspace = true } tokio = { version = "1", features = ["rt-multi-thread", "macros"] } [dev-dependencies] +# A real ICC profile for the --metadata test (#9466). +photocraft-cms = { workspace = true } # Synthetic camera raws (#7789). photocraft-raw = { workspace = true, features = ["testgen"] } # Shell completions and man pages (examples/man-and-completions.rs, for the packages); not in diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index a5de7bbc68..4ba08fbaae 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -79,9 +79,9 @@ pub(crate) struct ExportArgs { #[arg(long)] pub(crate) pcraft_full_composite: bool, /// The document metadata a flat export embeds: all (the default) keeps the document's XMP - /// packet and free-form text, as Save As does; none leaves them out, as Export As's Metadata: - /// None. The ICC profile, EXIF and resolution are kept either way, and PSD, PSB and .pcraft - /// always keep the XMP + /// packet and free-form text where the format holds them, as Save As does; none leaves them + /// out, as Export As's Metadata: None. Nothing else changes: the ICC profile, EXIF and + /// resolution are written as they are without it. PSD, PSB and .pcraft always keep the XMP #[arg(long, value_name = "none|all", value_parser = metadata)] pub(crate) metadata: Option, } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index caad46edc1..cffeed0644 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -758,10 +758,11 @@ fn jpeg_format_chooses_the_scans() { } } -/// #9466: `--metadata none` leaves the document's XMP packet out of a flat export from `convert`, -/// `run --out` and `batch`, as Export As's Metadata: None does, and changes nothing else (pixels, -/// ICC profile, resolution). The default, and `all`, keep it as before, and a PSD or `.pcraft` -/// keeps it either way. A value it doesn't name is a usage error and nothing is written. +/// #9466: `--metadata none` leaves the document's XMP packet and free-form text out of a flat +/// export from `convert`, `run --out` and `batch`, as Export As's Metadata: None does, and changes +/// nothing else (pixels, ICC profile, resolution). The default, and `all`, keep them as before (the +/// text where the format holds it, as PNG does), and a PSD or `.pcraft` keeps the XMP either way. +/// A value it doesn't name is a usage error and nothing is written. #[test] fn metadata_none_leaves_out_the_document_xmp() { const XMP: &str = "\ @@ -776,10 +777,14 @@ fn metadata_none_leaves_out_the_document_xmp() { let mut img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgba, data).unwrap(); img.meta.xmp = Some(XMP.into()); img.meta.dpi = Some((300.0, 300.0)); + img.meta.text = vec![("Comment".into(), "free-form-note".into())]; + // Display P3 rather than sRGB, so no export can pass for keeping it by writing its default. + img.icc = Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes().to_vec()); std::fs::write(&a, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); let ancestors = |p: &Path| String::from_utf8_lossy(&std::fs::read(p).unwrap()).contains("DocumentAncestors"); let decoded = |p: &Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap(); - assert!(ancestors(&a), "the input carries the packet"); + let note = |p: &Path| decoded(p).meta.text.iter().any(|(_, v)| v == "free-form-note"); + assert!(ancestors(&a) && note(&a), "the input carries the packet and the text"); let invert = r#"[{"command":"image.adjustments.invert"}]"#; for ext in ["png", "webp", "jpg", "tif"] { let mut converted_files = Vec::new(); @@ -795,12 +800,15 @@ fn metadata_none_leaves_out_the_document_xmp() { let batched = d.join(format!("batch-{name}")).join(format!("a.{ext}")); for out in [&converted, &ran, &batched] { assert_eq!(ancestors(out), flag != Some("none"), "{name}: {}", out.display()); + // PNG holds free-form text; JPEG, WebP and TIFF (but for its named tags) don't. + assert_eq!(note(out), ext == "png" && flag != Some("none"), "{name} text: {}", out.display()); } converted_files.push(converted); } - // Only the XMP goes: the pixels, profile and resolution are the default export's. + // Only the XMP and text go: the pixels, profile and resolution are the default export's. let (default, none) = (decoded(&converted_files[0]), decoded(&converted_files[2])); assert_eq!(none.data(), default.data(), "{ext}: pixels"); + assert!(default.icc.is_some(), "{ext}: the default export keeps the ICC profile"); assert_eq!(none.icc, default.icc, "{ext}: ICC profile"); assert_eq!(none.meta.dpi, default.meta.dpi, "{ext}: resolution"); assert!(none.meta.dpi.is_some_and(|(x, y)| (x - 300.0).abs() < 0.5 && (y - 300.0).abs() < 0.5), "{ext}: {:?}", none.meta.dpi); diff --git a/book/src/automation/cli.md b/book/src/automation/cli.md index 2f8c3628d7..c7278455ef 100644 --- a/book/src/automation/cli.md +++ b/book/src/automation/cli.md @@ -37,14 +37,19 @@ the operation. To list or replace the missing families intentionally, use ### Document metadata -`convert`, `run --out` and `batch` keep the document's XMP packet and -free-form text in a flat export (PNG, JPEG, WebP, TIFF, …), as Save As does. -`--metadata none` leaves them out, as Export As's Metadata: None does: a -Photoshop file's XMP can list every placed document's id +`convert`, `run --out` and `batch` keep the document's XMP packet in a flat +export whose format holds one (PNG, JPEG, WebP, TIFF, …), and its free-form +text where the format holds that too (PNG text chunks, TIFF's named text tags +such as ImageDescription; JPEG and WebP have no place for it), as Save As +does. `--metadata none` leaves them out, as Export As's Metadata: None does: +a Photoshop file's XMP can list every placed document's id (`DocumentAncestors`) and the text of every type layer, and can be far larger than the image. `--metadata all` is the default. The option changes nothing -else: the ICC profile, EXIF and resolution are written either way, and PSD, -PSB and `.pcraft` saves always keep the XMP. It is not a full metadata scrub. +else: the ICC profile, EXIF and resolution are written as they are without +it, where the format holds them. An Indexed Color document saved as a palette +PNG carries no XMP, text, ICC profile or EXIF with either value, only its +resolution. PSD, PSB and `.pcraft` saves always keep the XMP. It is not a full +metadata scrub. ```sh photocraft-cli batch --actions resize.json --in masters/ --out web/ \ diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c586cb0b60..3fcbc6eb84 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -151,7 +151,7 @@ The original reference entry retains its source date and historical totals; curr | Date | Change | Summary | |---|---|---| -| 2026-11-03 | minor | CLI `--metadata` (`none` or `all`) for `convert`, `run --out` and `batch`: `none` leaves the document's XMP packet and free-form text out of flat exports (PNG, JPEG, WebP, TIFF, …) through Export As's Metadata: None path; `all`, which keeps them as Save As does, stays the default. ICC, EXIF and resolution are written either way; PSD, PSB and `.pcraft` always keep the XMP (#9466) | +| 2026-11-03 | minor | CLI `--metadata` (`none` or `all`) for `convert`, `run --out` and `batch`: `none` leaves the document's XMP packet and free-form text out of flat exports (PNG, JPEG, WebP, TIFF, …) through Export As's Metadata: None path; `all`, which keeps them as Save As does, stays the default. The ICC profile, EXIF and resolution are written as they are without the option (a palette PNG carries only its resolution, either way); PSD, PSB and `.pcraft` always keep the XMP (#9466) | | 2026-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 117 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet | | 2026-10-31 | minor | `.atn` Group B: four Render events load, play and save; 120 supported and 97 unmapped. Supported-table columns corrected against the event registry; the original 117/101 reference entry remains historical. | | 2026-10-31 | minor | `.atn`: Pinch (`Pnch`), Polar Coordinates (`Plr `), Spherize (`Sphr`), Twirl (`Twrl`), Wave (`Wave`) and ZigZag (`ZgZg`) map to `filter.distort.*` with every key in recorded order; out-of-range values clamped and missing keys given Photoshop's defaults on import; a Wave scaled below 100 % stays a Photoshop step (the command has no scale); Shear still kept verbatim (#10605) | From a112beda7e4f11f9e936fd30bbc8ac9f472ecfe1 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Wed, 28 Oct 2026 19:09:08 +0100 Subject: [PATCH 031/113] CLI --metadata test: the export keeps the input's own ICC profile Review nitpick (#9466): the test only checked that the default export had some ICC profile and that `none` matched it, so a regression writing sRGB instead of the input's Display P3 would still pass. It now compares the default export's profile with the input's bytes. --- apps/photocraft-cli/tests/it/cli.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index cffeed0644..f830c25dc7 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -779,7 +779,8 @@ fn metadata_none_leaves_out_the_document_xmp() { img.meta.dpi = Some((300.0, 300.0)); img.meta.text = vec![("Comment".into(), "free-form-note".into())]; // Display P3 rather than sRGB, so no export can pass for keeping it by writing its default. - img.icc = Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes().to_vec()); + let p3 = photocraft_cms::Builtin::DisplayP3.profile().to_bytes().to_vec(); + img.icc = Some(p3.clone()); std::fs::write(&a, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); let ancestors = |p: &Path| String::from_utf8_lossy(&std::fs::read(p).unwrap()).contains("DocumentAncestors"); let decoded = |p: &Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap(); @@ -808,7 +809,7 @@ fn metadata_none_leaves_out_the_document_xmp() { // Only the XMP and text go: the pixels, profile and resolution are the default export's. let (default, none) = (decoded(&converted_files[0]), decoded(&converted_files[2])); assert_eq!(none.data(), default.data(), "{ext}: pixels"); - assert!(default.icc.is_some(), "{ext}: the default export keeps the ICC profile"); + assert_eq!(default.icc.as_deref(), Some(&p3[..]), "{ext}: the default export keeps the input's Display P3 profile"); assert_eq!(none.icc, default.icc, "{ext}: ICC profile"); assert_eq!(none.meta.dpi, default.meta.dpi, "{ext}: resolution"); assert!(none.meta.dpi.is_some_and(|(x, y)| (x - 300.0).abs() < 0.5 && (y - 300.0).abs() < 0.5), "{ext}: {:?}", none.meta.dpi); From d630efdce27ec7170dc842438f013452d5fb8df7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 19:22:40 -0800 Subject: [PATCH 032/113] Use whole-edge transform handles and consistent rotate cursors --- .../ui-egui/src/canvas/transform_controls.rs | 62 +++--- .../ui-egui/src/tools/transform_tool/draw.rs | 14 +- .../src/tools/transform_tool/pointer.rs | 120 +++++++---- .../ui-egui/src/transform_hit_zone_tests.rs | 186 ++++++++++++++++++ 4 files changed, 304 insertions(+), 78 deletions(-) create mode 100644 crates/ui-egui/src/transform_hit_zone_tests.rs diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs index 7e00fd8cb3..d0ad6ee752 100644 --- a/crates/ui-egui/src/canvas/transform_controls.rs +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -58,50 +58,40 @@ pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Op Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32))) } -/// The Move tool shows transform handles even before a Free Transform session exists. -/// Use the same hit areas for pointer-down and hover, so a control never behaves like -/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871). +fn controls_quad(r: Rect) -> [[f64; 2]; 4] { + [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| [f64::from(p.x), f64::from(p.y)]) +} + +fn controls_zone(r: Rect, p: Pos2) -> crate::transform_tool::Hit { + crate::state::TransformSession::box_hit(&controls_quad(r), [f64::from(p.x), f64::from(p.y)], crate::transform_tool::HANDLE_PX) +} + +/// Share the open session's screen-sized zones before the first interaction (#11097). pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option { - let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]; - let grab = crate::transform_tool::HANDLE_PX as f32; - for (i, handle) in handles.into_iter().enumerate() { - if handle.distance(p) <= grab { - return Some(match i { - 0 | 4 => egui::CursorIcon::ResizeNwSe, - 2 | 6 => egui::CursorIcon::ResizeNeSw, - 1 | 5 => egui::CursorIcon::ResizeVertical, - _ => egui::CursorIcon::ResizeHorizontal, - }); - } - } - // The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`). - in_rotation_band(r, p).then_some(egui::CursorIcon::None) + use crate::transform_tool::Hit; + Some(match controls_zone(r, p) { + Hit::Corner(0 | 2) => egui::CursorIcon::ResizeNwSe, + Hit::Corner(_) => egui::CursorIcon::ResizeNeSw, + Hit::Edge(0 | 2) => egui::CursorIcon::ResizeVertical, + Hit::Edge(_) => egui::CursorIcon::ResizeHorizontal, + Hit::Outside => egui::CursorIcon::None, + Hit::Inside | Hit::Pivot => egui::CursorIcon::Default, + }) } -fn in_rotation_band(r: Rect, p: Pos2) -> bool { - r.expand(18.0).contains(p) && !r.expand(5.0).contains(p) -} - -/// In the rotation band just outside the Move tool's transform controls, the screen direction the -/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free -/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a -/// drag there rotates. +/// At any distance outside the controls, the same edge/corner direction as Free Transform. pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option { - if !in_rotation_band(r, p) - || [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] - .into_iter() - .any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32) - { + if controls_zone(r, p) != crate::transform_tool::Hit::Outside { return None; } - let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() }); - Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0) + let k = crate::state::TransformSession::box_turn_direction(&controls_quad(r), [f64::from(p.x), f64::from(p.y)])?; + Some(vec2(k[0] as f32, k[1] as f32) * 16.0) } -/// A visible handle starts scaling; the narrow band just outside the box starts rotation. +/// A visible handle starts scaling; any point outside the box starts rotation. /// The interior stays the normal Move-tool drag target. pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool { - transform_controls_cursor(r, p).is_some() + !matches!(controls_zone(r, p), crate::transform_tool::Hit::Inside | crate::transform_tool::Hit::Pivot) } /// Enter the existing Free Transform session when a Move-tool transform control is pressed: on @@ -138,3 +128,7 @@ pub(super) fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::P painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); } } + +#[cfg(test)] +#[path = "../transform_hit_zone_tests.rs"] +mod hit_zone_tests; diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 26807afed6..21c14cb86f 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -1,11 +1,11 @@ use super::begin::warps_type; use super::drag_modes::{HandleIndicator, handle_indicator}; use super::options_bar::{quad_scale, readout}; -use super::pointer::{Hit, handle_at, rotate_dir, rotation_degrees}; +use super::pointer::{Hit, handle_at, rotation_degrees}; use super::warp::{on_section_edge, quick_split_kind, single_patch}; use super::{ - BezierMesh, Color32, DocId, HANDLE_PX, Homography, LayerId, PhotocraftApp, Pos2, SplitTool, Stroke, TransformPreview, TransformSession, ViewXform, Warp, - WarpDrag, WarpStyle, corners, pos2, vec2, + BezierMesh, Color32, DocId, Homography, LayerId, PhotocraftApp, Pos2, SplitTool, Stroke, TransformPreview, TransformSession, ViewXform, Warp, WarpDrag, + WarpStyle, corners, pos2, vec2, }; /// The distort or skew pointer at screen point `at`, where [`super::cursor`] hid the system @@ -212,14 +212,6 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE)); if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) { - let p = xf.to_doc(at); - let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01)); - if let Some(k) = rotate_dir(t, Some(pv), p, tol) { - // Through the view, so the arc bends round the corner as it shows under a turned or - // flipped view. - let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; - crate::crop_ui::draw_turn_cursor(painter.ctx(), at, toward); - } // Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204). if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) { draw_live_readout(app, painter.ctx(), at, r); diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index dd76e446c9..6f9186164a 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -17,21 +17,91 @@ pub(crate) enum Hit { Outside, } -/// The nearest handle within `tol` (on a small box their grab areas overlap), else inside or -/// outside the box. +/// Screen-sized corner and outward edge bands, shared with Move's unopened controls. +impl TransformSession { + pub(crate) fn box_hit(quad: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> Hit { + // `tol` is the existing 12 pt handle tolerance, divided by the view zoom. + let corner_radius = tol * (8.0 / HANDLE_PX); + let edge_width = tol * (11.0 / HANDLE_PX); + let distance = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); + if let Some((i, _)) = quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) { + return Hit::Corner(i); + } + let interior = inside(quad, p); + let edge = (0..4) + .filter_map(|i| { + let (_, q) = edge_projection(quad, i, p)?; + let d = distance(q); + // One pixel inside is interior, not a scale handle. The line itself is a handle. + (d <= edge_width && (!interior || d <= tol.abs() * 1e-9)).then_some((i, d)) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)); + match edge { + Some((i, _)) => Hit::Edge(i), + None if interior => Hit::Inside, + None => Hit::Outside, + } + } + + /// Into the nearest edge or corner: eight orientations for an upright rectangle, following + /// the actual quad when it is rotated, flipped or distorted. + pub(crate) fn box_turn_direction(quad: &[[f64; 2]; 4], p: [f64; 2]) -> Option<[f64; 2]> { + if p.iter().chain(quad.iter().flatten()).any(|v| !v.is_finite()) { + return None; + } + let (i, u, _) = (0..4) + .filter_map(|i| { + let (u, q) = edge_projection(quad, i, p)?; + Some((i, u, (p[0] - q[0]).hypot(p[1] - q[1]))) + }) + .min_by(|a, b| a.2.total_cmp(&b.2))?; + let unit = |v: [f64; 2]| { + let len = v[0].hypot(v[1]); + (len.is_finite() && len > 1e-9).then(|| [v[0] / len, v[1] / len]) + }; + let toward = if u <= 0.0 || u >= 1.0 { + let i = if u >= 1.0 { (i + 1) % 4 } else { i }; + let direction = |j: usize| unit([quad[j][0] - quad[i][0], quad[j][1] - quad[i][1]]); + let (a, b) = (direction((i + 1) % 4)?, direction((i + 3) % 4)?); + [a[0] + b[0], a[1] + b[1]] + } else { + let (a, b) = (quad[i], quad[(i + 1) % 4]); + let normal = [a[1] - b[1], b[0] - a[0]]; + let center = quad.iter().fold([0.0; 2], |c, q| [c[0] + q[0] / 4.0, c[1] + q[1] / 4.0]); + let sign = (normal[0] * (center[0] - a[0]) + normal[1] * (center[1] - a[1])).signum(); + normal.map(|v| v * sign) + }; + unit(toward) + } +} + +/// The nearest point on an edge segment and its clamped parameter. Degenerate edges have no +/// band or normal; the other edges and corner handles remain usable. +fn edge_projection(quad: &[[f64; 2]; 4], i: usize, p: [f64; 2]) -> Option<(f64, [f64; 2])> { + let (a, b) = (quad[i], quad[(i + 1) % 4]); + let d = [b[0] - a[0], b[1] - a[1]]; + let len2 = d[0] * d[0] + d[1] * d[1]; + if !len2.is_finite() || len2 <= 1e-18 { + return None; + } + let u = (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / len2).clamp(0.0, 1.0); + Some((u, [a[0] + u * d[0], a[1] + u * d[1]])) +} + +/// The shared box zones, retaining the nearest pivot's existing grab priority on small boxes. pub(crate) fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { let d = |a: [f64; 2]| ((a[0] - p[0]).powi(2) + (a[1] - p[1]).powi(2)).sqrt(); let mid = |i: usize| { let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]); [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0] }; - let handles = (0..4).map(|i| (t.quad[i], Hit::Corner(i))).chain((0..4).map(|i| (mid(i), Hit::Edge(i)))).chain([(t.pivot, Hit::Pivot)]); - let nearest = handles.map(|(q, h)| (d(q), h)).filter(|(dist, _)| *dist < tol).min_by(|a, b| a.0.total_cmp(&b.0)); - match nearest { - Some((_, h)) => h, - None if inside(&t.quad, p) => Hit::Inside, - None => Hit::Outside, - } + let h = TransformSession::box_hit(&t.quad, p, tol); + let handle_distance = match h { + Hit::Corner(i) => d(t.quad[i]), + Hit::Edge(i) => d(mid(i)), + _ => f64::INFINITY, + }; + if d(t.pivot) < tol && d(t.pivot) < handle_distance { Hit::Pivot } else { h } } fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { @@ -208,16 +278,12 @@ pub(super) fn carry_pivot(quad0: [[f64; 2]; 4], quad: [[f64; 2]; 4], pivot0: [f6 if x.is_finite() && y.is_finite() { [x, y] } else { pivot0 } } -/// True just outside a corner: rotate handle feedback lives here, not over the entire -/// empty canvas. The actual rotation gesture continues to work farther away. +/// Rotate feedback covers every outside point where a rotation gesture can start. pub(super) fn near_rotate_corner(t: &TransformSession, p: [f64; 2], tol: f64) -> bool { - t.warp.is_none() - && t.mode != TransformMode::Distort - && { - let h = hit(t, p, tol); - h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_))) - } - && t.quad.iter().any(|q| (p[0] - q[0]).hypot(p[1] - q[1]) <= tol * 3.0) + t.warp.is_none() && t.mode != TransformMode::Distort && { + let h = hit(t, p, tol); + h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_))) + } } /// Clockwise degrees in canvas coordinates (positive Y points down). @@ -228,8 +294,7 @@ pub(super) fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 { } /// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone: -/// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the -/// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box. +/// anywhere outside, or while a rotate drag is on. It follows the nearest edge or corner. pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) } @@ -251,17 +316,7 @@ pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: None if !near_rotate_corner(t, p, tol) => return None, None => {} } - let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); - let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?; - let unit = |to: [f64; 2]| { - let d = [to[0] - t.quad[i][0], to[1] - t.quad[i][1]]; - let l = d[0].hypot(d[1]); - (l.is_finite() && l > 1e-9).then(|| [d[0] / l, d[1] / l]) - }; - let (a, b) = (unit(t.quad[(i + 1) % 4])?, unit(t.quad[(i + 3) % 4])?); - let s = [a[0] + b[0], a[1] + b[1]]; - let l = s[0].hypot(s[1]); - (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) + TransformSession::box_turn_direction(&t.quad, p) } /// The handle a drag in progress holds, else the one under document point `p`. @@ -317,7 +372,6 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf), Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)), Hit::Pivot => CursorIcon::Crosshair, - Hit::Inside => CursorIcon::Move, - Hit::Outside => CursorIcon::Alias, + Hit::Inside | Hit::Outside => CursorIcon::Default, }) } diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs new file mode 100644 index 0000000000..a388f6c909 --- /dev/null +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -0,0 +1,186 @@ +use super::*; +use crate::state::{ContentAwareOptions, TransformMode, TransformSession}; +use crate::transform_tool::{Hit, cursor, hit, rotate_cursor_dir}; +use egui::{CursorIcon, Modifiers}; + +const QUAD: [[f64; 2]; 4] = [[100.0, 100.0], [500.0, 100.0], [500.0, 300.0], [100.0, 300.0]]; + +fn session(quad: [[f64; 2]; 4]) -> TransformSession { + TransformSession { + session: 1, + layer: 1, + rect: [100.0, 100.0, 500.0, 300.0], + quad, + pivot: quad.iter().fold([0.0; 2], |c, p| [c[0] + p[0] / 4.0, c[1] + p[1] / 4.0]), + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: TransformMode::Free, + content_aware: None, + skew_v: 0.0, + layers: Vec::new(), + } +} + +fn app(quad: [[f64; 2]; 4], zoom: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ui.transform = Some(session(quad)); + app +} + +fn view(zoom: f32) -> ViewXform { + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 800.0)), zoom, center: [300.0, 200.0], flip: false, rotation: 0.0, aspect: 1.0 } +} + +fn near(actual: Option<[f64; 2]>, expected: [f64; 2]) { + let actual = actual.expect("rotate direction"); + assert!((actual[0] - expected[0]).hypot(actual[1] - expected[1]) < 1e-6, "{actual:?} != {expected:?}"); +} + +#[test] +fn whole_edge_and_corner_priority_table_at_100_and_200_percent() { + for zoom in [1.0, 2.0] { + let q = QUAD.map(|p| p.map(|v| v / zoom)); + let t = session(q); + // Coordinates are screen pixels, so the same table must hold at both document zooms. + for (p, expected) in [ + ([100.0, 100.0], Hit::Corner(0)), + ([105.0, 105.0], Hit::Corner(0)), + ([95.0, 95.0], Hit::Corner(0)), + ([500.0, 300.0], Hit::Corner(2)), + ([180.0, 100.0], Hit::Edge(0)), + ([180.0, 89.0], Hit::Edge(0)), + ([500.0, 150.0], Hit::Edge(1)), + ([511.0, 150.0], Hit::Edge(1)), + ([420.0, 311.0], Hit::Edge(2)), + ([89.0, 250.0], Hit::Edge(3)), + ([180.0, 101.0], Hit::Inside), + ([499.0, 150.0], Hit::Inside), + ([180.0, 180.0], Hit::Inside), + ([180.0, 88.0], Hit::Outside), + ([620.0, 200.0], Hit::Outside), + ] { + assert_eq!(hit(&t, p.map(|v| v / zoom), 12.0 / zoom), expected, "zoom {zoom}, screen {p:?}"); + } + let tiny = session([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]); + assert_eq!(TransformSession::box_hit(&tiny.quad, [5.0, -1.0], 12.0), Hit::Corner(0), "corners beat overlapping edge bands"); + } +} + +#[test] +fn turned_box_zones_and_resize_cursors_follow_the_quad() { + let turn = |p: [f64; 2]| { + let (x, y) = (p[0] - 300.0, p[1] - 200.0); + let k = std::f64::consts::FRAC_1_SQRT_2; + [300.0 + (x - y) * k, 200.0 + (x + y) * k] + }; + for zoom in [1.0_f32, 2.0] { + let scale = |p: [f64; 2]| turn(p).map(|v| v / f64::from(zoom)); + let q = QUAD.map(scale); + let app = app(q, zoom); + let xf = view(zoom); + let t = app.ui.transform.as_ref().unwrap(); + for (p, expected, icon) in [ + ([180.0, 95.0], Hit::Edge(0), CursorIcon::ResizeNeSw), + ([505.0, 150.0], Hit::Edge(1), CursorIcon::ResizeNwSe), + ([180.0, 101.0], Hit::Inside, CursorIcon::Default), + ([180.0, -20.0], Hit::Outside, CursorIcon::None), + ] { + assert_eq!(hit(t, scale(p), 12.0 / f64::from(zoom)), expected); + assert_eq!(cursor(&app, &xf, scale(p), Modifiers::NONE), Some(icon), "zoom {zoom}, {p:?}"); + } + assert_eq!(hit(t, scale([100.0, 100.0]), 12.0 / f64::from(zoom)), Hit::Corner(0)); + } +} + +#[test] +fn distorted_and_flipped_quads_use_their_edges_not_an_axis_aligned_box() { + let q = [[100.0, 100.0], [500.0, 140.0], [460.0, 300.0], [80.0, 260.0]]; + for q in [q, [q[1], q[0], q[3], q[2]]] { + let t = session(q); + assert_eq!(hit(&t, [220.0, 112.0], 12.0), Hit::Edge(0)); + assert_eq!(hit(&t, [220.0, 107.0], 12.0), Hit::Edge(0)); + assert_eq!(hit(&t, [220.0, 113.0], 12.0), Hit::Inside); + assert_eq!(hit(&t, [220.0, 90.0], 12.0), Hit::Outside); + near(TransformSession::box_turn_direction(&q, [220.0, 90.0]), [-0.1 / 1.01_f64.sqrt(), 1.0 / 1.01_f64.sqrt()]); + } +} + +#[test] +fn outside_rotation_has_eight_edge_and_corner_orientations() { + let app = app(QUAD, 1.0); + let h = std::f64::consts::FRAC_1_SQRT_2; + for (p, direction) in [ + ([300.0, -20.0], [0.0, 1.0]), + ([620.0, -20.0], [-h, h]), + ([620.0, 200.0], [-1.0, 0.0]), + ([620.0, 420.0], [-h, -h]), + ([300.0, 420.0], [0.0, -1.0]), + ([-20.0, 420.0], [h, -h]), + ([-20.0, 200.0], [1.0, 0.0]), + ([-20.0, -20.0], [h, h]), + ] { + near(rotate_cursor_dir(&app, p), direction); + assert_eq!(cursor(&app, &view(1.0), p, Modifiers::NONE), Some(CursorIcon::None)); + assert_eq!(cursor(&app, &view(1.0), p, Modifiers::COMMAND), Some(CursorIcon::None)); + } +} + +#[test] +fn unopened_move_controls_share_the_open_sessions_zones_and_cursors() { + let app = app(QUAD, 1.0); + let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 300.0)); + for p in [pos2(100.0, 100.0), pos2(180.0, 95.0), pos2(505.0, 150.0), pos2(180.0, 101.0), pos2(620.0, 200.0), pos2(-20.0, -20.0)] { + let d = [f64::from(p.x), f64::from(p.y)]; + assert_eq!(transform_controls_cursor(r, p), cursor(&app, &view(1.0), d, Modifiers::NONE), "{p:?}"); + assert_eq!(transform_controls_hit(r, p), hit(app.ui.transform.as_ref().unwrap(), d, 12.0) != Hit::Inside); + match (transform_controls_turn(r, p), rotate_cursor_dir(&app, d)) { + (None, None) => {} + (Some(a), Some(b)) => near(Some([f64::from(a.x) / 16.0, f64::from(a.y) / 16.0]), b), + pair => panic!("unopened/open rotation disagreement: {pair:?}"), + } + } + assert_eq!(transform_controls_cursor(r, r.center()), Some(CursorIcon::Default)); + assert!(!transform_controls_hit(r, r.center()), "inside remains an ordinary Move drag"); +} + +#[test] +fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() { + let mut app = app(QUAD, 1.0); + for mode in [TransformMode::Distort, TransformMode::Skew] { + app.ui.transform.as_mut().unwrap().mode = mode; + assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None); + assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Default)); + } + app.ui.transform.as_mut().unwrap().mode = TransformMode::Free; + app.ui.transform.as_mut().unwrap().content_aware = Some(ContentAwareOptions::default()); + assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None); + assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Default)); + app.ui.transform.as_mut().unwrap().content_aware = None; + let t = app.ui.transform.as_mut().unwrap(); + t.warp = Some(photocraft_geom::warp::Warp::none(t.rect)); + assert_eq!(rotate_cursor_dir(&app, [620.0, 200.0]), None); + assert_eq!(cursor(&app, &view(1.0), [620.0, 200.0], Modifiers::NONE), Some(CursorIcon::Crosshair), "Warp retains its own cursor"); + app.ui.transform.as_mut().unwrap().warp = None; + assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 200.0]), None); + assert_eq!(TransformSession::box_turn_direction(&[[0.0, 0.0]; 4], [20.0, 20.0]), None); +} + +#[test] +fn rotate_drag_keeps_the_arrow_when_the_pointer_enters_the_box() { + let mut app = app(QUAD, 1.0); + app.ui.transform = None; + app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [4, 4, 16, 16], "fill": "#ff0000"})).unwrap(); + let ctx = egui::Context::default(); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + crate::transform_tool::pointer(&mut app, crate::canvas::ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + crate::transform_tool::pointer(&mut app, crate::canvas::ToolEvent::Move { x: 10.0, y: 10.0, pressure: 1.0 }, Modifiers::NONE); + assert!(rotate_cursor_dir(&app, [10.0, 10.0]).is_some(), "the held rotation gesture owns the arrow even inside"); + assert_eq!(cursor(&app, &view(1.0), [10.0, 10.0], Modifiers::NONE), Some(CursorIcon::None)); +} From 6eb625ccbfd8fcfa6f27e5de2f58323d490f85e9 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 19:35:45 -0800 Subject: [PATCH 033/113] Orient transform rotate arrows by quad winding --- crates/ui-egui/src/tools/transform_tool/pointer.rs | 6 ++++-- crates/ui-egui/src/transform_hit_zone_tests.rs | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 6f9186164a..781e02ec20 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -67,8 +67,10 @@ impl TransformSession { } else { let (a, b) = (quad[i], quad[(i + 1) % 4]); let normal = [a[1] - b[1], b[0] - a[0]]; - let center = quad.iter().fold([0.0; 2], |c, q| [c[0] + q[0] / 4.0, c[1] + q[1] / 4.0]); - let sign = (normal[0] * (center[0] - a[0]) + normal[1] * (center[1] - a[1])).signum(); + // Winding orients every edge, even when a concave quad's mean corner position + // lies on the wrong side of this edge. Translate before taking the area. + let cross = |i: usize, j: usize| (quad[i][0] - quad[0][0]) * (quad[j][1] - quad[0][1]) - (quad[i][1] - quad[0][1]) * (quad[j][0] - quad[0][0]); + let sign = (cross(1, 2) + cross(2, 3)).signum(); normal.map(|v| v * sign) }; unit(toward) diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index a388f6c909..397cef40c8 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -87,6 +87,7 @@ fn turned_box_zones_and_resize_cursors_follow_the_quad() { let xf = view(zoom); let t = app.ui.transform.as_ref().unwrap(); for (p, expected, icon) in [ + ([500.0, 100.0], Hit::Corner(1), CursorIcon::ResizeHorizontal), ([180.0, 95.0], Hit::Edge(0), CursorIcon::ResizeNeSw), ([505.0, 150.0], Hit::Edge(1), CursorIcon::ResizeNwSe), ([180.0, 101.0], Hit::Inside, CursorIcon::Default), @@ -112,6 +113,14 @@ fn distorted_and_flipped_quads_use_their_edges_not_an_axis_aligned_box() { } } +#[test] +fn concave_quad_edge_direction_uses_winding_in_both_orientations() { + let q = [[0.0, 0.0], [100.0, 0.0], [10.0, 10.0], [0.0, 100.0]]; + for q in [q, [q[1], q[0], q[3], q[2]]] { + near(TransformSession::box_turn_direction(&q, [56.0, 14.0]), [-1.0 / 82.0_f64.sqrt(), -9.0 / 82.0_f64.sqrt()]); + } +} + #[test] fn outside_rotation_has_eight_edge_and_corner_orientations() { let app = app(QUAD, 1.0); From 5e1e4b85026c930d0692aec68ca8817c03b3a3d4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 19:36:59 -0800 Subject: [PATCH 034/113] Keep the transform controls point constructor test-only --- crates/ui-egui/src/canvas/transform_controls.rs | 2 +- crates/ui-egui/src/transform_hit_zone_tests.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs index d0ad6ee752..68f37fb5b9 100644 --- a/crates/ui-egui/src/canvas/transform_controls.rs +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -1,6 +1,6 @@ use super::selection::floating_outline; use super::view_xform::ViewXform; -use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, pos2, vec2}; +use super::{Color32, LayerContent, PhotocraftApp, Pos2, Rect, Stroke, Tool, Vec2, vec2}; /// View › Show › Layer Edges: the colour of the active layer's outline. pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb); diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index 397cef40c8..ca08d2f012 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::state::{ContentAwareOptions, TransformMode, TransformSession}; use crate::transform_tool::{Hit, cursor, hit, rotate_cursor_dir}; -use egui::{CursorIcon, Modifiers}; +use egui::{CursorIcon, Modifiers, pos2}; const QUAD: [[f64; 2]; 4] = [[100.0, 100.0], [500.0, 100.0], [500.0, 300.0], [100.0, 300.0]]; From 4edd0914b0d620923241061889a3a20c6a839287 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 19:49:56 -0800 Subject: [PATCH 035/113] Exercise unopened Move edge controls through native dispatch --- .../ui-egui/src/transform_hit_zone_tests.rs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index ca08d2f012..cd0e818853 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -159,6 +159,39 @@ fn unopened_move_controls_share_the_open_sessions_zones_and_cursors() { assert!(!transform_controls_hit(r, r.center()), "inside remains an ordinary Move drag"); } +#[test] +fn move_whole_edge_press_enters_scaling_at_both_zooms() { + for zoom in [1.0, 2.0] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", serde_json::json!({"width": 640, "height": 480})).unwrap(); + app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [100, 100, 400, 200], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + app.ui.extras.snap = false; + let xf = view(zoom); + let ctx = egui::Context::default(); + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + // Away from the top edge's midpoint and corners: the native canvas first opens the + // controls here, then forwards the same document-space press to the transform tool. + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, xf.to_screen(180.0, 100.0))); + for event in [ + crate::canvas::ToolEvent::Down { x: 180.0, y: 100.0, pressure: 1.0 }, + crate::canvas::ToolEvent::Move { x: 180.0, y: 90.0, pressure: 1.0 }, + crate::canvas::ToolEvent::Up { x: 180.0, y: 90.0 }, + ] { + crate::canvas::tool_event(&mut app, event, Modifiers::SHIFT); + } + let t = app.ui.transform.as_ref().expect("a handle release retains the transform session"); + assert!(t.quad[0][1] < 100.0, "the pressed edge scales"); + assert!((t.quad[2][1] - 300.0).abs() < 1e-6, "the opposite edge anchors scaling instead of moving the whole box"); + assert_eq!(app.session.active().unwrap().doc, before, "a preview does not commit pixels"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + } +} + #[test] fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() { let mut app = app(QUAD, 1.0); From 49575e3a815e2affca3361a6d1d807dd74458509 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 19:51:50 -0800 Subject: [PATCH 036/113] Keep invalid points outside Move transform control activation --- crates/ui-egui/src/canvas/transform_controls.rs | 5 ++++- crates/ui-egui/src/transform_hit_zone_tests.rs | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs index 68f37fb5b9..5a26a5a281 100644 --- a/crates/ui-egui/src/canvas/transform_controls.rs +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -68,6 +68,9 @@ fn controls_zone(r: Rect, p: Pos2) -> crate::transform_tool::Hit { /// Share the open session's screen-sized zones before the first interaction (#11097). pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option { + if !p.is_finite() { + return None; + } use crate::transform_tool::Hit; Some(match controls_zone(r, p) { Hit::Corner(0 | 2) => egui::CursorIcon::ResizeNwSe, @@ -91,7 +94,7 @@ pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option { /// A visible handle starts scaling; any point outside the box starts rotation. /// The interior stays the normal Move-tool drag target. pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool { - !matches!(controls_zone(r, p), crate::transform_tool::Hit::Inside | crate::transform_tool::Hit::Pivot) + p.is_finite() && !matches!(controls_zone(r, p), crate::transform_tool::Hit::Inside | crate::transform_tool::Hit::Pivot) } /// Enter the existing Free Transform session when a Move-tool transform control is pressed: on diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index cd0e818853..66d13125b7 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -212,6 +212,12 @@ fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() { app.ui.transform.as_mut().unwrap().warp = None; assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 200.0]), None); assert_eq!(TransformSession::box_turn_direction(&[[0.0, 0.0]; 4], [20.0, 20.0]), None); + let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(500.0, 300.0)); + for p in [pos2(f32::NAN, 200.0), pos2(f32::INFINITY, 200.0)] { + assert_eq!(transform_controls_cursor(r, p), None, "invalid points cannot hide the pointer"); + assert_eq!(transform_controls_turn(r, p), None); + assert!(!transform_controls_hit(r, p), "invalid points cannot activate the overlay"); + } } #[test] From d35d966bed91f7cdbea9339896ce718101f6cedf Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 20:36:06 -0800 Subject: [PATCH 037/113] Preserve small transform handles and projected edge points --- .../src/tools/transform_tool/pointer.rs | 35 +++++++---- .../ui-egui/src/transform_hit_zone_tests.rs | 60 ++++++++++++++++++- 2 files changed, 83 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 781e02ec20..735bec0658 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -23,19 +23,32 @@ impl TransformSession { // `tol` is the existing 12 pt handle tolerance, divided by the view zoom. let corner_radius = tol * (8.0 / HANDLE_PX); let edge_width = tol * (11.0 / HANDLE_PX); + // Canvas coordinates round through f32. Treat only sub-pixel projection noise as + // the line itself; a point one screen pixel inside still belongs to the interior. + let line_epsilon = tol.abs() * (1e-3 / HANDLE_PX); let distance = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); - if let Some((i, _)) = quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) { - return Hit::Corner(i); - } let interior = inside(quad, p); - let edge = (0..4) - .filter_map(|i| { - let (_, q) = edge_projection(quad, i, p)?; - let d = distance(q); - // One pixel inside is interior, not a scale handle. The line itself is a handle. - (d <= edge_width && (!interior || d <= tol.abs() * 1e-9)).then_some((i, d)) - }) - .min_by(|a, b| a.1.total_cmp(&b.1)); + let edge_distance = |i| { + let (_, q) = edge_projection(quad, i, p)?; + let d = distance(q); + (d <= edge_width && (!interior || d <= line_epsilon)).then_some(d) + }; + if let Some((i, corner_distance)) = + quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) + { + // Corners beat edge bands, but overlapping painted handles on small boxes keep + // their nearest-handle priority. Otherwise a 16pt box's edge center is a corner. + let painted_edge = (0..4) + .filter_map(|k| { + edge_distance(k)?; + let (a, b) = (quad[k], quad[(k + 1) % 4]); + let d = distance([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]); + (d < corner_distance).then_some((k, d)) + }) + .min_by(|a, b| a.1.total_cmp(&b.1)); + return painted_edge.map_or(Hit::Corner(i), |(k, _)| Hit::Edge(k)); + } + let edge = (0..4).filter_map(|i| edge_distance(i).map(|d| (i, d))).min_by(|a, b| a.1.total_cmp(&b.1)); match edge { Some((i, _)) => Hit::Edge(i), None if interior => Hit::Inside, diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index 66d13125b7..010d4e68e9 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -69,7 +69,65 @@ fn whole_edge_and_corner_priority_table_at_100_and_200_percent() { assert_eq!(hit(&t, p.map(|v| v / zoom), 12.0 / zoom), expected, "zoom {zoom}, screen {p:?}"); } let tiny = session([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]]); - assert_eq!(TransformSession::box_hit(&tiny.quad, [5.0, -1.0], 12.0), Hit::Corner(0), "corners beat overlapping edge bands"); + assert_eq!(TransformSession::box_hit(&tiny.quad, [1.0, -1.0], 12.0), Hit::Corner(0), "corners beat overlapping edge bands"); + } +} + +#[test] +fn small_boxes_keep_their_painted_mid_edge_handles() { + for side in [8.0, 16.0, 32.0] { + for zoom in [1.0, 2.0] { + let q = [[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]].map(|p| p.map(|v| v / zoom)); + let t = session(q); + for i in 0..4 { + let (a, b) = (q[i], q[(i + 1) % 4]); + let midpoint = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + assert_eq!(hit(&t, midpoint, 12.0 / zoom), Hit::Edge(i), "side {side}, zoom {zoom}, edge {i}"); + assert_eq!(hit(&t, a, 12.0 / zoom), Hit::Corner(i)); + } + } + } +} + +#[test] +fn an_edge_survives_the_actual_f32_view_round_trip() { + for zoom in [1.0_f32, 2.0] { + let q = [[100.0, 100.00002], [500.0, 100.00002], [500.0, 300.0], [100.0, 300.0]].map(|p| p.map(|v| v / f64::from(zoom))); + let t = session(q); + let xf = view(zoom); + let p = xf.to_doc(xf.to_screen((180.0 / f64::from(zoom)) as f32, q[0][1] as f32)); + let inward_rounding = (p[1] - q[0][1]) * f64::from(zoom); + assert!(inward_rounding > 0.0 && inward_rounding < 1e-3, "fixture must expose inward f32 rounding: {inward_rounding}"); + assert_eq!(hit(&t, p, 12.0 / f64::from(zoom)), Hit::Edge(0)); + assert_eq!(hit(&t, [p[0], q[0][1] + 1.0 / f64::from(zoom)], 12.0 / f64::from(zoom)), Hit::Inside, "a whole pixel inside still moves"); + } +} + +#[test] +fn a_small_edge_keeps_distort_and_legacy_aspect_behavior() { + for mode in [TransformMode::Distort, TransformMode::Free] { + let mut app = app(QUAD, 1.0); + app.ui.transform = None; + app.ui.extras.snap = false; + app.ui.transform_unlinked = true; + app.session.edit_prefs(|p| p.general.use_legacy_free_transform = true); + app.session.execute("shape.create", serde_json::json!({"kind":"rect","rect":[8,8,16,16],"fill":"#ff0000"})).unwrap(); + crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap(); + app.ui.transform.as_mut().unwrap().mode = mode; + let before = app.ui.transform.as_ref().unwrap().quad; + for event in [ + crate::canvas::ToolEvent::Down { x: 24.0, y: 16.0, pressure: 1.0 }, + crate::canvas::ToolEvent::Move { x: 40.0, y: 16.0, pressure: 1.0 }, + crate::canvas::ToolEvent::Up { x: 40.0, y: 16.0 }, + ] { + crate::canvas::tool_event(&mut app, event, Modifiers::NONE); + } + let q = app.ui.transform.as_ref().unwrap().quad; + if mode == TransformMode::Distort { + assert_eq!(q, before, "Distort still ignores an edge press"); + } else { + assert!((q[2][0] - q[0][0] - 32.0).abs() < 1e-6 && (q[2][1] - q[0][1] - 16.0).abs() < 1e-6, "a legacy edge stretches one axis: {q:?}"); + } } } From 6b38df86bcfe8406bbb920dc5bb255521d951bcd Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 3 Nov 2026 22:11:16 -0800 Subject: [PATCH 038/113] Document transform hit-zone invariants and regression controls --- crates/ui-egui/src/canvas/transform_controls.rs | 2 ++ crates/ui-egui/src/tools/transform_tool/pointer.rs | 7 +++++++ crates/ui-egui/src/transform_hit_zone_tests.rs | 12 ++++++++++++ 3 files changed, 21 insertions(+) diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs index 5a26a5a281..76237b1e20 100644 --- a/crates/ui-egui/src/canvas/transform_controls.rs +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -58,10 +58,12 @@ pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Op Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32))) } +/// Express the unopened screen rectangle in the same corner order as a transform quad. fn controls_quad(r: Rect) -> [[f64; 2]; 4] { [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| [f64::from(p.x), f64::from(p.y)]) } +/// Classify screen coordinates with the fixed screen-space tolerance, without a pivot. fn controls_zone(r: Rect, p: Pos2) -> crate::transform_tool::Hit { crate::state::TransformSession::box_hit(&controls_quad(r), [f64::from(p.x), f64::from(p.y)], crate::transform_tool::HANDLE_PX) } diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 735bec0658..d06f921574 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -19,6 +19,9 @@ pub(crate) enum Hit { /// Screen-sized corner and outward edge bands, shared with Move's unopened controls. impl TransformSession { + /// Classify a document point with screen-sized corner and outward edge zones. + /// Corners outrank free edge bands; overlapping painted handles keep nearest-handle priority. + /// Only projection-scale rounding is treated as an edge on the interior side. pub(crate) fn box_hit(quad: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> Hit { // `tol` is the existing 12 pt handle tolerance, divided by the view zoom. let corner_radius = tol * (8.0 / HANDLE_PX); @@ -119,6 +122,8 @@ pub(crate) fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { if d(t.pivot) < tol && d(t.pivot) < handle_distance { Hit::Pivot } else { h } } +/// Even-odd quad membership, independent of winding and valid for concave boxes. +/// Handles and edge-rounding tolerance are classified separately by the caller. fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { let mut c = false; for i in 0..4 { @@ -314,6 +319,8 @@ pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64 rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) } +/// Choose hover or captured rotation feedback without overriding scaling gestures. +/// Warp, Distort, Skew and Content-Aware Scale keep their own cursor behavior. pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { // Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow. if !(p[0].is_finite() && p[1].is_finite()) diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index 010d4e68e9..1f9b52ae1c 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -43,6 +43,7 @@ fn near(actual: Option<[f64; 2]>, expected: [f64; 2]) { assert!((actual[0] - expected[0]).hypot(actual[1] - expected[1]) < 1e-6, "{actual:?} != {expected:?}"); } +/// Screen-sized zones must survive zoom changes; the interior control rejects an all-sided edge grab area. #[test] fn whole_edge_and_corner_priority_table_at_100_and_200_percent() { for zoom in [1.0, 2.0] { @@ -73,6 +74,7 @@ fn whole_edge_and_corner_priority_table_at_100_and_200_percent() { } } +/// An overlapping corner zone must not steal a closer painted midpoint on a small box. #[test] fn small_boxes_keep_their_painted_mid_edge_handles() { for side in [8.0, 16.0, 32.0] { @@ -89,6 +91,7 @@ fn small_boxes_keep_their_painted_mid_edge_handles() { } } +/// Reproduce inward rounding through the view transform, with a one-pixel interior control. #[test] fn an_edge_survives_the_actual_f32_view_round_trip() { for zoom in [1.0_f32, 2.0] { @@ -103,6 +106,7 @@ fn an_edge_survives_the_actual_f32_view_round_trip() { } } +/// The same small-edge press must be ignored by Distort and stretch one axis in legacy unlinked scaling. #[test] fn a_small_edge_keeps_distort_and_legacy_aspect_behavior() { for mode in [TransformMode::Distort, TransformMode::Free] { @@ -131,6 +135,7 @@ fn a_small_edge_keeps_distort_and_legacy_aspect_behavior() { } } +/// At 45 degrees, corners and edges exchange cursor axis orientation at both tested zooms. #[test] fn turned_box_zones_and_resize_cursors_follow_the_quad() { let turn = |p: [f64; 2]| { @@ -158,6 +163,7 @@ fn turned_box_zones_and_resize_cursors_follow_the_quad() { } } +/// Skewed edges and reversed winding must use actual segment geometry for hits and turn direction. #[test] fn distorted_and_flipped_quads_use_their_edges_not_an_axis_aligned_box() { let q = [[100.0, 100.0], [500.0, 140.0], [460.0, 300.0], [80.0, 260.0]]; @@ -171,6 +177,7 @@ fn distorted_and_flipped_quads_use_their_edges_not_an_axis_aligned_box() { } } +/// A concave quad whose corner mean is beyond an edge rejects center-based normal orientation. #[test] fn concave_quad_edge_direction_uses_winding_in_both_orientations() { let q = [[0.0, 0.0], [100.0, 0.0], [10.0, 10.0], [0.0, 100.0]]; @@ -179,6 +186,7 @@ fn concave_quad_edge_direction_uses_winding_in_both_orientations() { } } +/// Each outside position selects its inward turn orientation and hides the system cursor. #[test] fn outside_rotation_has_eight_edge_and_corner_orientations() { let app = app(QUAD, 1.0); @@ -199,6 +207,7 @@ fn outside_rotation_has_eight_edge_and_corner_orientations() { } } +/// Compare unopened controls with an active session at identical points, including a free interior. #[test] fn unopened_move_controls_share_the_open_sessions_zones_and_cursors() { let app = app(QUAD, 1.0); @@ -217,6 +226,7 @@ fn unopened_move_controls_share_the_open_sessions_zones_and_cursors() { assert!(!transform_controls_hit(r, r.center()), "inside remains an ordinary Move drag"); } +/// A press away from midpoint handles must scale an anchored preview without creating a history edit. #[test] fn move_whole_edge_press_enters_scaling_at_both_zooms() { for zoom in [1.0, 2.0] { @@ -250,6 +260,7 @@ fn move_whole_edge_press_enters_scaling_at_both_zooms() { } } +/// Excluded modes retain cursor ownership, and non-finite coordinates cannot activate controls. #[test] fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() { let mut app = app(QUAD, 1.0); @@ -278,6 +289,7 @@ fn modes_that_do_not_rotate_and_invalid_points_do_not_hide_the_pointer() { } } +/// Captured rotation must retain feedback after crossing into the box, independent of hover zones. #[test] fn rotate_drag_keeps_the_arrow_when_the_pointer_enters_the_box() { let mut app = app(QUAD, 1.0); From b5ff372c456c330f0bb99fedcd953f321e2ba154 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 5 Nov 2026 15:22:12 -0800 Subject: [PATCH 039/113] Check reference point ownership through the actual drag --- .../ui-egui/src/transform_hit_zone_tests.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index 72715bdcf2..86f16ac72e 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -216,12 +216,17 @@ fn outside_rotation_has_eight_edge_and_corner_orientations() { #[test] fn outside_reference_point_owns_the_pointer_only_when_shown() { let p = [80.0, 40.0]; + let pivot = [76.0, 40.0]; + let to = [80.0, 48.0]; for shown in [false, true] { let mut app = app(QUAD, 1.0); app.ui.transform = None; + app.ui.extras.snap = false; app.session.execute("shape.create", serde_json::json!({"kind": "rect", "rect": [4, 4, 16, 16], "fill": "#ff0000"})).unwrap(); crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap(); - app.ui.transform.as_mut().unwrap().pivot = p; + let t = app.ui.transform.as_mut().unwrap(); + t.pivot = pivot; + let quad = t.quad; app.ui.tool_options.transform_reference_point = shown; assert_eq!(rotate_cursor_dir(&app, p).is_some(), !shown); let icon = if shown { CursorIcon::Crosshair } else { CursorIcon::None }; @@ -229,8 +234,16 @@ fn outside_reference_point_owns_the_pointer_only_when_shown() { let down = crate::canvas::ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }; crate::transform_tool::pointer(&mut app, down, Modifiers::NONE); - let gesture = app.transform_preview.as_ref().unwrap().gesture.unwrap(); - assert_eq!(gesture.hit, if shown { Hit::Pivot } else { Hit::Outside }); + let drag = crate::canvas::ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }; + crate::transform_tool::pointer(&mut app, drag, Modifiers::NONE); + let t = app.ui.transform.as_ref().unwrap(); + if shown { + assert_eq!(t.quad, quad, "the reference-point drag leaves the box in place"); + assert_eq!(t.pivot, to); + } else { + assert_ne!(t.quad, quad, "the outside drag turns the box"); + assert_eq!(t.pivot, pivot); + } } } From 2037705698ed9e0001f2f19530cfeb58b7131285 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:17:36 +0100 Subject: [PATCH 040/113] Address review: pin crop's 0 origin, numeric strings, partly-outside rect and Reveal All x/y of 0 count as given, numeric strings are refused on every side, a rectangle partly past the canvas grows it as passed, and Reveal All (crop_keeping_background) still crops to all four sides with a selection active. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds/tests.rs | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index bf414dc189..b35040cb5d 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -437,6 +437,51 @@ fn crop_refuses_a_bad_explicit_rect_instead_of_cropping_to_the_selection() { assert_eq!(doc(&s).size, Size::new(21, 10)); } +/// The explicit rectangle of #9279's edge cases, each with a selection elsewhere that a fallback +/// would crop to: `0` is a given origin, numeric strings are not numbers (refused, as `x`/`y` +/// already were), and a rectangle partly past the canvas is used as passed, never clamped. +#[test] +fn crop_rect_edge_cases_never_fall_back_to_the_selection() { + let with_selection = || { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + s + }; + // `x`/`y` of 0 count as given: the red square (10, 5)..(20, 15) stays where it was, where a + // crop to the selection would have moved it to (5, 3). + let mut s = with_selection(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 15, "height": 10})).unwrap(); + assert_eq!(doc(&s).size, Size::new(15, 10)); + assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 15, 10)); + // Numeric strings are refused on every side, with or without a selection. + for p in [ + json!({"x": "0", "y": "0", "width": "15", "height": "10"}), + json!({"x": "0", "y": 0, "width": 15, "height": 10}), + json!({"x": 0, "y": 0, "width": 15, "height": "10"}), + ] { + for mut s in [with_selection(), session()] { + let err = s.execute("image.crop", p.clone()).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err:?}"); + assert_eq!(doc(&s).size, Size::new(40, 20), "{p}"); + } + } + // Partly outside the canvas: the canvas grows to the rectangle, not to its overlap with the + // canvas or the selection. + let mut s = with_selection(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 30, "height": 40})).unwrap(); + assert_eq!(doc(&s).size, Size::new(30, 40)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]); + // Reveal All passes all four sides through the same check (here x = y = 0: the hidden pixels + // are past the right and bottom edges), so a selection doesn't change what it reveals. + let mut s = with_selection(); + s.execute("image.canvasSize", json!({"width": 12, "height": 8, "anchor": "topLeft"})).unwrap(); + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 4, "height": 4})).unwrap(); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true); + let size = doc(&s).size; + assert!(size.width >= 20 && size.height >= 15, "{size:?}: the red square is revealed"); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(19, 14), vec![1.0, 0.0, 0.0, 1.0]); +} + #[test] fn crop_extension_fills_the_background_with_the_background_colour() { let mut shrink = Session::new(); From 608cedc5eb3e164148a347fa80eb3bb02163b7c2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:24:20 +0100 Subject: [PATCH 041/113] Address review: keep scaled pattern scales within 1..1000 % scale_effects (Image Size's Scale Styles, Layer Style > Scale Effects, the Free Transform style preview) now clamps the Pattern Overlay, Bevel & Emboss Texture and pattern Stroke scales to the 1..1000 % the Layer Style dialog allows, through one shared photocraft_doc::effects::PATTERN_SCALE_RANGE that the layer style param parser now uses too. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/effects.rs | 4 ++ crates/engine/src/cmd/image_cmds.rs | 16 ++++- .../engine/src/cmd/layer_menu_cmds/tests.rs | 66 +++++++++++++++++++ crates/engine/src/layer_style.rs | 5 +- 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs index 4e3f32a97f..a71aa883dd 100644 --- a/crates/doc/src/effects.rs +++ b/crates/doc/src/effects.rs @@ -10,6 +10,10 @@ use serde::{Deserialize, Serialize}; use crate::adjust::CurvePoint; +/// The range of a style's pattern scale as a fraction (1 = 100 %): Pattern Overlay, a pattern +/// Stroke and the Bevel & Emboss Texture all take 1..1000 % in the Layer Style dialog. +pub const PATTERN_SCALE_RANGE: (f32, f32) = (0.01, 10.0); + /// Gradient geometry (fill layers, gradient overlays, gradient strokes). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum GradientStyle { diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 6b4f06c3ee..e41fbf09bb 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -151,16 +151,16 @@ pub fn scale_effects(fx: &mut Effects, k: f32) { b.size *= k; b.soften *= k; if let Some(t) = &mut b.texture { - t.scale *= k; + scale_pattern(&mut t.scale, k); } } - Effect::PatternOverlay { scale, .. } => *scale *= k, + Effect::PatternOverlay { scale, .. } => scale_pattern(scale, k), Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {} } if let Effect::Stroke(s) = e && let FxPaint::Pattern { scale, .. } = &mut s.paint { - *scale *= k; + scale_pattern(scale, k); } } // Effects changed: the preserved PSD block no longer applies. @@ -169,6 +169,16 @@ pub fn scale_effects(fx: &mut Effects, k: f32) { } } +/// Scale a style's pattern scale, kept within the 1..1000 % the Layer Style dialog and the +/// reference application allow (a 10 % pattern reduced to 5 % stays at 1 %). +fn scale_pattern(scale: &mut f32, k: f32) { + let (min, max) = photocraft_doc::effects::PATTERN_SCALE_RANGE; + let v = *scale * k; + if !v.is_nan() { + *scale = v.clamp(min, max); + } +} + /// Image Size's resampling methods; `None` changes the resolution only. #[derive(Clone, Copy)] enum Method { diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index 758ba4c4ba..b60e984bd0 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -160,6 +160,72 @@ fn scale_effects_scales_the_bevel_texture_with_the_pattern_overlay() { assert_eq!((overlay, texture), (Some(0.5), Some(0.5))); } +/// The pattern scales of Pattern Overlay, the Bevel & Emboss Texture and a pattern Stroke, in +/// that order. +fn pattern_scales(s: &Session) -> (Option, Option, Option) { + let fx = &active(s).effects.items; + let overlay = fx.iter().find_map(|e| match e { + Effect::PatternOverlay { scale, .. } => Some(*scale), + _ => None, + }); + let texture = fx.iter().find_map(|e| match e { + Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale), + _ => None, + }); + let stroke = fx.iter().find_map(|e| match e { + Effect::Stroke(st) => match &st.paint { + photocraft_doc::FxPaint::Pattern { scale, .. } => Some(*scale), + _ => None, + }, + _ => None, + }); + (overlay, texture, stroke) +} + +/// A layer with a Pattern Overlay, a Bevel & Emboss Texture and a pattern Stroke, all at `pct` %. +fn pattern_styled(pct: f64) -> Session { + let mut s = session(8, "rgb"); + paint(&mut s, disc); + s.execute("layer.layerStyle.patternOverlay", json!({"scale": pct})).unwrap(); + s.execute("layer.layerStyle.bevelEmboss", json!({"texture": "Bubbles", "textureScale": pct})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 3})).unwrap(); + s.edit("pattern stroke", |doc, active| { + let layer = doc.layer_mut(active.unwrap()).unwrap(); + for e in &mut layer.effects.items { + if let Effect::Stroke(st) = e { + st.paint = photocraft_doc::FxPaint::Pattern { name: "Bubbles".into(), id: String::new(), scale: pct as f32 / 100.0 }; + } + } + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn scale_effects_keeps_pattern_scales_within_the_dialog_range() { + // 10 % reduced to 1 % would be 0.1 %: the patterns stop at the dialog's 1 %. + let mut s = pattern_styled(10.0); + s.execute("layer.layerStyle.scaleEffects", json!({"scale": 1})).unwrap(); + assert_eq!(pattern_scales(&s), (Some(0.01), Some(0.01), Some(0.01))); + // 500 % enlarged to 1000 % would be 5000 %: they stop at 1000 %. + let mut s = pattern_styled(500.0); + s.execute("layer.layerStyle.scaleEffects", json!({"scale": 1000})).unwrap(); + assert_eq!(pattern_scales(&s), (Some(10.0), Some(10.0), Some(10.0))); + // Inside the range nothing is clamped: 200 % halved is 100 %. + let mut s = pattern_styled(200.0); + s.execute("layer.layerStyle.scaleEffects", json!({"scale": 50})).unwrap(); + assert_eq!(pattern_scales(&s), (Some(1.0), Some(1.0), Some(1.0))); +} + +#[test] +fn image_size_scale_styles_keeps_pattern_scales_within_the_dialog_range() { + // 40x30 -> 400x300 with Scale Styles multiplies by 10: 500 % would become 5000 %. + let mut s = pattern_styled(500.0); + s.execute("image.imageSize", json!({"width": 400, "height": 300, "scaleStyles": true})).unwrap(); + assert_eq!(pattern_scales(&s), (Some(10.0), Some(10.0), Some(10.0))); +} + #[test] fn global_light_rejects_numbers_beyond_f32() { let mut s = session(8, "rgb"); diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 176f08b264..af7180cc8a 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -2,6 +2,7 @@ use photocraft_color::{BlendMode, Color}; use photocraft_doc::adjust::CurvePoint; +use photocraft_doc::effects::PATTERN_SCALE_RANGE; use photocraft_doc::{ Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, GradientStyle, Satin, Shadow, StrokeFx, StrokePosition, @@ -795,7 +796,7 @@ fn overlay_pattern(fx: &mut Effect, p: &Value) { *id = String::new(); } if let Some(x) = f_of(p, "scale") { - *scale = (x / 100.0).clamp(0.01, 10.0); + *scale = (x / 100.0).clamp(PATTERN_SCALE_RANGE.0, PATTERN_SCALE_RANGE.1); } if let Some(x) = f_of(p, "angle") { *angle = x; @@ -903,7 +904,7 @@ fn overlay_bevel(bv: &mut Bevel, p: &Value) { bv.texture = Some(photocraft_doc::BevelTexture { name: t.to_string(), id: t.to_string(), - scale: (f(p, "textureScale", 100.0) / 100.0).clamp(0.01, 10.0), + scale: (f(p, "textureScale", 100.0) / 100.0).clamp(PATTERN_SCALE_RANGE.0, PATTERN_SCALE_RANGE.1), depth: (f(p, "textureDepth", 100.0) / 100.0).clamp(-10.0, 10.0), invert: b(p, "textureInvert", false), link: b(p, "textureLink", true), From e5e2ef36d0d6cce6c4e63f760e8e41f4c60e8114 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:33:34 +0100 Subject: [PATCH 042/113] Address review: crop key tests reach keys() past the default-frame guard After #9855 crop_shield::keys returns early over the untouched default frame, so the Shift+H/Shift+P and Alt-letter tests on crop_app() passed without the fix. They now start a crop in progress (frame changed, default_frame false); the Shift tests also cover the untouched default frame (and, for Shift+I, no frame), where the letters must still reach the tool keys. Plain P with a crop in progress still toggles Classic Mode, so the setup really reaches the key checks. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/crop_shield.rs | 54 ++++++++++++++++++------- crates/ui-egui/src/tools/crop_size.rs | 33 ++++++++++----- 2 files changed, 62 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/tools/crop_shield.rs b/crates/ui-egui/src/tools/crop_shield.rs index e71e86e8c5..ffc9113ad0 100644 --- a/crates/ui-egui/src/tools/crop_shield.rs +++ b/crates/ui-egui/src/tools/crop_shield.rs @@ -389,25 +389,51 @@ mod tests { assert!(app.ui.tool_options.crop_shield.show_cropped_area); } - /// ⇧H and ⇧P are the Hand and Pen tool keys even with a crop box: egui's `consume_key` ignores - /// an extra ⇧, so the plain-key checks must refuse it. + /// A crop in progress: a frame changed from the default one, so [`keys`] gets past its + /// early returns (#9731). + fn crop_in_progress_app() -> PhotocraftApp { + let mut app = crop_app(); + app.ui.crop_rect = Some([20.0, 10.0, 120.0, 90.0]); + app.crop.default_frame = false; + app + } + + /// ⇧H and ⇧P are the Hand and Pen tool keys with a crop in progress, where plain H and P are + /// the crop box's: egui's `consume_key` ignores an extra ⇧, so the plain-key checks must refuse + /// it. Over the untouched default frame they are the tool keys too. #[test] fn shift_h_and_shift_p_switch_tools_instead_of_crop_options() { - for (key, tool) in [(Key::H, Tool::Hand), (Key::P, Tool::Pen)] { - let mut app = crop_app(); - assert!(app.session.prefs().tools.use_shift_key_for_tool_switch); - let before = app.ui.tool_options.crop_shield.clone(); - let ctx = egui::Context::default(); - ctx.input_mut(|i| { - // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). - i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); - }); - crate::shortcuts::handle(&mut app, &ctx); - assert_eq!(app.ui.tool, tool, "{key:?}"); - assert_eq!(app.ui.tool_options.crop_shield, before, "{key:?} leaves Show Cropped Area and Classic Mode alone"); + for in_progress in [true, false] { + for (key, tool) in [(Key::H, Tool::Hand), (Key::P, Tool::Pen)] { + let mut app = if in_progress { crop_in_progress_app() } else { crop_app() }; + assert_eq!(app.crop.default_frame, !in_progress); + assert!(app.session.prefs().tools.use_shift_key_for_tool_switch); + let before = app.ui.tool_options.crop_shield.clone(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). + i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + }); + crate::shortcuts::handle(&mut app, &ctx); + assert_eq!(app.ui.tool, tool, "{key:?}, crop in progress: {in_progress}"); + assert_eq!(app.ui.tool_options.crop_shield, before, "{key:?} leaves Show Cropped Area and Classic Mode alone"); + } } } + /// The same plain H and P with a crop in progress are still the crop box's keys, so the test + /// above really reaches the key checks. + #[test] + fn plain_p_toggles_classic_mode_while_a_crop_is_in_progress() { + let mut app = crop_in_progress_app(); + let classic = app.ui.tool_options.crop_shield.classic_mode; + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: Key::P, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE })); + crate::shortcuts::handle(&mut app, &ctx); + assert_eq!(app.ui.tool, Tool::Crop, "P doesn't switch to the Pen tool"); + assert_eq!(app.ui.tool_options.crop_shield.classic_mode, !classic); + } + /// Alt+H, Alt+P and Alt+I are not the crop box's H, P and I (Show Cropped Area, Classic Mode, /// Front Image): egui's `consume_key` ignores an extra ⌥, so the plain-key checks must refuse /// it and leave the press for later handlers. diff --git a/crates/ui-egui/src/tools/crop_size.rs b/crates/ui-egui/src/tools/crop_size.rs index 6320700780..68b0714190 100644 --- a/crates/ui-egui/src/tools/crop_size.rs +++ b/crates/ui-egui/src/tools/crop_size.rs @@ -537,19 +537,30 @@ mod tests { assert!(!keys(&mut app2, &ctx)); } - /// ⇧I is the Eyedropper group's key even with the Crop tool, not Front Image. + /// ⇧I is the Eyedropper group's key even with the Crop tool, not Front Image: with no frame + /// yet, over the untouched default frame and with a crop in progress. #[test] fn shift_i_with_the_crop_tool_switches_to_the_eyedropper() { - let mut app = app(SampleType::U8); - let ratio = app.ui.tool_options.crop_ratio.clone(); - let ctx = egui::Context::default(); - ctx.input_mut(|i| { - // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). - i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); - }); - crate::shortcuts::handle(&mut app, &ctx); - assert_eq!(app.ui.tool, Tool::Eyedropper); - assert_eq!(app.ui.tool_options.crop_ratio, ratio); + for frame in ["none", "default", "in progress"] { + let mut app = app(SampleType::U8); + if frame != "none" { + crate::crop_ui::ensure_frame(&mut app); + assert!(app.ui.crop_rect.is_some() && app.crop.default_frame, "{frame}"); + } + if frame == "in progress" { + app.ui.crop_rect = Some([20.0, 10.0, 120.0, 90.0]); + app.crop.default_frame = false; + } + let ratio = app.ui.tool_options.crop_ratio.clone(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + // Only the event holds ⇧, as with a control-channel `ui.key` (the frame's state lags). + i.events.push(egui::Event::Key { key: egui::Key::I, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + }); + crate::shortcuts::handle(&mut app, &ctx); + assert_eq!(app.ui.tool, Tool::Eyedropper, "{frame}"); + assert_eq!(app.ui.tool_options.crop_ratio, ratio, "{frame}"); + } } /// Committing a W x H x Resolution crop resamples the frame's area to exactly W x H px and sets From a79db76e3045582fb8f56c2309567ef474ad17e3 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 01:48:29 +0100 Subject: [PATCH 043/113] Address review: Alt-letter test also starts a crop in progress Over the untouched default frame crop_shield::keys returns early, so the Alt+H/Alt+P cases checked nothing; only Alt+I reached its key check. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/crop_shield.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/crop_shield.rs b/crates/ui-egui/src/tools/crop_shield.rs index ffc9113ad0..d8b3fba7e1 100644 --- a/crates/ui-egui/src/tools/crop_shield.rs +++ b/crates/ui-egui/src/tools/crop_shield.rs @@ -440,7 +440,7 @@ mod tests { #[test] fn alt_letters_are_not_the_crop_box_keys() { for key in [Key::H, Key::P, Key::I] { - let mut app = crop_app(); + let mut app = crop_in_progress_app(); let (shield, ratio) = (app.ui.tool_options.crop_shield.clone(), app.ui.tool_options.crop_ratio.clone()); let ctx = egui::Context::default(); let alt = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT }; From 51806959efaaf29e47ec56859252b90b06408d27 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 5 Nov 2026 18:00:58 -0800 Subject: [PATCH 044/113] Expect the default cursor inside Free Transform --- crates/ui-egui/src/canvas/snap_ui/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/snap_ui/tests.rs b/crates/ui-egui/src/canvas/snap_ui/tests.rs index 17ba7ca349..dfb239cc0f 100644 --- a/crates/ui-egui/src/canvas/snap_ui/tests.rs +++ b/crates/ui-egui/src/canvas/snap_ui/tests.rs @@ -876,7 +876,7 @@ fn alt_over_the_box_shows_the_reference_point_pointer() { for p in [[55.0, 52.0], [30.0, 30.0], [200.0, 200.0]] { assert_eq!(crate::transform_tool::cursor(&app, &xf, p, alt), Some(egui::CursorIcon::Crosshair), "{p:?}"); } - assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Move)); + assert_eq!(crate::transform_tool::cursor(&app, &xf, [55.0, 52.0], egui::Modifiers::NONE), Some(egui::CursorIcon::Default)); assert_ne!(crate::transform_tool::cursor(&app, &xf, [40.0, 40.0], alt), Some(egui::CursorIcon::Crosshair), "a corner handle stays a handle"); } From 1f1f42182b9be8d8c7ab7d6620cb65056588cc7c Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 14:20:22 +0100 Subject: [PATCH 045/113] Address CodeRabbit review: keep the pattern-scale clamp out of previews transform_fx::work_layer scales a style to the preview's work resolution with scale_effects, so the 1..1000 % clamp turned a 2 % pattern at a quarter of the size into 1 % instead of 0.5 %, and an imported 2000 % pattern into 1000 % at full size. scale_effects_preview scales patterns exactly; Scale Effects and Image Size's Scale Styles keep the clamp. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image_cmds.rs | 30 +++++++++++++------ .../engine/src/cmd/layer_menu_cmds/tests.rs | 27 +++++++++++++++++ crates/ui-egui/src/tools/transform_fx.rs | 23 +++++++++++++- 3 files changed, 70 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 0cac8be4b2..03683f1d00 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -134,9 +134,21 @@ pub(crate) fn reidentify_copied_layers(doc: &mut Document) { } } -/// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style › -/// Scale Effects, and previews that draw a style at a reduced resolution). +/// Scale every size and distance of a style by `k` (Image Size's Scale Styles and Layer Style › +/// Scale Effects), with pattern scales kept within the dialog's 1..1000 %. pub fn scale_effects(fx: &mut Effects, k: f32) { + scale_effects_with(fx, k, true); +} + +/// [`scale_effects`] for a preview that draws a style at a reduced resolution: pattern scales +/// follow `k` exactly, so the preview matches the style it stands for (a 2 % pattern drawn at a +/// quarter of the size is 0.5 %, not the dialog's 1 % minimum). +pub fn scale_effects_preview(fx: &mut Effects, k: f32) { + scale_effects_with(fx, k, false); +} + +fn scale_effects_with(fx: &mut Effects, k: f32, clamp: bool) { + let pattern = |scale: &mut f32| scale_pattern(scale, k, clamp); for e in &mut fx.items { match e { Effect::DropShadow(s) | Effect::InnerShadow(s) => { @@ -153,16 +165,16 @@ pub fn scale_effects(fx: &mut Effects, k: f32) { b.size *= k; b.soften *= k; if let Some(t) = &mut b.texture { - scale_pattern(&mut t.scale, k); + pattern(&mut t.scale); } } - Effect::PatternOverlay { scale, .. } => scale_pattern(scale, k), + Effect::PatternOverlay { scale, .. } => pattern(scale), Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {} } if let Effect::Stroke(s) = e && let FxPaint::Pattern { scale, .. } = &mut s.paint { - scale_pattern(scale, k); + pattern(scale); } } // Effects changed: the preserved PSD block no longer applies. @@ -171,13 +183,13 @@ pub fn scale_effects(fx: &mut Effects, k: f32) { } } -/// Scale a style's pattern scale, kept within the 1..1000 % the Layer Style dialog and the -/// reference application allow (a 10 % pattern reduced to 5 % stays at 1 %). -fn scale_pattern(scale: &mut f32, k: f32) { +/// Scale a style's pattern scale; with `clamp`, kept within the 1..1000 % the Layer Style dialog +/// and the reference application allow (a 10 % pattern reduced to 5 % stays at 1 %). +fn scale_pattern(scale: &mut f32, k: f32, clamp: bool) { let (min, max) = photocraft_doc::effects::PATTERN_SCALE_RANGE; let v = *scale * k; if !v.is_nan() { - *scale = v.clamp(min, max); + *scale = if clamp { v.clamp(min, max) } else { v }; } } diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index b60e984bd0..0dcd7c2333 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -218,6 +218,33 @@ fn scale_effects_keeps_pattern_scales_within_the_dialog_range() { assert_eq!(pattern_scales(&s), (Some(1.0), Some(1.0), Some(1.0))); } +/// Previews at a reduced resolution scale the patterns exactly, past the dialog's range: only +/// commands that store the style clamp them. +#[test] +fn preview_scaling_leaves_pattern_scales_unclamped() { + let s = pattern_styled(2.0); + let mut fx = active(&s).effects.clone(); + crate::image_cmds::scale_effects_preview(&mut fx, 0.25); + let mut clamped = active(&s).effects.clone(); + crate::image_cmds::scale_effects(&mut clamped, 0.25); + let scales = |fx: &photocraft_doc::Effects| { + fx.items + .iter() + .filter_map(|e| match e { + Effect::PatternOverlay { scale, .. } => Some(*scale), + Effect::BevelEmboss(b) => b.texture.as_ref().map(|t| t.scale), + Effect::Stroke(st) => match &st.paint { + photocraft_doc::FxPaint::Pattern { scale, .. } => Some(*scale), + _ => None, + }, + _ => None, + }) + .collect::>() + }; + assert_eq!(scales(&fx), vec![0.005; 3]); + assert_eq!(scales(&clamped), vec![0.01; 3]); +} + #[test] fn image_size_scale_styles_keeps_pattern_scales_within_the_dialog_range() { // 40x30 -> 400x300 with Scale Styles multiplies by 10: 500 % would become 5000 %. diff --git a/crates/ui-egui/src/tools/transform_fx.rs b/crates/ui-egui/src/tools/transform_fx.rs index 0ad888536d..5be2428c85 100644 --- a/crates/ui-egui/src/tools/transform_fx.rs +++ b/crates/ui-egui/src/tools/transform_fx.rs @@ -106,7 +106,7 @@ pub fn work_layer(layer: &Layer, scale: f64) -> Layer { l.vector_mask = None; l.fill_cache = None; l.blend = BlendMode::Normal; - photocraft_engine::image_cmds::scale_effects(&mut l.effects, scale as f32); + photocraft_engine::image_cmds::scale_effects_preview(&mut l.effects, scale as f32); l.effects.reference = l.effects.reference.map(|(x, y)| (x * scale, y * scale)); l } @@ -468,6 +468,27 @@ mod tests { l } + fn pattern_stroke_scale(l: &Layer) -> Option { + l.effects.items.iter().find_map(|e| match e { + Effect::Stroke(StrokeFx { paint: FxPaint::Pattern { scale, .. }, .. }) => Some(*scale), + _ => None, + }) + } + + /// The preview draws a pattern at the work scale exactly: the dialog's 1..1000 % range is for + /// stored styles, so a 2 % pattern at a quarter of the size is 0.5 %, and an imported 2000 % + /// one stays 2000 % at full size, as the committed style draws them. + #[test] + fn work_layer_scales_patterns_past_the_dialog_range() { + let with_pattern = |scale: f32| { + let Effect::Stroke(mut st) = stroke(3.0) else { panic!("a stroke") }; + st.paint = FxPaint::Pattern { name: "Bubbles".into(), id: String::new(), scale }; + styled(vec![Effect::Stroke(st)]) + }; + assert_eq!(pattern_stroke_scale(&work_layer(&with_pattern(0.02), 0.25)), Some(0.005)); + assert_eq!(pattern_stroke_scale(&work_layer(&with_pattern(20.0), 1.0)), Some(20.0)); + } + fn doc() -> Document { Document::new("t", photocraft_geom::Size::new(200, 200), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8) } From c3f825eed5641f1e1e0fa9c81f94c07e2e2f74e6 Mon Sep 17 00:00:00 2001 From: AethelisDEV Date: Fri, 30 Oct 2026 02:09:50 +0300 Subject: [PATCH 046/113] ui-egui: support native file drag and drop on Wayland --- apps/photocraft/src/cursor.rs | 2 +- crates/ui-egui/src/app.rs | 1 - crates/ui-egui/src/app/frame.rs | 2 +- crates/ui-egui/src/canvas/start_screen.rs | 10 +-- crates/ui-egui/src/canvas/tabs.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 7 +- crates/ui-egui/src/file_open.rs | 10 ++- crates/ui-egui/src/notices.rs | 97 +---------------------- 8 files changed, 20 insertions(+), 111 deletions(-) diff --git a/apps/photocraft/src/cursor.rs b/apps/photocraft/src/cursor.rs index 719e8239c9..72548ca638 100644 --- a/apps/photocraft/src/cursor.rs +++ b/apps/photocraft/src/cursor.rs @@ -6,7 +6,7 @@ //! - **macOS**: `NSEvent.mouseLocation`, converted into the content view of our window under it. //! - **X11**: `QueryPointer` on our window (a second, pure-Rust X connection). //! - **Windows**: `GetCursorPos`, relative to the window's client area. -//! - **Wayland**: winit 0.30 delivers no file drops there, so there's nothing to place. +//! - **Wayland**: winit delivers file drops, and egui's last pointer position is used as fallback. //! //! No `unsafe`: every OS call goes through a safe binding. //! diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0a77bbdf3b..5d5d79c7a8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -222,7 +222,6 @@ impl PhotocraftApp { histogram_panel::restore_options(&mut app); // After the saved preferences, which say whether the set was already offered. kys_import::offer_import(&mut app); - notices::wayland_file_drop_guidance(&mut app); // File › Scripts › Script Events Manager: "Start Application". photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication"); app diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index eec74bfcc4..08774a1b7d 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -121,7 +121,7 @@ impl PhotocraftApp { } let dropped = ctx.input(|i| i.raw.dropped_files.clone()); if !dropped.is_empty() { - let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); + let at = self.cursor_pos(ctx); self.open_dropped(ctx, dropped, at); // Files dragged in from another app's window: PhotoCraft comes to the front and takes // the keyboard, as Photoshop does, instead of staying behind the source (#5687). diff --git a/crates/ui-egui/src/canvas/start_screen.rs b/crates/ui-egui/src/canvas/start_screen.rs index 64fbe541e5..b033500d03 100644 --- a/crates/ui-egui/src/canvas/start_screen.rs +++ b/crates/ui-egui/src/canvas/start_screen.rs @@ -274,13 +274,9 @@ fn render_first_run_content(app: &mut PhotocraftApp, ui: &mut egui::Ui, content_ }); } -/// Wayland has no native file drops (winit 0.30, #386), so the hint offers File › Open and paste. -pub(crate) fn start_screen_drop_hint(app: &PhotocraftApp) -> std::borrow::Cow<'static, str> { - if app.services.is_wayland { - crate::i18n::fmt(tl!("Use File › Open, or paste a copied image with {paste}."), &[("paste", &crate::notices::paste_hint(app))]).into() - } else { - tl!("Drop an image or PSD anywhere to open it.").into() - } +/// Hint displayed on the start screen for opening files. +pub(crate) fn start_screen_drop_hint(_app: &PhotocraftApp) -> std::borrow::Cow<'static, str> { + tl!("Drop an image or PSD anywhere to open it.").into() } /// Recent files listed on the Home screen. diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 7389104f6c..27341e8224 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -697,7 +697,7 @@ fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) { if ui.input(|i| i.raw.hovered_files.is_empty()) { return; } - let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx())); + let at = app.cursor_pos(ui.ctx()); let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return }; let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return }; let Some((r, after)) = tabs.iter().find(|(i, _)| *i == slot).map(|&(_, r)| (r, false)).or_else(|| tabs.last().map(|&(_, r)| (r, true))) else { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 661da5d277..9b532d0055 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1409,14 +1409,11 @@ fn clone_overlay_is_clipped_to_a_shaped_tip() { } #[test] -fn wayland_start_screen_hint_does_not_claim_file_drop_works() { +fn wayland_start_screen_hint_offers_file_drop() { let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); let wayland = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { is_wayland: true, ..Default::default() }); assert!(start_screen_drop_hint(&x11).starts_with("Drop")); - // Pasting a copied image file works on Wayland (#338): the hint says how. - let hint = start_screen_drop_hint(&wayland); - assert!(!hint.contains("Drop"), "{hint}"); - assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}"); + assert!(start_screen_drop_hint(&wayland).starts_with("Drop")); } /// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460 diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 865f65d7ef..901629eb02 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -334,16 +334,22 @@ impl PhotocraftApp { } } + /// The pointer position, from the OS cursor service when available, falling back to egui's + /// last-known pointer position (e.g. on Wayland). + pub(crate) fn cursor_pos(&mut self, ctx: &egui::Context) -> Option { + self.services.cursor_pos.as_mut().and_then(|f| f(ctx)).or_else(|| ctx.input(|i| i.pointer.latest_pos())) + } + /// Which of the files called `names`, dropped onto the window just now, are placed on the /// active document's canvas rather than opened, for a shell that reads dropped files itself /// (the browser reads them asynchronously, so the web shell can't hand them to /// [`open_dropped`](Self::open_dropped)). It delivers those through /// [`Services::place_inbox`](crate::Services::place_inbox) and the rest through /// [`Services::inbox`](crate::Services::inbox). The pointer comes from - /// [`Services::cursor_pos`](crate::Services::cursor_pos). As with a desktop canvas drop, a Free + /// [`cursor_pos`](Self::cursor_pos). As with a desktop canvas drop, a Free /// Transform still open is applied first (#4833). pub fn dropped_on_canvas(&mut self, ctx: &egui::Context, names: &[String]) -> Vec { - let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); + let at = self.cursor_pos(ctx); let canvas = self.drop_target(ctx, at) == DropTarget::Canvas; let places: Vec = names.iter().map(|n| canvas && !crate::preset_files_ui::is_preset_file(n)).collect(); if places.contains(&true) { diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index f2025a0d78..899d4cd63f 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -7,7 +7,6 @@ use serde::{Deserialize, Serialize}; use crate::PhotocraftApp; -const WAYLAND_FILE_DROP_DISMISSED: &str = "ui.waylandFileDropGuidanceDismissed"; const CLIPBOARD_UNREADABLE: &str = "Pasting from other apps is unavailable"; /// At most this many notices are kept; older ones drop off. pub const MAX_NOTICES: usize = 3; @@ -74,37 +73,11 @@ fn cap_notices(app: &mut PhotocraftApp) { } /// How to paste in hints: Edit › Paste's effective shortcut (`Ctrl+V`), else the menu path. +#[cfg(test)] pub(crate) fn paste_hint(app: &PhotocraftApp) -> String { crate::shortcuts::shortcut_label(app, "edit.paste").unwrap_or_else(|| tl!("Edit › Paste").to_string()) } -/// Show the Wayland-specific fallback guidance unless the user dismissed it in preferences: winit -/// 0.30 delivers no file drops on Wayland, so point at File › Open, pasting a copied file, and the -/// command that starts this install under XWayland (where drops work), when there is one. -pub fn wayland_file_drop_guidance(app: &mut PhotocraftApp) { - if !app.services.is_wayland - || app.session.prefs().dialogs.get(WAYLAND_FILE_DROP_DISMISSED).and_then(serde_json::Value::as_bool) == Some(true) - || app.ui.notices.iter().any(|notice| notice.dismiss_pref.as_deref() == Some(WAYLAND_FILE_DROP_DISMISSED)) - { - return; - } - // English templates, translated and filled in when drawn, so the notice follows a language change. - let mut lines = vec![ - "Native file drag-and-drop is not supported on Wayland yet. Use File › Open, or copy the image in your file manager and paste it with {paste}." - .to_owned(), - ]; - let mut args = vec![("paste".to_owned(), paste_hint(app))]; - if let Some(command) = &app.services.xwayland_command { - lines.push("To drop files, start PhotoCraft under XWayland: `{command}`".to_owned()); - args.push(("command".to_owned(), command.clone())); - lines.push("Or set Preferences › Performance › Linux display server to X11: PhotoCraft then always starts under XWayland.".to_owned()); - } - let id = post(app, "Native file drag-and-drop is unavailable", lines, false, Some(WAYLAND_FILE_DROP_DISMISSED)); - if let Some(notice) = app.ui.notices.iter_mut().find(|notice| notice.id == id) { - notice.args = args; - } -} - /// A paste found no clipboard to read (#5031). In a Flatpak on Wayland the sandbox hides the /// data-control protocol that other apps' images are read through, and there is no X server to /// fall back to, so the clipboard may hold an image all the same. Say so, and give the command @@ -303,16 +276,11 @@ mod tests { use super::*; use crate::{PhotocraftApp, Services}; use photocraft_engine::Session; - use std::sync::{Arc, Mutex}; #[test] - fn wayland_guidance_follows_language_changes_after_startup() { - let command = Some("WAYLAND_DISPLAY= photocraft".to_string()); - let app = PhotocraftApp::new(Session::new(), Services { is_wayland: true, xwayland_command: command, ..Default::default() }); - let notice = &app.ui.notices[0]; - // the notice keeps its English source text and is translated when drawn (`i18n::t` with - // the current language) - assert_eq!(notice.title, "Native file drag-and-drop is unavailable"); + fn wayland_session_does_not_post_unavailable_notice() { + let app = PhotocraftApp::new(Session::new(), Services { is_wayland: true, ..Default::default() }); + assert!(app.ui.notices.is_empty()); } /// #5031: a paste that can't reach the clipboard (a Flatpak on Wayland) says why and how to @@ -350,39 +318,7 @@ mod tests { notice.lines.iter().map(|line| crate::i18n::fmt(line, &args)).collect::>().join(" ") } - #[test] - fn wayland_guidance_is_only_shown_in_wayland_sessions() { - let command = Some("WAYLAND_DISPLAY= '/apps/Photo Craft.AppImage'".to_string()); - let mut app = PhotocraftApp::new(Session::new(), Services { is_wayland: true, xwayland_command: command, ..Default::default() }); - assert_eq!(app.ui.notices.len(), 1); - assert_eq!(app.ui.notices[0].title, "Native file drag-and-drop is unavailable"); - let guidance = english(&app.ui.notices[0]); - assert!(guidance.contains("not supported on Wayland yet")); - assert!(guidance.contains("File › Open")); - // Pasting a copied file works on Wayland (#338), so the notice offers it. - let paste = paste_hint(&app); - assert!(guidance.contains(&format!("paste it with {paste}")), "{guidance}"); - // The relaunch command is the one for this install (an AppImage here), not a guess. - assert!(guidance.contains("under XWayland: `WAYLAND_DISPLAY= '/apps/Photo Craft.AppImage'`"), "{guidance}"); - assert!(guidance.contains("Linux display server to X11"), "{guidance}"); - assert_eq!(app.ui.notices[0].dismiss_pref.as_deref(), Some(WAYLAND_FILE_DROP_DISMISSED)); - for i in 0..MAX_NOTICES { - post(&mut app, format!("Transient {i}"), Vec::new(), false, None); - } - assert_eq!(app.ui.notices.len(), MAX_NOTICES); - assert!(app.ui.notices.iter().any(|notice| notice.dismiss_pref.is_some())); - let app = PhotocraftApp::new(Session::new(), Services::default()); - assert!(app.ui.notices.is_empty()); - } - - #[test] - fn wayland_guidance_without_an_x_server_does_not_suggest_xwayland() { - let app = PhotocraftApp::new(Session::new(), Services { is_wayland: true, ..Default::default() }); - let guidance = english(&app.ui.notices[0]); - assert!(guidance.contains("File › Open")); - assert!(!guidance.contains("XWayland"), "{guidance}"); - } #[test] fn paste_hint_follows_the_shortcut_and_falls_back_to_the_menu() { @@ -394,31 +330,6 @@ mod tests { assert_eq!(paste_hint(&app), "Edit › Paste"); } - #[test] - fn dismissing_wayland_guidance_persists_across_launches() { - let saved = Arc::new(Mutex::new(None::)); - let load_store = saved.clone(); - let save_store = saved.clone(); - let services = Services { - is_wayland: true, - load_prefs: Some(Box::new(move || load_store.lock().unwrap_or_else(|e| e.into_inner()).clone())), - save_prefs: Some(Box::new(move |text| { - *save_store.lock().unwrap_or_else(|e| e.into_inner()) = Some(text.to_owned()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - let id = app.ui.notices[0].id; - dismiss(&mut app, id); - crate::prefs_ui::tick(&mut app, &egui::Context::default()); - - let services = - Services { is_wayland: true, load_prefs: Some(Box::new(move || saved.lock().unwrap_or_else(|e| e.into_inner()).clone())), ..Default::default() }; - let app = PhotocraftApp::new(Session::new(), services); - assert!(app.ui.notices.is_empty()); - } - #[test] fn preparing_compositor_does_not_warn_about_large_documents() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 3a7a0aaa1eb40437efcd84e6a93b2dbe364606a5 Mon Sep 17 00:00:00 2001 From: Firstbober Date: Tue, 27 Oct 2026 19:26:55 +0100 Subject: [PATCH 047/113] feat: add Indexed Color matte control --- crates/engine/src/cmd/mode_cmds.rs | 45 ++++++++++++++- crates/engine/src/cmd/mode_cmds/tests.rs | 55 +++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 42 ++++++++++++++ .../src/dialogs/filter_dialog/tests.rs | 44 +++++++++++++++ docs/development.md | 9 +++ 5 files changed, 193 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ea6504f7a8..58b959c3f7 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -255,6 +255,32 @@ fn parse_dither(s: &str) -> Option { }) } +fn indexed_matte(s: &Session, p: &Value) -> Result> { + const CMD: &str = "image.mode.indexedColor"; + let rgba = |color: [f32; 4]| [color[0], color[1], color[2]]; + let matte = match p.get("matte") { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(value)) => match value.as_str() { + "none" => return Ok(None), + "white" => [1.0; 3], + "black" => [0.0; 3], + "foreground" => rgba(s.tools.foreground), + "background" => rgba(s.tools.background), + value if value.len() == 7 && value.starts_with('#') => p + .get("matte") + .and_then(parse_color) + .ok_or_else(|| bad(CMD, "matte must be none, foreground, background, white, black or #rrggbb"))? + .map(|v| f32::from(v) / 255.0), + _ => return Err(bad(CMD, "matte must be none, foreground, background, white, black or #rrggbb")), + }, + _ => return Err(bad(CMD, "matte must be a colour string")), + }; + if matte.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) { + return Err(bad(CMD, "matte channels must be finite and in 0..=1")); + } + Ok(Some(matte)) +} + fn indexed_color(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.mode.indexedColor"; let kind = PaletteKind::from_id(str_or(p, "palette", "selective")) @@ -273,8 +299,23 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result { }; let amount = num(p, "amount", 75.0).clamp(0.0, 100.0) / 100.0; let transparency = p.get("transparency").and_then(Value::as_bool).unwrap_or(true); + let matte = indexed_matte(s, p)?; let (pal_len, transparent) = s.edit("Indexed Color", |doc, active| { - let mut px = composite(doc, !transparency); + let mut px = composite(doc, !transparency && matte.is_none()); + if let Some(matte) = matte { + for pixel in &mut px { + let alpha = pixel[3].clamp(0.0, 1.0); + if alpha == 1.0 { + continue; + } + if !transparency || alpha > 0.0 { + for (channel, background) in pixel[..3].iter_mut().zip(matte) { + *channel = *channel * alpha + background * (1.0 - alpha); + } + pixel[3] = 1.0; + } + } + } let has_clear = transparency && px.iter().any(|q| q[3] < 0.5); let mut pal = quantize::build_palette(&px, kind, if has_clear { colors.saturating_sub(1).max(2) } else { colors }, forced).map_err(|e| bad(CMD, e))?; let transparent = if has_clear && pal.len() < 256 { @@ -689,7 +730,7 @@ pub fn specs() -> Vec { "image.mode.indexedColor", "Indexed Color…", ["Image", "Mode"], - r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens)"##, + r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|#rrggbb)"##, |s| mode_is( s, &[ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Duotone, ColorMode::Cmyk, ColorMode::Lab], diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 8f190f445c..0cf1d38bf9 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -247,6 +247,61 @@ fn indexed_color_palettes_and_dithers() { } } +#[test] +fn indexed_matte_blends_edges_without_replacing_clear_pixels() { + for depth in [8, 16, 32] { + for (matte, color) in [ + ("black", [0.0, 0.0, 0.0]), + ("white", [1.0, 1.0, 1.0]), + ("#0000ff", [0.0, 0.0, 1.0]), + ("foreground", [0.0, 0.0, 1.0]), + ("background", [0.0, 1.0, 0.0]), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#0000ff", "background": "#00ff00"})).unwrap(); + paint(&mut s, |x, _| match x { + 0 => [0.0, 1.0, 0.0, 1.0], + 1 => [1.0, 0.0, 0.0, 0.75], + 2 => [1.0, 0.0, 0.0, 0.25], + _ => [0.0; 4], + }); + let source = [1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)); + let expected = source.map(|pixel| [0, 1, 2].map(|i| pixel[i] * pixel[3] + color[i] * (1.0 - pixel[3]))); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap(); + let surface = doc(&s).layers[0].surface().unwrap(); + let edges = [1, 2].map(|x| surface.rgba(x, 0)); + for (edge, expected) in edges.iter().zip(expected) { + for i in 0..3 { + assert!((edge[i] - expected[i]).abs() <= 1.0 / 255.0, "{depth}-bit {matte}: {edge:?} vs {expected:?}"); + } + assert_eq!(edge[3], 1.0); + } + assert_eq!(surface.rgba(3, 0)[3], 0.0, "{matte}: fully transparent pixels stay clear"); + assert_eq!(surface.rgba(0, 0), [0.0, 1.0, 0.0, 1.0]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), source); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), edges); + } + } +} + +#[test] +fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_atomically() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1, "background": "transparent"})).unwrap(); + let before = s.active().unwrap().revision; + for matte in [json!(false), json!(12), json!("#gg0000"), json!("#000000ff"), json!("unknown")] { + assert!(s.execute("image.mode.indexedColor", json!({"matte": matte})).is_err(), "{matte}"); + assert_eq!(s.active().unwrap().revision, before); + assert_eq!(doc(&s).mode, ColorMode::Rgb); + } + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false, "matte": "#0000ff"})).unwrap(); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None); +} + #[test] fn indexed_exact_transparency_and_sources() { // Two colours + transparency: exact palette with a transparent entry. diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index be53034183..47eec78cbf 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -840,6 +840,44 @@ fn replace_color_result(ui: &mut egui::Ui, f: &mut Map) { } } +fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { + let value = fields.get("matte").and_then(Value::as_str).unwrap_or("none"); + let mut choice = if value.starts_with('#') { "custom" } else { value }; + let color = crate::color_picker_ui::parse_hex(value).unwrap_or([1.0; 3]); + let mut changed = false; + let mut pick = false; + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Matte")).color(Tokens::get(ui.ctx()).text_dim)); + changed = crate::widgets::dropdown( + ui, + "indexed-matte", + "Matte", + &mut choice, + &[ + ("none", "None"), + ("foreground", "Foreground Color"), + ("background", "Background Color"), + ("white", "White"), + ("black", "Black"), + ("custom", "Other…"), + ], + 170.0, + ); + if choice == "custom" { + let bytes = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + pick = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), tl!("Matte")).clicked(); + } + }); + let custom = choice == "custom"; + if changed { + let next = if custom { crate::color_picker_ui::hex(color) } else { choice.to_owned() }; + fields.insert("matte".into(), json!(next)); + } + if custom && (changed || pick) { + crate::color_picker_ui::request_field(fields, "matte", &crate::color_picker_ui::title_for("Matte")); + } +} + /// Dialog body for filter commands. pub fn body(ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); @@ -856,6 +894,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { crate::select_mask_view::controls(ui, f); } for p in parse_spec(&spec) { + if cmd == "image.mode.indexedColor" && p.key == "matte" { + indexed_matte_row(ui, f); + continue; + } if zoom_center::owns(&cmd, f) && matches!(p.key.as_str(), "centerX" | "centerY") { if p.key == "centerX" { zoom_center::row(ui, f); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 036b085882..4225bdedf1 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1642,3 +1642,47 @@ fn replace_color_localized_color_clusters() { assert!(px(2)[1] > 0.5, "near the point: shifted to green {:?}", px(2)); assert!(px(38)[0] > 0.9 && px(38)[1] < 0.1, "far away: still red {:?}", px(38)); } + +#[test] +fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + for (choice, blue) in [("Black", 0.0), ("Other…", 0.25)] { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); + session + .edit("fixture", |doc, active| { + let bounds = doc.bounds(); + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().write_region(bounds, &[1.0, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0]); + Ok(()) + }) + .unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap(); + harness.state_mut().ui.dialog_mut(id).unwrap().fields.insert("palette".into(), json!("exact")); + harness.run_steps(3); + harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click(); + harness.run_steps(2); + harness.get_by_label(choice).click(); + harness.run_steps(3); + if choice == "Other…" { + let picker = harness.state().ui.dialogs.last().unwrap().id; + assert_ne!(picker, id); + harness.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#0000ff")); + crate::dialogs::confirm(harness.state_mut(), picker).unwrap(); + harness.state_mut().ui.dialogs.retain(|dialog| dialog.id != picker); + harness.run_steps(3); + } + harness.get_by_label("OK").click(); + harness.run_steps(3); + let doc = &harness.state().session.active().unwrap().doc; + assert_eq!(doc.mode, photocraft_color::ColorMode::Indexed); + let surface = doc.layers[0].surface().unwrap(); + let edge = surface.rgba(0, 0); + assert!((edge[0] - 0.75).abs() <= 1.0 / 255.0 && edge[1] == 0.0 && (edge[2] - blue).abs() <= 1.0 / 255.0 && edge[3] == 1.0, "{choice}: {edge:?}"); + assert_eq!(surface.rgba(1, 0)[3], 0.0); + } +} diff --git a/docs/development.md b/docs/development.md index 1fa912575f..0d907fb97e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -661,6 +661,15 @@ except Place, which is a job that `poll_jobs` steps on the UI thread (a *coopera ## Indexed Color timings +The stock Indexed Color dialog exposes Matte: None, Foreground Color, Background Color, +White, Black and Other… (the shared Color Picker). Automation accepts `matte` as `none`, +`foreground`, `background`, `white`, `black` or `#rrggbb`. A selected matte blends all +partially transparent edges; with Transparency on, fully clear pixels stay transparent. +With Transparency off, the selected matte also fills clear pixels. None retains the existing +hard-edged transparency/default flattening behavior. Indexed conversion retains the document's +ICC profile and encoded RGB sample representation; matte colours are interpreted in the document +RGB coordinate space. This follows Adobe's documented +[Indexed Color conversion options](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-modes/conversion-options-for-indexed-color-images.html). `cargo run --release -p photocraft-engine --example indexed_color_perf -- image.png` measures palette construction, Floyd–Steinberg diffusion, and the complete full-resolution CPU preview path (proxy copy, engine command, result composition; excludes GPU upload/presentation). From b57ec9f729ae55722dc44ae7cd2801ada7821729 Mon Sep 17 00:00:00 2001 From: Firstbober Date: Wed, 28 Oct 2026 11:48:58 +0100 Subject: [PATCH 048/113] fix: preserve indexed matte when picker is canceled --- crates/ui-egui/src/dialogs/color_picker_ui.rs | 10 +++++- crates/ui-egui/src/dialogs/filter_dialog.rs | 9 ++++-- .../src/dialogs/filter_dialog/tests.rs | 31 +++++++++++++++++++ docs/development.md | 8 +++-- 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index 1c0ce157e8..d713fbf9d7 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -271,6 +271,10 @@ fn set_field(f: &mut Map, field: &str, value: Value) -> Result<() /// Opens the Color Picker dialog `id`'s body asked for ([`request`], [`request_field`]), on its /// colour: OK sets that field of the dialog (not the foreground), Cancel leaves it as it was. +/// +/// A dialog can provide `__pickColorDefault` when its field is a non-colour choice that has not +/// yet been replaced by the picked colour. The temporary default seeds the picker without +/// changing the parent field; it is removed before the picker opens. pub fn open_requested(app: &mut PhotocraftApp, id: u64) { let Some(d) = app.ui.dialog_mut(id) else { return }; let (title, field) = match d.fields.remove(REQUEST) { @@ -282,7 +286,11 @@ pub fn open_requested(app: &mut PhotocraftApp, id: u64) { } _ => return, }; - let rgb = field_value(&d.fields, &field).and_then(parse_hex).unwrap_or([0.0; 3]); + let rgb = field_value(&d.fields, &field) + .and_then(parse_hex) + .or_else(|| d.fields.get("__pickColorDefault").and_then(Value::as_str).and_then(parse_hex)) + .unwrap_or([0.0; 3]); + d.fields.remove("__pickColorDefault"); open_for_field(app, &title, rgb, id, &field); } diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 47eec78cbf..4a91bdf81b 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -870,8 +870,13 @@ fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { }); let custom = choice == "custom"; if changed { - let next = if custom { crate::color_picker_ui::hex(color) } else { choice.to_owned() }; - fields.insert("matte".into(), json!(next)); + if custom { + // Keep the previous matte until the picker confirms; the picker uses this only as + // its initial colour when switching from a named matte or None. + fields.insert("__pickColorDefault".into(), json!(crate::color_picker_ui::hex(color))); + } else { + fields.insert("matte".into(), json!(choice.to_owned())); + } } if custom && (changed || pick) { crate::color_picker_ui::request_field(fields, "matte", &crate::color_picker_ui::title_for("Matte")); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 4225bdedf1..db0f606677 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1686,3 +1686,34 @@ fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { assert_eq!(surface.rgba(1, 0)[3], 0.0); } } + +/// Selecting Other… must not replace None until the custom colour picker is confirmed. +#[test] +fn indexed_matte_cancel_keeps_the_previous_choice() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap(); + harness.run_steps(3); + harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click(); + harness.run_steps(2); + harness.get_by_label("Other…").click(); + harness.run_steps(3); + + let picker = harness.state().ui.dialogs.last().expect("custom matte picker").id; + assert_ne!(picker, id); + let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog"); + assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "opening Other… does not commit a matte"); + assert_eq!(harness.state().ui.dialogs.last().unwrap().fields["color"], "#ffffff", "the previous default still seeds the picker"); + + crate::dialogs::cancel(harness.state_mut(), picker).unwrap(); + harness.run_steps(3); + let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog"); + assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "cancel restores the previous None choice"); + assert!(!parent.fields.contains_key("__pickColorDefault")); +} diff --git a/docs/development.md b/docs/development.md index 0d907fb97e..836b68f85f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -662,9 +662,11 @@ except Place, which is a job that `poll_jobs` steps on the UI thread (a *coopera ## Indexed Color timings The stock Indexed Color dialog exposes Matte: None, Foreground Color, Background Color, -White, Black and Other… (the shared Color Picker). Automation accepts `matte` as `none`, -`foreground`, `background`, `white`, `black` or `#rrggbb`. A selected matte blends all -partially transparent edges; with Transparency on, fully clear pixels stay transparent. +White, Black and Other… (the shared Color Picker). Choosing Other… opens the picker without +replacing the current matte; Cancel leaves that choice unchanged, and OK commits the picked +`#rrggbb`. Automation accepts `matte` as `none`, `foreground`, `background`, +`white`, `black` or `#rrggbb`. A selected matte blends all partially transparent +edges; with Transparency on, fully clear pixels stay transparent. With Transparency off, the selected matte also fills clear pixels. None retains the existing hard-edged transparency/default flattening behavior. Indexed conversion retains the document's ICC profile and encoded RGB sample representation; matte colours are interpreted in the document From 2fbec8b533eb018518c4e1c1d680f3b2ead7540f Mon Sep 17 00:00:00 2001 From: Firstbober Date: Sat, 31 Oct 2026 13:51:34 +0100 Subject: [PATCH 049/113] fix: preserve document colours for indexed mattes --- crates/engine/src/cmd/mode_cmds.rs | 37 +++++++++-- crates/engine/src/cmd/mode_cmds/tests.rs | 61 +++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 59 +++++++++++++++++- .../src/dialogs/filter_dialog/tests.rs | 35 ++++++++++- docs/development.md | 13 ++-- 5 files changed, 190 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index 58b959c3f7..df14c063cc 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -9,6 +9,7 @@ use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind}; use photocraft_algo::transform::{Homography, Interp}; +use photocraft_cms::{ColorSpace, Transform}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size}; @@ -255,23 +256,47 @@ fn parse_dither(s: &str) -> Option { }) } +/// Convert a tool colour from the working RGB space into the samples used by the +/// flattened document. RGB and Indexed documents keep their own document profile; +/// grayscale output is a scalar sample replicated into the flattened RGB view. +fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[f32; 3]> { + let destination = match crate::color_cmds::mode_space(doc.mode) { + ColorSpace::Rgb | ColorSpace::Gray => crate::color_cmds::document_profile(doc), + // CMYK and Lab flatten through the compositor's sRGB view on the pinned main path. + _ => crate::color_cmds::composite_profile(doc), + }; + let source = s.color.working(ColorMode::Rgb); + let transform = Transform::new(&source, &destination, s.color.settings.intent(), s.color.settings.bpc) + .map_err(|e| bad("image.mode.indexedColor", format!("cannot convert matte colour: {e}")))?; + let mut output = [0.0; 16]; + transform.eval(&color[..3], &mut output); + let matte = if destination.color_space == ColorSpace::Gray { + [output[0]; 3] + } else { + [output[0], output[1], output[2]] + }; + Ok(matte) +} + fn indexed_matte(s: &Session, p: &Value) -> Result> { const CMD: &str = "image.mode.indexedColor"; - let rgba = |color: [f32; 4]| [color[0], color[1], color[2]]; + let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let matte = match p.get("matte") { None | Some(Value::Null) => return Ok(None), Some(Value::String(value)) => match value.as_str() { "none" => return Ok(None), "white" => [1.0; 3], "black" => [0.0; 3], - "foreground" => rgba(s.tools.foreground), - "background" => rgba(s.tools.background), + "gray" => [128.0 / 255.0; 3], + "netscapeGray" => [192.0 / 255.0; 3], + "foreground" => working_matte_color(s, &doc, s.tools.foreground)?, + "background" => working_matte_color(s, &doc, s.tools.background)?, value if value.len() == 7 && value.starts_with('#') => p .get("matte") .and_then(parse_color) - .ok_or_else(|| bad(CMD, "matte must be none, foreground, background, white, black or #rrggbb"))? + .ok_or_else(|| bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb"))? .map(|v| f32::from(v) / 255.0), - _ => return Err(bad(CMD, "matte must be none, foreground, background, white, black or #rrggbb")), + _ => return Err(bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb")), }, _ => return Err(bad(CMD, "matte must be a colour string")), }; @@ -730,7 +755,7 @@ pub fn specs() -> Vec { "image.mode.indexedColor", "Indexed Color…", ["Image", "Mode"], - r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|#rrggbb)"##, +r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|gray|netscapeGray|#rrggbb; gray=50% Gray (#808080), netscapeGray=Netscape Gray (#c0c0c0))"##, |s| mode_is( s, &[ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Duotone, ColorMode::Cmyk, ColorMode::Lab], diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 0cf1d38bf9..f249f87bca 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -287,6 +287,67 @@ fn indexed_matte_blends_edges_without_replacing_clear_pixels() { } } +#[test] +fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() { + use photocraft_cms::Transform; + + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.color.settings.working_rgb = "display-p3".into(); + s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#3366cc"})).unwrap(); + paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] }); + + let source = s.color.working(ColorMode::Rgb); + let destination = crate::color_cmds::document_profile(doc(&s)); + let transform = Transform::new(&source, &destination, s.color.settings.intent(), s.color.settings.bpc).unwrap(); + let mut converted = [0.0; 16]; + transform.eval(&[0.2, 0.4, 0.8], &mut converted); + let expected = [0.5 + 0.5 * converted[0], 0.5 * converted[1], 0.5 * converted[2]]; + + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "foreground"})).unwrap(); + let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + for (got, want) in edge[..3].iter().zip(expected) { + assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}"); + } + assert_eq!(edge[3], 1.0); + } +} + +#[test] +fn indexed_matte_hex_stays_in_document_rgb_coordinates() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + paint(&mut s, |_| [1.0, 0.0, 0.0, 0.5]); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "#3366cc"})).unwrap(); + let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + let expected = [0.5 + 0.5 * 0.2, 0.5 * 0.4, 0.5 * 0.8]; + for (got, want) in edge[..3].iter().zip(expected) { + assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}"); + } + assert_eq!(edge[3], 1.0); + } +} + +#[test] +fn indexed_matte_named_gray_choices_use_their_document_samples() { + for (matte, channel) in [("gray", 128.0 / 255.0), ("netscapeGray", 192.0 / 255.0)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); + paint(&mut s, |_| [1.0, 0.0, 0.0, 0.5]); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap(); + let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + assert!((edge[0] - 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}"); + for value in edge[1..3].iter() { + assert!((*value - channel * 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}"); + } + assert_eq!(edge[3], 1.0); + } +} + #[test] fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_atomically() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 4a91bdf81b..31a7bbc03d 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -6,6 +6,8 @@ use std::sync::Arc; +use photocraft_cms::{ColorSpace, Transform}; +use photocraft_color::ColorMode; use photocraft_doc::Document; use photocraft_engine::color_cmds::ColorSettings; use photocraft_engine::installed_profiles::InstalledProfile; @@ -429,6 +431,9 @@ fn default_value(app: &PhotocraftApp, command: &str, p: &Param) -> Option /// Command-specific open defaults (ruler straighten, warp from layer, …), not remembered prefs. fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) { + if command == "image.mode.indexedColor" { + indexed_matte_defaults(app, fields); + } if command == "image.rotation.arbitrary" { straighten_defaults(app, fields); } @@ -840,10 +845,58 @@ fn replace_color_result(ui: &mut egui::Ui, f: &mut Map) { } } +const INDEXED_MATTE_FOREGROUND: &str = "__indexedMatteForeground"; +const INDEXED_MATTE_BACKGROUND: &str = "__indexedMatteBackground"; + +/// Resolve a tool colour into the encoded samples used by Indexed Color's matte. +/// +/// The picker and command fields carry document RGB coordinates. Tool swatches are +/// working-RGB coordinates, so only the named tool choices need this conversion here. +fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32; 4]) -> [f32; 3] { + let destination = match photocraft_engine::color_cmds::mode_space(doc.mode) { + ColorSpace::Rgb | ColorSpace::Gray => photocraft_engine::color_cmds::document_profile(doc), + _ => photocraft_engine::color_cmds::composite_profile(doc), + }; + let source = app.session.color.working(ColorMode::Rgb); + let Ok(transform) = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc) else { + return [color[0], color[1], color[2]]; + }; + let mut output = [0.0; 16]; + transform.eval(&color[..3], &mut output); + if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] } +} + +fn indexed_matte_defaults(app: &PhotocraftApp, fields: &mut Map) { + let Some(doc) = app.session.active().map(|state| state.doc.clone()) else { return }; + let foreground = indexed_matte_document_color(app, &doc, app.session.tools.foreground); + let background = indexed_matte_document_color(app, &doc, app.session.tools.background); + fields.insert(INDEXED_MATTE_FOREGROUND.into(), json!(crate::color_picker_ui::hex(foreground))); + fields.insert(INDEXED_MATTE_BACKGROUND.into(), json!(crate::color_picker_ui::hex(background))); +} + +fn indexed_matte_seed(fields: &Map, value: &str) -> [f32; 3] { + match value { + "foreground" => fields + .get(INDEXED_MATTE_FOREGROUND) + .and_then(Value::as_str) + .and_then(crate::color_picker_ui::parse_hex) + .unwrap_or([0.0; 3]), + "background" => fields + .get(INDEXED_MATTE_BACKGROUND) + .and_then(Value::as_str) + .and_then(crate::color_picker_ui::parse_hex) + .unwrap_or([1.0; 3]), + "black" => [0.0; 3], + "gray" => [128.0 / 255.0; 3], + "netscapeGray" => [192.0 / 255.0; 3], + _ => [1.0; 3], + } +} + fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { let value = fields.get("matte").and_then(Value::as_str).unwrap_or("none"); let mut choice = if value.starts_with('#') { "custom" } else { value }; - let color = crate::color_picker_ui::parse_hex(value).unwrap_or([1.0; 3]); + let color = crate::color_picker_ui::parse_hex(value).unwrap_or_else(|| indexed_matte_seed(fields, value)); let mut changed = false; let mut pick = false; ui.horizontal(|ui| { @@ -859,6 +912,8 @@ fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { ("background", "Background Color"), ("white", "White"), ("black", "Black"), + ("gray", "50% Gray"), + ("netscapeGray", "Netscape Gray"), ("custom", "Other…"), ], 170.0, @@ -872,7 +927,7 @@ fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { if changed { if custom { // Keep the previous matte until the picker confirms; the picker uses this only as - // its initial colour when switching from a named matte or None. + // its initial document-encoded colour when switching from a named matte or None. fields.insert("__pickColorDefault".into(), json!(crate::color_picker_ui::hex(color))); } else { fields.insert("matte".into(), json!(choice.to_owned())); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index db0f606677..31786411b7 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -90,6 +90,31 @@ fn display_names_are_not_split_like_camel_case_keys() { assert_eq!(source_label("centerX"), "Center X"); } +#[test] +fn indexed_matte_tool_seeds_use_document_encoded_rgb() { + use photocraft_cms::Transform; + + let mut session = photocraft_engine::Session::new(); + session.color.settings.working_rgb = "display-p3".into(); + session.execute("file.new", json!({"width": 2, "height": 2, "background": "transparent"})).unwrap(); + session.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let mut fields = Map::new(); + indexed_matte_defaults(&app, &mut fields); + + let doc = app.session.active().unwrap().doc.clone(); + let source = app.session.color.working(ColorMode::Rgb); + let destination = photocraft_engine::color_cmds::document_profile(&doc); + let transform = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc).unwrap(); + for (key, input) in [(INDEXED_MATTE_FOREGROUND, [0.2, 0.4, 0.8]), (INDEXED_MATTE_BACKGROUND, [0.8, 0.4, 0.2])] { + let mut output = [0.0; 16]; + transform.eval(&input, &mut output); + let expected = crate::color_picker_ui::hex([output[0], output[1], output[2]]); + assert_eq!(fields.get(key).and_then(Value::as_str), Some(expected.as_str()), "{key}"); + assert_eq!(indexed_matte_seed(&fields, if key == INDEXED_MATTE_FOREGROUND { "foreground" } else { "background" }), crate::color_picker_ui::parse_hex(&expected).unwrap()); + } +} /// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out. #[test] fn black_point_compensation_is_spelled_out() { @@ -1648,7 +1673,12 @@ fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { use egui::accesskit::Role; use egui_kittest::{Harness, kittest::Queryable}; - for (choice, blue) in [("Black", 0.0), ("Other…", 0.25)] { + for (choice, matte) in [ + ("Black", [0.0, 0.0, 0.0]), + ("50% Gray", [128.0 / 255.0; 3]), + ("Netscape Gray", [192.0 / 255.0; 3]), + ("Other…", [0.0, 0.0, 1.0]), + ] { let mut session = photocraft_engine::Session::new(); session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); session @@ -1682,7 +1712,8 @@ fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { assert_eq!(doc.mode, photocraft_color::ColorMode::Indexed); let surface = doc.layers[0].surface().unwrap(); let edge = surface.rgba(0, 0); - assert!((edge[0] - 0.75).abs() <= 1.0 / 255.0 && edge[1] == 0.0 && (edge[2] - blue).abs() <= 1.0 / 255.0 && edge[3] == 1.0, "{choice}: {edge:?}"); + let expected = [0.75 + 0.25 * matte[0], 0.25 * matte[1], 0.25 * matte[2]]; + assert!(edge.iter().zip(expected).all(|(got, want)| (got - want).abs() <= 1.0 / 255.0) && edge[3] == 1.0, "{choice}: {edge:?} vs {expected:?}"); assert_eq!(surface.rgba(1, 0)[3], 0.0); } } diff --git a/docs/development.md b/docs/development.md index 836b68f85f..79ca11f377 100644 --- a/docs/development.md +++ b/docs/development.md @@ -662,11 +662,14 @@ except Place, which is a job that `poll_jobs` steps on the UI thread (a *coopera ## Indexed Color timings The stock Indexed Color dialog exposes Matte: None, Foreground Color, Background Color, -White, Black and Other… (the shared Color Picker). Choosing Other… opens the picker without -replacing the current matte; Cancel leaves that choice unchanged, and OK commits the picked -`#rrggbb`. Automation accepts `matte` as `none`, `foreground`, `background`, -`white`, `black` or `#rrggbb`. A selected matte blends all partially transparent -edges; with Transparency on, fully clear pixels stay transparent. +White, Black, 50% Gray, Netscape Gray and Other… (the shared Color Picker). Choosing Other… +opens the picker without replacing the current matte; Cancel leaves that choice unchanged, and +OK commits the picked `#rrggbb` in document RGB coordinates. Automation accepts `matte` as +`none`, `foreground`, `background`, `white`, `black`, `gray` (50% Gray, encoded +`#808080`), `netscapeGray` (Netscape Gray, encoded `#c0c0c0`) or `#rrggbb`. Foreground/background +tool colours are converted from the +working RGB profile into the document profile before blending. A selected matte blends all +partially transparent edges; with Transparency on, fully clear pixels stay transparent. With Transparency off, the selected matte also fills clear pixels. None retains the existing hard-edged transparency/default flattening behavior. Indexed conversion retains the document's ICC profile and encoded RGB sample representation; matte colours are interpreted in the document From 95c9d3c9eb018452af8c2caa2ba205b0612196db Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:59:22 +0100 Subject: [PATCH 050/113] PDF import: open the first page with PDFium File > Open, drag-and-drop and photocraft-cli now accept PDF files. The first page is rendered with PDFium at 300 dpi (ImportOptions.pdf_dpi), built through the flat importer, and the document resolution keeps the page's print size. The page count is reported; multi-page import is the next step (#2541 / FILE-215-10). - crates/io: pdf_import module, native-only pdfium-render + image deps, import and preflight dispatch (.ai keeps its existing path). - PDFium loads from the executable's folder or PDFIUM_DIR. --- Cargo.lock | 78 +++++++++++++++++++++++++++++++++++++ crates/io/Cargo.toml | 3 ++ crates/io/src/lib.rs | 20 +++++++++- crates/io/src/pdf_import.rs | 76 ++++++++++++++++++++++++++++++++++++ 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 crates/io/src/pdf_import.rs diff --git a/Cargo.lock b/Cargo.lock index 201ca61db0..d3221556bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -874,6 +874,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -1278,6 +1284,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "console_log" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" +dependencies = [ + "log", + "web-sys", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -5008,6 +5034,32 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pdfium-render" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "bytes", + "chrono", + "console_error_panic_hook", + "console_log", + "image", + "itertools 0.15.0", + "js-sys", + "libloading", + "log", + "maybe-owned", + "once_cell", + "utf16string", + "vecmath", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "pem" version = "3.0.6" @@ -5412,9 +5464,11 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", + "image", "imagesize", "lopdf", "miniz_oxide 0.9.1", + "pdfium-render", "photocraft-affinity", "photocraft-algo", "photocraft-cms", @@ -5723,6 +5777,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "piston-float" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" + [[package]] name = "pkg-config" version = "0.3.34" @@ -8205,6 +8265,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" +[[package]] +name = "utf16string" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" +dependencies = [ + "byteorder", +] + [[package]] name = "utf8-zero" version = "0.8.1" @@ -8246,6 +8315,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vecmath" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +dependencies = [ + "piston-float", +] + [[package]] name = "vello_common" version = "0.2.0" diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index dcd86482db..ef151b80cf 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -51,6 +51,9 @@ imagesize = "0.13" resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } +# PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. +pdfium-render = "0.9" +image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 68b1754e61..a828b5ff12 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -65,6 +65,7 @@ pub use ora::losses as ora_losses; pub mod pattern_map; mod pcraft_cache; pub mod pdf; +mod pdf_import; mod pdn; pub use pcraft_cache::PcraftExportCache; pub mod pixels; @@ -513,8 +514,8 @@ pub enum ImportPreflight { /// A flat raster decoded into one image, bounded by /// [`ImportOptions::flat_max_pixel_bytes`]. Flat, - /// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw and `.pcraft` files: this build has - /// no header-only estimate of their pixel memory before decoding. + /// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw, PDF and `.pcraft` files: this + /// build has no header-only estimate of their pixel memory before decoding. Unbounded, } @@ -555,6 +556,10 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } + // PDF (PDFium, native only); `.ai` files are PDFs but keep their existing path. + if has_extension(name, "pdf") || (pdf_import::is_pdf(bytes) && !has_extension(name, "ai")) { + return ImportPreflight::Unbounded; + } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } } @@ -601,6 +606,9 @@ pub struct ImportOptions { /// Decoded-pixel allowance for a flat raster (the buffer a codec decodes into). May lower /// the codec's default cap; 0 uses it. PSD/PSB and layered TIFF use `psd_max_pixel_bytes`. pub flat_max_pixel_bytes: u64, + /// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so + /// the page's print size is preserved. Defaults to 300. + pub pdf_dpi: f32, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -615,6 +623,7 @@ impl Default for ImportOptions { demosaic: raw::Demosaic::default(), psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, + pdf_dpi: 300.0, psd_high_memory_approved: false, psd_approved_estimate: None, } @@ -975,6 +984,13 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) + || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) + { + return pdf_import::import(name, bytes, opts); + } match route(name, bytes) { Route::Pcraft => { let document = photocraft_format::load_from_bytes(bytes)?; diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs new file mode 100644 index 0000000000..ca9d984993 --- /dev/null +++ b/crates/io/src/pdf_import.rs @@ -0,0 +1,76 @@ +//! PDF import: PDFium renders the first page to a PNG and the flat importer builds the document. +//! +//! The page's print size is preserved by setting the document resolution to the import DPI: +//! pixels ÷ DPI × 72 pt is the PDF page's size again. Multi-page import, vector/text extraction +//! and page management are the next steps (see PLAN.md in the local PDF project). + +use crate::{ImportOptions, ImportResult, IoError}; + +/// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. +pub fn is_pdf(bytes: &[u8]) -> bool { + bytes.starts_with(b"%PDF-") +} + +/// Native PDF import is not available in the web build. +#[cfg(target_arch = "wasm32")] +pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result { + Err(IoError::Unsupported("PDF import needs the desktop build".into())) +} + +/// Renders the PDF's first page at [`ImportOptions::pdf_dpi`] and opens it as a flat document. +#[cfg(not(target_arch = "wasm32"))] +pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result { + use image::ImageEncoder; + use pdfium_render::prelude::*; + + let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; + let pdfium = bind()?; + let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page_count = document.pages().len(); + let page = document.pages().get(0).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let width_pt = f64::from(page.width().value); + // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge + // allocation. 20,000 px is far above a poster at 300 dpi. + let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; + let config = PdfRenderConfig::new().set_target_width(target_width); + let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + let rgba = bitmap.as_rgba_bytes(); + let image = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; + // Reuse the well-tested flat importer (the PNG still carries the alpha and colour exactly). + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png) + .write_image(image.as_raw(), width, height, image::ExtendedColorType::Rgba8) + .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; + let mut result = crate::flat::import_flat(name, &png)?; + result.document.resolution_dpi = dpi; + result.document.name = name.to_string(); + if page_count > 1 { + result + .warnings + .push(format!("PDF has {page_count} pages; this build imports page 1 (multi-page import is the next step)")); + } + Ok(result) +} + +/// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). +#[cfg(not(target_arch = "wasm32"))] +fn bind() -> Result { + use pdfium_render::prelude::Pdfium; + + let dir = std::env::var_os("PDFIUM_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| { + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)) + .unwrap_or_default() + }); + let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let bindings = Pdfium::bind_to_library(&library).map_err(|e| { + IoError::Unsupported(format!( + "PDF import: cannot load PDFium from {} ({e}); put pdfium.dll next to the executable or set PDFIUM_DIR", + library.display() + )) + })?; + Ok(Pdfium::new(bindings)) +} From 399cd6ea4de6febaedff5a67f4e009496f233bd6 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:44:49 +0100 Subject: [PATCH 051/113] PDF: import every page as an artboard; export a page per artboard The PDF importer renders each page with PDFium at the import DPI (default 300), lays the pages out side by side and wraps each in an artboard, so a 2-page PDF opens as 2 artboards and saves back as a 2-page PDF (one page per artboard, page-sized, labelled). The import caps at 16 pages for now. The PDF writer now takes a list of pages: shared font/ICC/selection objects, one image per page, and the existing one-page export is the single-page case. Artboards with vector/text layers are rasterised in this path. Tested: artboards_export_as_one_page_each; convert sample.pdf app-multi.pdf (2 pages), rendered back with the probe. --- crates/io/src/pdf.rs | 169 ++++++++++++++++++++++++------------ crates/io/src/pdf/tests.rs | 26 ++++++ crates/io/src/pdf_import.rs | 96 +++++++++++++------- 3 files changed, 204 insertions(+), 87 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index d693ee941b..71c2818b97 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -109,10 +109,12 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { /// A one-page PDF. pub fn print_pdf(page: &PrintPage) -> Vec { - print_pdf_with_vectors(page, "", &selection::SelectionFont::default()) + print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default()) } -fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &selection::SelectionFont) -> Vec { +/// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`. +fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &selection::SelectionFont) -> Vec { + let Some(first) = pages.first() else { return Vec::new() }; let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); let mut obj = |out: &mut Vec, body: &[u8]| { @@ -121,58 +123,78 @@ fn print_pdf_with_vectors(page: &PrintPage, vectors: &str, selection_font: &sele out.extend_from_slice(body); out.extend_from_slice(b"\nendobj\n"); }; - let img = &page.image; - let (pw, ph) = page.paper; - let (x, y, w, h) = page.rect; - let selection_base = if img.icc.is_some() { 8 } else { 7 }; - // 1 catalog, 2 pages, 3 page, 4 contents, 5 image, 6 font, 7 ICC (optional). + let n = pages.len(); + // 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection. + let font_obj = 3 + n * 3; + let icc = first.image.icc.as_ref(); + let icc_obj = icc.map(|_| font_obj + 1); + let selection_base = font_obj + if icc.is_some() { 2 } else { 1 }; obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); - obj(&mut out, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"); - obj( - &mut out, - format!( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 5 0 R >> /Font << /F1 6 0 R /FSelect {selection_base} 0 R >> >> /Contents 4 0 R >>" + let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::>().join(" "); + obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); + for (i, page) in pages.iter().enumerate() { + let page_obj = 3 + i * 3; + let content_obj = page_obj + 1; + let image_obj = page_obj + 2; + let (pw, ph) = page.paper; + let (x, y, w, h) = page.rect; + obj( + &mut out, + format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {pw:.2} {ph:.2}] /Resources << /XObject << /Im0 {image_obj} 0 R >> /Font << /F1 {font_obj} 0 R /FSelect {selection_base} 0 R >> >> /Contents {content_obj} 0 R >>" + ) + .as_bytes(), + ); + // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. + let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"); + if let Some(v) = vectors.get(i) { + content.push_str(v); + } + content.push_str(&marks_ops(page.marks, page.rect)); + let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; + let pad = if any_marks { 30.0 } else { 6.0 }; + if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l))); + } + if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) { + content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d))); + } + let c = deflate(content.as_bytes()); + let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes(); + body.extend_from_slice(&c); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); + let img = &page.image; + let device = match img.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; + let cs = match icc_obj { + Some(obj) => format!("[/ICCBased {obj} 0 R]"), + None => device.to_string(), + }; + let z = deflate(&img.data); + let mut body = format!( + "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", + img.width, + img.height, + z.len() ) - .as_bytes(), - ); - // An explicit white page, so every viewer (and rasteriser) shows paper, not transparency. - let mut content = format!("q 1 g 0 0 {pw:.2} {ph:.2} re f Q\nq {w:.3} 0 0 {h:.3} {x:.3} {y:.3} cm /Im0 Do Q\n"); - content.push_str(vectors); - content.push_str(&marks_ops(page.marks, page.rect)); - let any_marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration; - let pad = if any_marks { 30.0 } else { 6.0 }; - if let Some(l) = page.label.as_deref().filter(|l| !l.is_empty()) { - content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y + h + pad, pdf_string(l))); + .into_bytes(); + body.extend_from_slice(&z); + body.extend_from_slice(b"\nendstream"); + obj(&mut out, &body); } - if let Some(d) = page.description.as_deref().filter(|d| !d.is_empty()) { - content.push_str(&format!("BT /F1 8 Tf 0 g {:.2} {:.2} Td {} Tj ET\n", x, y - pad - 8.0, pdf_string(d))); - } - let c = deflate(content.as_bytes()); - let mut body = format!("<< /Length {} /Filter /FlateDecode >>\nstream\n", c.len()).into_bytes(); - body.extend_from_slice(&c); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); - let device = match img.channels { - 1 => "/DeviceGray", - 4 => "/DeviceCMYK", - _ => "/DeviceRGB", - }; - let cs = if img.icc.is_some() { "[/ICCBased 7 0 R]".to_string() } else { device.to_string() }; - let z = deflate(&img.data); - let mut body = format!( - "<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {cs} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - img.width, - img.height, - z.len() - ) - .into_bytes(); - body.extend_from_slice(&z); - body.extend_from_slice(b"\nendstream"); - obj(&mut out, &body); obj(&mut out, b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"); - if let Some(icc) = &img.icc { + if let Some(icc) = icc { + let device = match first.image.channels { + 1 => "/DeviceGray", + 4 => "/DeviceCMYK", + _ => "/DeviceRGB", + }; let z = deflate(icc); - let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", img.channels, z.len()).into_bytes(); + let mut body = format!("<< /N {} /Alternate {device} /Filter /FlateDecode /Length {} >>\nstream\n", first.image.channels, z.len()).into_bytes(); body.extend_from_slice(&z); body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); @@ -261,9 +283,10 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio (layers, selection_font) } -/// File › Save As / Save a Copy › PDF (#3401): the flattened document, at its print size -/// (pixels ÷ resolution × 72 pt), as a one-page PDF. Layers and transparency are dropped — the -/// warning says so — and the embedded profile travels with the image. +/// File › Save As / Save a Copy › PDF (#3401): the flattened document at its print size +/// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one +/// page for the whole document. Layers and transparency are dropped — the warning says so — and +/// the embedded profile travels with the images. pub fn export(doc: &Document) -> std::result::Result { let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { @@ -277,6 +300,41 @@ pub fn export(doc: &Document) -> std::result::Result { }; let fmt = doc.pixel_format(); let n = fmt.channels().max(1); + let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; + let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); + let artboards = doc.artboards(); + if !artboards.is_empty() { + // One flattened pass of the whole document; each artboard is a crop of it. + let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); + let mut pages = Vec::with_capacity(artboards.len()); + for (_, name, artboard) in &artboards { + let rect = artboard.rect; + let (aw, ah) = (rect.width(), rect.height()); + if aw == 0 || ah == 0 { + continue; + } + let values = surface.read_region(rect); + let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device)); + for px in values.chunks(n) { + let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); + for v in px.iter().take(device) { + data.push(to8(v * a + paper * (1.0 - a))); + } + } + let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() }; + let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi); + pages.push(PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: Some((*name).to_string()) }); + } + if pages.is_empty() { + return Err(IoError::Unsupported("PDF: the document's artboards have no area".into())); + } + let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; + warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len())); + let vectors = vec![String::new(); pages.len()]; + return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); + } let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); // Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing // compositing. Stop at the first unsupported visible layer, since it may depend on the @@ -290,10 +348,8 @@ pub fn export(doc: &Document) -> std::result::Result { } let surface = photocraft_compose::flatten_to_surface(&backdrop, PixelFormat::new(fmt.mode, fmt.sample, true), None); let values = surface.read_region(canvas); - let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; // Straight alpha, composited here over paper: white in RGB/Gray (1 = full light), zero ink // in CMYK (0 = paper). - let paper = if doc.mode == ColorMode::Cmyk { 0.0 } else { 1.0 }; let mut data = Vec::with_capacity((w * h).saturating_mul(device)); for px in values.chunks(n) { let a = px.last().copied().unwrap_or(1.0).clamp(0.0, 1.0); @@ -301,8 +357,7 @@ pub fn export(doc: &Document) -> std::result::Result { data.push(to8(v * a + paper * (1.0 - a))); } } - let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: doc.icc_profile.as_ref().map(|p| p.to_vec()) }; - let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None }; let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; @@ -315,7 +370,7 @@ pub fn export(doc: &Document) -> std::result::Result { vectors.push_str(ops); } vectors.push_str("Q\n"); - Ok(ExportResult { bytes: print_pdf_with_vectors(&page, &vectors, &selection_font), warnings }) + Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font), warnings }) } #[cfg(test)] diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index e745623e41..0364fa6e1a 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -393,3 +393,29 @@ fn leading_newline_stays_in_the_first_selection_span() { let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(content.contains("/ActualText "), "the first span retains the leading newline:\n{content}"); } + +#[test] +fn artboards_export_as_one_page_each() { + use photocraft_doc::{Artboard, Group}; + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let mut d = Document::new("pages.pdf", Size { width: 40, height: 30 }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 72.0; + for (rect, px) in [(Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]), (Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0])] { + let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &px))); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + d.layers.push(Layer::new("Page", LayerContent::Group(group))); + } + let out = export(&d).unwrap(); + check_structure(&out.bytes); + let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); + let pages = parsed.get_pages(); + assert_eq!(pages.len(), 2); + for id in pages.values() { + let page = parsed.get_dictionary(*id).unwrap(); + let media = page.get(b"MediaBox").unwrap().as_array().unwrap(); + let w = media[2].as_float().or_else(|_| media[2].as_i64().map(|v| v as f32)).unwrap(); + let h = media[3].as_float().or_else(|_| media[3].as_i64().map(|v| v as f32)).unwrap(); + assert!((w - 20.0).abs() < 0.01 && (h - 30.0).abs() < 0.01, "page {w}x{h}"); + } + assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2); +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ca9d984993..b35a224dd7 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,10 +1,12 @@ -//! PDF import: PDFium renders the first page to a PNG and the flat importer builds the document. +//! PDF import: PDFium renders every page and each page becomes an artboard. //! -//! The page's print size is preserved by setting the document resolution to the import DPI: -//! pixels ÷ DPI × 72 pt is the PDF page's size again. Multi-page import, vector/text extraction -//! and page management are the next steps (see PLAN.md in the local PDF project). +//! The document resolution is the import DPI, so pixels ÷ DPI × 72 pt is the PDF page's size +//! again. Pages are laid out side by side with a small gap; more than [`MAX_PAGES`] pages are +//! capped so the union canvas stays bounded. use crate::{ImportOptions, ImportResult, IoError}; +use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +use photocraft_geom::Rect; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. pub fn is_pdf(bytes: &[u8]) -> bool { @@ -17,41 +19,75 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result Result { use image::ImageEncoder; use pdfium_render::prelude::*; + /// The most pages one import renders; more would make the union canvas enormous. + const MAX_PAGES: usize = 16; + /// Gap between the artboards, in document pixels. + const GAP: u32 = 80; + let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let page_count = document.pages().len(); - let page = document.pages().get(0).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let width_pt = f64::from(page.width().value); - // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge - // allocation. 20,000 px is far above a poster at 300 dpi. - let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; - let config = PdfRenderConfig::new().set_target_width(target_width); - let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - let rgba = bitmap.as_rgba_bytes(); - let image = image::RgbaImage::from_raw(width, height, rgba) - .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; - // Reuse the well-tested flat importer (the PNG still carries the alpha and colour exactly). - let mut png = Vec::new(); - image::codecs::png::PngEncoder::new(&mut png) - .write_image(image.as_raw(), width, height, image::ExtendedColorType::Rgba8) - .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; - let mut result = crate::flat::import_flat(name, &png)?; - result.document.resolution_dpi = dpi; - result.document.name = name.to_string(); - if page_count > 1 { - result - .warnings - .push(format!("PDF has {page_count} pages; this build imports page 1 (multi-page import is the next step)")); + let total = document.pages().len().max(0) as usize; + let count = total.min(MAX_PAGES); + if count == 0 { + return Err(IoError::Unsupported("PDF has no pages".into())); } - Ok(result) + // Render first, so a malformed later page fails before any document is built. + let mut rendered = Vec::with_capacity(count); + for index in 0..count { + let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let width_pt = f64::from(page.width().value); + // A page can be arbitrarily large; cap the raster so a hostile PDF cannot request a huge + // allocation. 20,000 px is far above a poster at 300 dpi. + let target_width = (width_pt * f64::from(dpi) / 72.0).round().clamp(1.0, 20_000.0) as i32; + let config = PdfRenderConfig::new().set_target_width(target_width); + let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + rendered.push((width, height, bitmap.as_rgba_bytes())); + } + let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); + let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); + let mut doc: Option = None; + let mut x = 0u32; + for (index, (width, height, rgba)) in rendered.into_iter().enumerate() { + // Reuse the well-tested flat importer: the page is composited into the union canvas at its + // artboard position, encoded as PNG, and decoded into a document-wide raster layer. + let mut canvas = image::RgbaImage::new(doc_width, doc_height); + let page = image::RgbaImage::from_raw(width, height, rgba) + .ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; + image::imageops::overlay(&mut canvas, &page, i64::from(x), 0); + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png) + .write_image(canvas.as_raw(), doc_width, doc_height, image::ExtendedColorType::Rgba8) + .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; + let mut result = crate::flat::import_flat(name, &png)?; + let layer = result.document.layers.pop().ok_or_else(|| IoError::Unsupported("PDF: the page decoded to an empty layer".into()))?; + let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + let artboard = Layer::new(format!("Page {}", index + 1), LayerContent::Group(group)); + match &mut doc { + None => { + result.document.layers = vec![artboard]; + doc = Some(result.document); + } + Some(d) => d.layers.push(artboard), + } + x += width + GAP; + } + let mut doc = doc.ok_or_else(|| IoError::Unsupported("PDF has no pages".into()))?; + doc.resolution_dpi = dpi; + doc.name = name.to_string(); + let mut warnings = Vec::new(); + if total > count { + warnings.push(format!("PDF has {total} pages; imported the first {count} (the limit is {MAX_PAGES})")); + } + Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). From c1662d49116d73cf1760d37f7089a232a5159c6e Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:45:00 +0100 Subject: [PATCH 052/113] Export: split nested groups into separate layers/files file.export.layersToFiles gains groups: layers (walk every visible leaf at any depth, not only top-level layers) and naming: layer (bare .png names; duplicates get -2). This is the recursive folder export from the local Program Files build, brought in as the second fix on this branch. Tested: layers_to_files_exports_group_children_as_loose_files (nested subgroup + sibling). --- crates/engine/src/cmd/file_cmds/export.rs | 138 ++++++++++++++++------ crates/engine/src/cmd/file_cmds/tests.rs | 75 ++++++++++++ 2 files changed, 175 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 1f7f9677ff..ef947a5f21 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -20,7 +20,7 @@ pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) export_layers_report_with(s, p, write).map(|report| report.files) } -/// A top-level layer omitted from a successful Layers to Files export. +/// A layer omitted from a successful Layers to Files export. #[derive(Debug, serde::Serialize)] pub struct SkippedExportLayer { /// Session layer id (names need not be unique). @@ -38,14 +38,59 @@ pub struct LayerExportReport { pub skipped: Vec, } -/// The same export as [`export_layers_with`], with an explanation for every omitted top-level -/// layer. Groups export merged, so their children are not separate exports or skips. Encoding -/// and write failures remain errors, never successful skips. Existing numbering is preserved. +/// One layer the export will write or explain, in top-to-bottom order. +enum Planned<'a> { + Export(&'a Layer), + Skip(&'a Layer, &'static str), + Hidden(&'a Layer), +} + +/// Flattens a layer (and, with `split_groups`, its group descendants) into export entries. +fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { + if !layer.visible && visible_only { + plan.push(Planned::Hidden(layer)); + return; + } + if let LayerContent::Group(group) = &layer.content + && split_groups + { + for child in group.children.iter().rev() { + plan_layer(child, split_groups, visible_only, plan); + } + return; + } + if matches!(layer.content, LayerContent::Adjustment(_)) { + plan.push(Planned::Skip(layer, "adjustment layer has no pixels of its own")); + } else { + plan.push(Planned::Export(layer)); + } +} + +/// The same export as [`export_layers_with`], with an explanation for every omitted layer. +/// +/// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one +/// file, as before; `"layers"` walks into the group and exports each visible layer inside it as +/// its own file (top to bottom), so no group is a file of its own. Encoding and write failures +/// remain errors, never successful skips. Existing numbering is preserved. pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); + let split_groups = match p.get("groups").and_then(Value::as_str).unwrap_or("merged") { + "merged" => false, + "layers" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); + } + }; + let layer_names = match p.get("naming").and_then(Value::as_str).map(|s| s.to_ascii_lowercase()).as_deref() { + None | Some("numbered") => false, + Some("layer") => true, + Some(other) => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); + } + }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); @@ -53,48 +98,65 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); + let mut plan = Vec::new(); + for l in doc.layers.iter().rev() { + plan_layer(l, split_groups, visible_only, &mut plan); + } let mut report = LayerExportReport::default(); + let mut used = std::collections::HashSet::new(); // Hidden layers never consumed a filename index; adjustments that pass the visibility // filter did. Keep those filenames stable while reporting both kinds of omission. let mut i = 0usize; - for l in doc.layers.iter().rev() { - if !l.visible && visible_only { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); - continue; - } - let index = i; - i += 1; - if matches!(l.content, LayerContent::Adjustment(_)) { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); - continue; - } - let mut one = (*doc).clone(); - let mut only = l.clone(); - only.visible = true; - only.clipped = false; - one.layers = vec![only]; - if trim { - let mut bounds = Rect::EMPTY; - let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { - let width = band.rect.width() as usize; - for (i, rgba) in band.px.iter().enumerate() { - if rgba[3] > 0.0 && width > 0 { - let x = band.rect.x0 + (i % width) as i32; - let y = band.rect.y0 + (i / width) as i32; - bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); + for entry in plan { + match entry { + Planned::Hidden(l) => report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }), + Planned::Skip(l, reason) => { + i += 1; + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason }); + } + Planned::Export(l) => { + let index = i; + i += 1; + let mut one = (*doc).clone(); + let mut only = l.clone(); + only.visible = true; + only.clipped = false; + one.layers = vec![only]; + if trim { + let mut bounds = Rect::EMPTY; + let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { + let width = band.rect.width() as usize; + for (i, rgba) in band.px.iter().enumerate() { + if rgba[3] > 0.0 && width > 0 { + let x = band.rect.x0 + (i % width) as i32; + let y = band.rect.y0 + (i / width) as i32; + bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); + } + } + Ok(()) + }); + if !bounds.is_empty() && bounds != one.bounds() { + crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; } } - Ok(()) - }); - if !bounds.is_empty() && bounds != one.bounds() { - crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; + + let name = if layer_names { + let base = sanitize(&l.name); + let mut name = format!("{base}.{format}"); + let mut n = 2; + while !used.insert(name.clone()) { + name = format!("{base}-{n}.{format}"); + n += 1; + } + name + } else { + format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)) + }; + let (bytes, _warnings) = encode(&one, &name, save)?; + write(&name, &bytes)?; + report.files.push(name); } } - - let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); - let (bytes, _warnings) = encode(&one, &name, save)?; - write(&name, &bytes)?; - report.files.push(name); } Ok(report) } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 26e172ffd6..7c98907983 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2538,6 +2538,81 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } } +#[test] +fn layers_to_files_exports_group_children_as_loose_files() { + let dir = tmp("layers-groups"); + let mut s = session(8, 8, 8); + s.edit("Group", |doc, _| { + let fmt = doc.pixel_format(); + let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); + let sub = photocraft_doc::Layer::new( + "sub", + photocraft_doc::LayerContent::Group(photocraft_doc::Group { + children: vec![child("c")], + expanded: true, + artboard: None, + frame_stroke: None, + }), + ); + doc.layers.push(photocraft_doc::Layer::new( + "expanded", + photocraft_doc::LayerContent::Group(photocraft_doc::Group { + children: vec![child("a"), child("b"), sub], + expanded: true, + artboard: None, + frame_stroke: None, + }), + )); + Ok(()) + }) + .unwrap(); + let files = |r: &Value| -> Vec { r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() }; + + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); + assert_eq!( + files(&r), + vec![ + join(&dir, "loose_0000_c.png"), + join(&dir, "loose_0001_b.png"), + join(&dir, "loose_0002_a.png"), + join(&dir, "loose_0003_Background.png") + ] + ); + assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); + + // The default still merges the group into one file. + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "merged"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "merged_0000_expanded.png"), join(&dir, "merged_0001_Background.png")]); + + // naming: "layer" writes the bare layer names instead of prefix_index_name. + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "layers", "naming": "layer"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "c.png"), join(&dir, "b.png"), join(&dir, "a.png"), join(&dir, "Background.png")]); + + // A hidden child is skipped with visibleOnly and exported without it. + s.edit("Hide b", |doc, _| { + let group = doc.layers.last_mut().ok_or_else(|| EngineError::Other("no group".into()))?; + let LayerContent::Group(g) = &mut group.content else { return Err(EngineError::Other("not a group".into())) }; + g.children[1].visible = false; + Ok(()) + }) + .unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "visible", "groups": "layers"})).unwrap(); + assert_eq!(files(&r), vec![join(&dir, "visible_0000_c.png"), join(&dir, "visible_0001_a.png"), join(&dir, "visible_0002_Background.png")]); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); + assert_eq!( + files(&r), + vec![ + join(&dir, "all_0000_c.png"), + join(&dir, "all_0001_b.png"), + join(&dir, "all_0002_a.png"), + join(&dir, "all_0003_Background.png") + ] + ); + + // An unknown mode is rejected instead of silently merging. + assert!(s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "folders"})).is_err()); +} + #[test] fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { let mut s = session(4, 4, 8); From 3a1b41f0c65873c845e9a190f05d9dd9f02f2666 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 13:55:45 +0100 Subject: [PATCH 053/113] PDF: bound the import canvas The importer budgets the per-page raster (100 M px) and the artboard strip (200 M px): an oversized page is scaled down, and pages that would exceed the strip budget are skipped with a warning, instead of allocating a multi-gigabyte union canvas. The page-count cap stays 16. Also applies cargo fmt to the new PDF code and the export-recursion test. --- crates/engine/src/cmd/file_cmds/tests.rs | 21 ++-------- crates/io/src/pdf.rs | 9 +++- crates/io/src/pdf_import.rs | 52 ++++++++++++++++++------ 3 files changed, 50 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 7c98907983..6a14a7542b 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2547,12 +2547,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); let sub = photocraft_doc::Layer::new( "sub", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { - children: vec![child("c")], - expanded: true, - artboard: None, - frame_stroke: None, - }), + photocraft_doc::LayerContent::Group(photocraft_doc::Group { children: vec![child("c")], expanded: true, artboard: None, frame_stroke: None }), ); doc.layers.push(photocraft_doc::Layer::new( "expanded", @@ -2571,12 +2566,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); assert_eq!( files(&r), - vec![ - join(&dir, "loose_0000_c.png"), - join(&dir, "loose_0001_b.png"), - join(&dir, "loose_0002_a.png"), - join(&dir, "loose_0003_Background.png") - ] + vec![join(&dir, "loose_0000_c.png"), join(&dir, "loose_0001_b.png"), join(&dir, "loose_0002_a.png"), join(&dir, "loose_0003_Background.png")] ); assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); @@ -2601,12 +2591,7 @@ fn layers_to_files_exports_group_children_as_loose_files() { let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); assert_eq!( files(&r), - vec![ - join(&dir, "all_0000_c.png"), - join(&dir, "all_0001_b.png"), - join(&dir, "all_0002_a.png"), - join(&dir, "all_0003_Background.png") - ] + vec![join(&dir, "all_0000_c.png"), join(&dir, "all_0001_b.png"), join(&dir, "all_0002_a.png"), join(&dir, "all_0003_Background.png")] ); // An unknown mode is rejected instead of silently merging. diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 71c2818b97..55e70d0318 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -325,7 +325,14 @@ pub fn export(doc: &Document) -> std::result::Result { } let image = PrintImage { width: aw, height: ah, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(aw) * 72.0 / dpi, f64::from(ah) * 72.0 / dpi); - pages.push(PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: Some((*name).to_string()) }); + pages.push(PrintPage { + paper: (pw, ph), + image, + rect: (0.0, 0.0, pw, ph), + marks: Marks::default(), + description: None, + label: Some((*name).to_string()), + }); } if pages.is_empty() { return Err(IoError::Unsupported("PDF: the document's artboards have no area".into())); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index b35a224dd7..7bd5f76df9 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -38,19 +38,47 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result MAX_PAGE_PIXELS { + let scale = (MAX_PAGE_PIXELS / area).sqrt(); + target_width = (target_width * scale).max(1.0); + } + let config = PdfRenderConfig::new().set_target_width(target_width as i32); let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // Stop before the strip exceeds the union budget; the pages rendered so far stay. + let next_width = union_width + u64::from(width) + if rendered.is_empty() { 0 } else { u64::from(GAP) }; + let next_height = union_height.max(u64::from(height)); + if next_width.saturating_mul(next_height) > MAX_UNION_PIXELS { + break; + } + union_width = next_width; + union_height = next_height; rendered.push((width, height, bitmap.as_rgba_bytes())); } + let count = rendered.len(); + if count == 0 { + return Err(IoError::Unsupported("PDF pages are too large to import; reduce the DPI".into())); + } let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); let mut doc: Option = None; @@ -59,8 +87,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result Result count { - warnings.push(format!("PDF has {total} pages; imported the first {count} (the limit is {MAX_PAGES})")); + let reason = if total > MAX_PAGES { "the page limit is 16" } else { "the rest would make the import canvas too large" }; + warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } @@ -95,12 +124,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result Result { use pdfium_render::prelude::Pdfium; - let dir = std::env::var_os("PDFIUM_DIR").map(std::path::PathBuf::from).unwrap_or_else(|| { - std::env::current_exe() - .ok() - .and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)) - .unwrap_or_default() - }); + let dir = std::env::var_os("PDFIUM_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); let library = Pdfium::pdfium_platform_library_name_at_path(&dir); let bindings = Pdfium::bind_to_library(&library).map_err(|e| { IoError::Unsupported(format!( From 94a4998208f9b5528c4f038010d5bcbcf3a3299a Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:53:46 +0100 Subject: [PATCH 054/113] PDF: address CodeRabbit review (cancellation, budgets, labels, export edges) - Cancellation: the importer and the PDF writer take the Interrupt and check between pages. - Physical size: the effective DPI keeps each page print size when budgets cap the raster. - Oversized pages: final dimensions are checked before rendering. - Memory: pages go straight into layer surfaces; the aggregate pixel estimate is admitted. - Labels: /PageLabels (UTF-16BE) carry artboard names; no label is drawn outside the media box. - Metadata: the artboard export warns when free-form text metadata is dropped. - Export: hidden groups report their children; non-string modes are rejected; case-insensitive filename collisions are suffixed. - Dispatch: a recognised raster renamed .pdf goes to the flat importer; .ai keeps its path. - Platform: the PDFium recovery message names the actual library. --- crates/engine/src/cmd/file_cmds/export.rs | 50 +++++-- crates/io/src/lib.rs | 14 +- crates/io/src/pdf.rs | 37 ++++- crates/io/src/pdf/tests.rs | 36 ++--- crates/io/src/pdf_import.rs | 167 ++++++++++++---------- 5 files changed, 192 insertions(+), 112 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index ef947a5f21..629b7aad82 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -49,6 +49,12 @@ enum Planned<'a> { fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { if !layer.visible && visible_only { plan.push(Planned::Hidden(layer)); + // A hidden group takes its descendants with it; report each so the omission is complete. + if split_groups && let LayerContent::Group(group) = &layer.content { + for child in group.children.iter().rev() { + plan_hidden(child, plan); + } + } return; } if let LayerContent::Group(group) = &layer.content @@ -66,6 +72,16 @@ fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan } } +/// Marks `layer` and all of its descendants as hidden, top to bottom. +fn plan_hidden<'a>(layer: &'a Layer, plan: &mut Vec>) { + plan.push(Planned::Hidden(layer)); + if let LayerContent::Group(group) = &layer.content { + for child in group.children.iter().rev() { + plan_hidden(child, plan); + } + } +} + /// The same export as [`export_layers_with`], with an explanation for every omitted layer. /// /// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one @@ -77,19 +93,27 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); - let split_groups = match p.get("groups").and_then(Value::as_str).unwrap_or("merged") { - "merged" => false, - "layers" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); - } + let split_groups = match p.get("groups") { + None => false, + Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { + "merged" => false, + "layers" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); + } + }, + Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "groups must be a string: \"merged\" or \"layers\"".into() }), }; - let layer_names = match p.get("naming").and_then(Value::as_str).map(|s| s.to_ascii_lowercase()).as_deref() { - None | Some("numbered") => false, - Some("layer") => true, - Some(other) => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); - } + let layer_names = match p.get("naming") { + None => false, + Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { + "numbered" => false, + "layer" => true, + other => { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); + } + }, + Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "naming must be a string: \"numbered\" or \"layer\"".into() }), }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. @@ -144,7 +168,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let base = sanitize(&l.name); let mut name = format!("{base}.{format}"); let mut n = 2; - while !used.insert(name.clone()) { + while !used.insert(name.to_ascii_lowercase()) { name = format!("{base}-{n}.{format}"); n += 1; } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a828b5ff12..1f69b40ea4 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -556,8 +556,9 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } - // PDF (PDFium, native only); `.ai` files are PDFs but keep their existing path. - if has_extension(name, "pdf") || (pdf_import::is_pdf(bytes) && !has_extension(name, "ai")) { + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return ImportPreflight::Unbounded; } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } @@ -978,6 +979,7 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { if is_psd_input(name, bytes) { return Route::NamedPsd; } +<<<<<<< HEAD Route::Flat } @@ -990,6 +992,12 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts); +======= + // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized + // raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + return pdf_import::import(name, bytes, opts, ctl); +>>>>>>> 806c53fd2 (PDF: address CodeRabbit review (cancellation, budgets, labels, export edges)) } match route(name, bytes) { Route::Pcraft => { @@ -1170,7 +1178,7 @@ fn export_stages_with_renderer( return Ok(res.into()); } if ext == "pdf" { - let mut res = pdf::export(doc)?; + let mut res = pdf::export(doc, ctl)?; if let Some(r) = renderer { res.warnings.push("PDF export uses CPU compositor; GPU rendering applies to flat formats".into()); res.warnings.extend(r.drain_diagnostics()); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 55e70d0318..4317784e50 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -44,6 +44,8 @@ pub struct PrintPage { pub marks: Marks, pub description: Option, pub label: Option, + /// The page's name in the PDF `/PageLabels` tree (Unicode-capable; not drawn on the page). + pub page_label: Option, } pub(super) fn pdf_string(s: &str) -> String { @@ -62,6 +64,16 @@ pub(super) fn pdf_string(s: &str) -> String { o } +/// A PDF text string with UTF-16BE hex (the Unicode-capable form, byte-order mark included). +fn pdf_unicode_string(s: &str) -> String { + let mut o = String::from("'); + o +} + fn deflate(data: &[u8]) -> Vec { // Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static // Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger @@ -124,12 +136,14 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel out.extend_from_slice(b"\nendobj\n"); }; let n = pages.len(); + let selections_on = pages.iter().any(|p| p.page_label.is_some()); // 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection. let font_obj = 3 + n * 3; let icc = first.image.icc.as_ref(); let icc_obj = icc.map(|_| font_obj + 1); let selection_base = font_obj + if icc.is_some() { 2 } else { 1 }; - obj(&mut out, b"<< /Type /Catalog /Pages 2 0 R >>"); + let labels_obj = selections_on.then_some(selection_base + 1); + obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes()); let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::>().join(" "); obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); for (i, page) in pages.iter().enumerate() { @@ -202,6 +216,15 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel for body in selection_font.objects(selection_base) { obj(&mut out, &body); } + if labels_obj.is_some() { + let nums = pages + .iter() + .enumerate() + .filter_map(|(i, p)| p.page_label.as_deref().filter(|l| !l.is_empty()).map(|l| format!("{i} << /P {} >>", pdf_unicode_string(l)))) + .collect::>() + .join(" "); + obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes()); + } let xref = out.len(); out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); for o in &offsets { @@ -287,7 +310,8 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio /// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one /// page for the whole document. Layers and transparency are dropped — the warning says so — and /// the embedded profile travels with the images. -pub fn export(doc: &Document) -> std::result::Result { +pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result::Result { + ctl.check().map_err(|_| IoError::Cancelled)?; let (w, h) = (usize::try_from(doc.size.width).unwrap_or(0), usize::try_from(doc.size.height).unwrap_or(0)); if w == 0 || h == 0 { return Err(IoError::Unsupported("PDF needs a document with non-zero width and height; nothing was written".into())); @@ -310,6 +334,7 @@ pub fn export(doc: &Document) -> std::result::Result { let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); let mut pages = Vec::with_capacity(artboards.len()); for (_, name, artboard) in &artboards { + ctl.check().map_err(|_| IoError::Cancelled)?; let rect = artboard.rect; let (aw, ah) = (rect.width(), rect.height()); if aw == 0 || ah == 0 { @@ -331,7 +356,8 @@ pub fn export(doc: &Document) -> std::result::Result { rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, - label: Some((*name).to_string()), + label: None, + page_label: Some((*name).to_string()), }); } if pages.is_empty() { @@ -339,6 +365,9 @@ pub fn export(doc: &Document) -> std::result::Result { } let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; warnings.push(format!("PDF exported {} artboards as {} pages; vector/text layers on artboards are rasterised", artboards.len(), pages.len())); + if !doc.metadata.text.is_empty() { + warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); + } let vectors = vec![String::new(); pages.len()]; return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); } @@ -366,7 +395,7 @@ pub fn export(doc: &Document) -> std::result::Result { } let image = PrintImage { width: doc.size.width, height: doc.size.height, channels: device, data, icc: icc.clone() }; let (pw, ph) = (f64::from(doc.size.width) * 72.0 / dpi, f64::from(doc.size.height) * 72.0 / dpi); - let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None }; + let page = PrintPage { paper: (pw, ph), image, rect: (0.0, 0.0, pw, ph), marks: Marks::default(), description: None, label: None, page_label: None }; let mut warnings = vec!["PDF was saved flattened: layers, masks-as-editable and transparency are not preserved (#3401)".into()]; if !doc.metadata.text.is_empty() { warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 0364fa6e1a..30c38a2698 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -4,7 +4,7 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::{Layer, LayerContent, Size}; use photocraft_geom::Rect; -use photocraft_raster::Surface; +use photocraft_raster::{Interrupt, Surface}; fn solid(fmt: PixelFormat, x0: i32, y0: i32, x1: i32, y1: i32, px: &[f32]) -> Surface { let mut s = Surface::new(fmt); @@ -68,7 +68,7 @@ fn check_structure(pdf: &[u8]) { #[test] fn a_flat_rgb_document_saves_as_one_page_pdf() { let d = doc(ColorMode::Rgb); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); let pdf = &out.bytes; check_structure(pdf); assert!(has(pdf, "/MediaBox [0 0 4.00 2.00]"), "page = image size at 72 pt/in"); @@ -85,7 +85,7 @@ fn layers_composite_over_white_before_the_page() { let mut d = doc(ColorMode::Rgb); let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers.push(Layer::new("Half red", LayerContent::Raster(solid(fmt, 1, 0, 3, 2, &[1.0, 0.0, 0.0, 0.5])))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); let img = stream_after(&out.bytes, "/Subtype /Image"); // Pixels 1-2 of row 0: 0.5 red over white = (1.0, 0.5, 0.5); elsewhere plain white. assert_eq!(&img[3..6], &[255, 128, 128], "the blend lands: {:?}", &img[3..6]); @@ -102,7 +102,7 @@ fn topmost_solid_shape_is_exported_as_a_vector_path() { ..Default::default() }; d.layers.push(Layer::new("Shape", LayerContent::Shape(shape))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -128,7 +128,7 @@ fn topmost_text_layer_is_exported_with_selectable_text_and_vector_outlines() { let baseline = layout.lines.get(cluster.line).expect("a line").baseline; let origin = text.transform.apply(photocraft_geom::Point::new(f64::from(cluster.x), f64::from(baseline))); d.layers.push(Layer::new("Text", LayerContent::Text(text))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -159,7 +159,7 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() { d.layers.push(Layer::new("Shape", LayerContent::Shape(shape))); let text = TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }; d.layers.push(Layer::new("Text", LayerContent::Text(text))); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let content = stream_after(&out.bytes, "/Contents 4 0 R"); let content = String::from_utf8(content).unwrap(); @@ -173,10 +173,10 @@ fn topmost_shape_and_text_layers_are_both_exported_as_vectors() { #[test] fn greyscale_and_cmyk_pages_keep_their_channels() { - let g = export(&doc(ColorMode::Grayscale)).unwrap(); + let g = export(&doc(ColorMode::Grayscale), &Interrupt::NONE).unwrap(); assert!(has(&g.bytes, "/ColorSpace /DeviceGray"), "gray is DeviceGray"); assert_eq!(stream_after(&g.bytes, "/Subtype /Image"), vec![255; 4 * 2], "one sample per pixel"); - let c = export(&doc(ColorMode::Cmyk)).unwrap(); + let c = export(&doc(ColorMode::Cmyk), &Interrupt::NONE).unwrap(); assert!(has(&c.bytes, "/ColorSpace /DeviceCMYK"), "cmyk is DeviceCMYK"); assert_eq!(stream_after(&c.bytes, "/Subtype /Image"), vec![0; 4 * 2 * 4], "zero ink over the whole page"); } @@ -188,7 +188,7 @@ fn the_page_measures_at_the_document_resolution() { let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); d.layers = vec![Layer::new("Paper", LayerContent::Raster(solid(fmt, 0, 0, 300, 150, &[1.0, 1.0, 1.0, 1.0])))]; d.resolution_dpi = 300.0; - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "/MediaBox [0 0 72.00 36.00]"), "300 px at 300 dpi is one inch"); } @@ -196,7 +196,7 @@ fn the_page_measures_at_the_document_resolution() { fn an_embedded_profile_travels_as_iccbased() { let mut d = doc(ColorMode::Rgb); d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8])); - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); assert!(has(&out.bytes, "[/ICCBased 7 0 R]"), "the image refers to the profile"); assert_eq!(stream_after(&out.bytes, "/N 3 /Alternate"), vec![1, 2, 3, 4, 5, 6, 7, 8], "the profile bytes survive"); } @@ -204,7 +204,7 @@ fn an_embedded_profile_travels_as_iccbased() { #[test] fn other_modes_are_refused_with_an_actionable_error() { let d = doc(ColorMode::Lab); - let e = export(&d).unwrap_err().to_string(); + let e = export(&d, &Interrupt::NONE).unwrap_err().to_string(); assert!(e.contains("RGB") && e.contains("Mode"), "{e}"); assert!(crate::export(&d, "x.pdf", &crate::ExportOptions::default()).is_err()); } @@ -226,7 +226,7 @@ fn unicode_text_over_a_photo_extracts_through_a_pdf_reader() { ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let parsed = lopdf::Document::load_mem(&pdf).unwrap(); assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), text); assert!(has(&pdf, "/Subtype /Image")); @@ -266,7 +266,7 @@ fn text_with_compositing_or_a_profile_stays_in_the_raster_backdrop() { _ => d.icc_profile = Some(std::sync::Arc::new(vec![1, 2, 3, 4])), } d.layers.push(layer); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(!content.contains("/ActualText"), "case {case} must retain the raster composite"); assert!(stream_after(&pdf, "/Subtype /Image").iter().any(|v| *v != 255), "case {case} must retain visible text"); @@ -304,7 +304,7 @@ fn text_outside_the_vector_prefix_does_not_consume_the_selection_font() { "Top text", LayerContent::Text(TextLayer { text: "Hi".into(), size_pt: 12.0, color: photocraft_color::Color::rgb(0.0, 1.0, 0.0), ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; let parsed = lopdf::Document::load_mem(&pdf).unwrap(); assert_eq!(parsed.extract_text(&[1]).unwrap().trim(), "Hi", "case {case}: only the top text is selectable"); let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); @@ -355,7 +355,7 @@ fn a_text_layer_refused_at_emission_keeps_the_upper_vectors_and_stays_raster() { ..Default::default() }), )); - let pdf = export(&d).unwrap().bytes; + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; check_structure(&pdf); let content = String::from_utf8(stream_after(&pdf, "/Contents 4 0 R")).unwrap(); assert!(content.contains("/ActualText "), "the first span retains the leading newline:\n{content}"); } @@ -405,7 +405,7 @@ fn artboards_export_as_one_page_each() { let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; d.layers.push(Layer::new("Page", LayerContent::Group(group))); } - let out = export(&d).unwrap(); + let out = export(&d, &Interrupt::NONE).unwrap(); check_structure(&out.bytes); let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); let pages = parsed.get_pages(); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 7bd5f76df9..58ec5fa70b 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,12 +1,14 @@ //! PDF import: PDFium renders every page and each page becomes an artboard. //! -//! The document resolution is the import DPI, so pixels ÷ DPI × 72 pt is the PDF page's size -//! again. Pages are laid out side by side with a small gap; more than [`MAX_PAGES`] pages are -//! capped so the union canvas stays bounded. +//! The document resolution is chosen so the page's physical size is preserved even when the +//! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side +//! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. use crate::{ImportOptions, ImportResult, IoError}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; -use photocraft_geom::Rect; +use photocraft_geom::{Rect, Size}; +use photocraft_raster::{Interrupt, Surface}; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. pub fn is_pdf(bytes: &[u8]) -> bool { @@ -15,22 +17,24 @@ pub fn is_pdf(bytes: &[u8]) -> bool { /// Native PDF import is not available in the web build. #[cfg(target_arch = "wasm32")] -pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions) -> Result { +pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result { Err(IoError::Unsupported("PDF import needs the desktop build".into())) } -/// Renders every PDF page at [`ImportOptions::pdf_dpi`] and opens it as one artboard per page. +/// Renders every PDF page and opens it as one artboard per page. #[cfg(not(target_arch = "wasm32"))] -pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result { - use image::ImageEncoder; +pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { use pdfium_render::prelude::*; - /// The most pages one import renders; more would make the union canvas enormous. + /// The most pages one import renders. const MAX_PAGES: usize = 16; /// Gap between the artboards, in document pixels. const GAP: u32 = 80; + /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. + const MAX_PAGE_PIXELS: f64 = 100_000_000.0; + const MAX_UNION_PIXELS: u64 = 200_000_000; - let dpi = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { opts.pdf_dpi } else { 300.0 }; + let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let total = document.pages().len().max(0) as usize; @@ -38,87 +42,101 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result MAX_PAGE_PIXELS { - let scale = (MAX_PAGE_PIXELS / area).sqrt(); - target_width = (target_width * scale).max(1.0); - } - let config = PdfRenderConfig::new().set_target_width(target_width as i32); - let bitmap = page.render_with_config(&config).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - // Stop before the strip exceeds the union budget; the pages rendered so far stay. - let next_width = union_width + u64::from(width) + if rendered.is_empty() { 0 } else { u64::from(GAP) }; - let next_height = union_height.max(u64::from(height)); - if next_width.saturating_mul(next_height) > MAX_UNION_PIXELS { - break; - } - union_width = next_width; - union_height = next_height; - rendered.push((width, height, bitmap.as_rgba_bytes())); + sizes.push((w, h)); } - let count = rendered.len(); - if count == 0 { - return Err(IoError::Unsupported("PDF pages are too large to import; reduce the DPI".into())); + let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); + let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); + let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); + if doc_width == 0 || doc_height == 0 { + return Err(IoError::Unsupported("PDF pages have no area".into())); } - let doc_width = rendered.iter().map(|(w, _, _)| *w).sum::() + GAP * (count as u32 - 1); - let doc_height = rendered.iter().map(|(_, h, _)| *h).max().unwrap_or(1); - let mut doc: Option = None; + // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. + let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); + let estimate = (page_pixels * 4.0 * 2.0) as u64; + if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { + return Err(IoError::Unsupported(format!( + "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", + estimate >> 20, + opts.flat_max_pixel_bytes >> 20 + ))); + } + let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); + doc.resolution_dpi = dpi as f32; let mut x = 0u32; - for (index, (width, height, rgba)) in rendered.into_iter().enumerate() { - // Reuse the well-tested flat importer: the page is composited into the union canvas at its - // artboard position, encoded as PNG, and decoded into a document-wide raster layer. - let mut canvas = image::RgbaImage::new(doc_width, doc_height); - let page = - image::RgbaImage::from_raw(width, height, rgba).ok_or_else(|| IoError::Unsupported("PDF: the rendered bitmap does not match its buffer".into()))?; - image::imageops::overlay(&mut canvas, &page, i64::from(x), 0); - let mut png = Vec::new(); - image::codecs::png::PngEncoder::new(&mut png) - .write_image(canvas.as_raw(), doc_width, doc_height, image::ExtendedColorType::Rgba8) - .map_err(|e| IoError::Unsupported(format!("PDF: encoding the rendered page: {e}")))?; - let mut result = crate::flat::import_flat(name, &png)?; - let layer = result.document.layers.pop().ok_or_else(|| IoError::Unsupported("PDF: the page decoded to an empty layer".into()))?; + for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { + ctl.check().map_err(|_| IoError::Cancelled)?; + let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; + let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; + // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the + // union check runs; reject the final dimensions up front. + if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { + return Err(IoError::Unsupported(format!( + "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", + index + 1, + target_width, + target_height + ))); + } + let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let bitmap = + page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; + let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // The page's pixels go straight into the document-wide layer surface: no full-strip + // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let rgba = bitmap.as_rgba_bytes(); + let mut data = Vec::with_capacity(rgba.len()); + for chunk in rgba.as_chunks::<4>().0 { + for &v in &chunk[..3] { + data.push(f32::from(v) / 255.0); + } + data.push(f32::from(chunk[3]) / 255.0); + } + surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); + let layer = Layer::new(format!("Page {}", index + 1), LayerContent::Raster(surface)); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - let artboard = Layer::new(format!("Page {}", index + 1), LayerContent::Group(group)); - match &mut doc { - None => { - result.document.layers = vec![artboard]; - doc = Some(result.document); - } - Some(d) => d.layers.push(artboard), - } + doc.layers.push(Layer::new(format!("Page {}", index + 1), LayerContent::Group(group))); x += width + GAP; + ctl.progress((index + 1) as f32 / count as f32); } - let mut doc = doc.ok_or_else(|| IoError::Unsupported("PDF has no pages".into()))?; - doc.resolution_dpi = dpi; - doc.name = name.to_string(); let mut warnings = Vec::new(); if total > count { - let reason = if total > MAX_PAGES { "the page limit is 16" } else { "the rest would make the import canvas too large" }; + let reason = if count < total.min(MAX_PAGES) { "the rest would make the import canvas too large" } else { "the page limit is 16" }; warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// The highest DPI not above `requested` that keeps every page and the artboard strip within +/// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. +#[cfg(not(target_arch = "wasm32"))] +fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, max_union: u64) -> f64 { + let mut dpi = requested; + for (w, h) in sizes { + dpi = dpi.min(72.0 * (max_page / (w * h)).sqrt()); + } + let n = sizes.len() as f64; + let sum_w: f64 = sizes.iter().map(|(w, _)| w).sum(); + let max_h = sizes.iter().map(|(_, h)| h).fold(0.0_f64, |a, &h| a.max(h)); + // (sum_w * k + gaps) * (max_h * k) <= max_union, where k = dpi / 72: solve a k² + b k - c = 0. + let gaps = f64::from(gap) * (n - 1.0); + let a = sum_w * max_h; + let b = gaps * max_h; + let k = if a > 0.0 { (-b + (b * b + 4.0 * a * max_union as f64).sqrt()) / (2.0 * a) } else { f64::INFINITY }; + dpi.min(72.0 * k).max(1.0) +} + /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). #[cfg(not(target_arch = "wasm32"))] fn bind() -> Result { @@ -128,9 +146,10 @@ fn bind() -> Result { .map(std::path::PathBuf::from) .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); let bindings = Pdfium::bind_to_library(&library).map_err(|e| { IoError::Unsupported(format!( - "PDF import: cannot load PDFium from {} ({e}); put pdfium.dll next to the executable or set PDFIUM_DIR", + "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display() )) })?; From b1870f1950d5d4b1a9f69fbe4c04a48d9ae61c8f Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:15:57 +0100 Subject: [PATCH 055/113] PDF: second CodeRabbit round (render size, buffer estimate, label tree) --- crates/io/src/lib.rs | 9 --------- crates/io/src/pdf.rs | 7 ++++--- crates/io/src/pdf_import.rs | 12 +++++++++++- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 1f69b40ea4..285e0d8602 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -979,25 +979,16 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { if is_psd_input(name, bytes) { return Route::NamedPsd; } -<<<<<<< HEAD Route::Flat } /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) - || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) - { - return pdf_import::import(name, bytes, opts); -======= // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized // raster signature wins over a misleading `.pdf` suffix. if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts, ctl); ->>>>>>> 806c53fd2 (PDF: address CodeRabbit review (cancellation, budgets, labels, export edges)) } match route(name, bytes) { Route::Pcraft => { diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 4317784e50..35c0fdecf5 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -142,7 +142,8 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel let icc = first.image.icc.as_ref(); let icc_obj = icc.map(|_| font_obj + 1); let selection_base = font_obj + if icc.is_some() { 2 } else { 1 }; - let labels_obj = selections_on.then_some(selection_base + 1); + let selection_objects = selection_font.objects(selection_base); + let labels_obj = selections_on.then_some((selection_base + selection_objects.len()) as u32); obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes()); let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::>().join(" "); obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); @@ -213,8 +214,8 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel body.extend_from_slice(b"\nendstream"); obj(&mut out, &body); } - for body in selection_font.objects(selection_base) { - obj(&mut out, &body); + for body in &selection_objects { + obj(&mut out, body); } if labels_obj.is_some() { let nums = pages diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 58ec5fa70b..ec58153ad4 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -62,7 +62,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); - let estimate = (page_pixels * 4.0 * 2.0) as u64; + // The RGBA bitmap, the f32 conversion buffer (16 bytes/px) and the document tiles. + let estimate = (page_pixels * 24.0) as u64; if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { return Err(IoError::Unsupported(format!( "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", @@ -91,6 +92,15 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); + // The rounded target width can render a taller bitmap than the pre-check predicted. + if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { + return Err(IoError::Unsupported(format!( + "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", + index + 1, + width, + height + ))); + } // The page's pixels go straight into the document-wide layer surface: no full-strip // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); From ef7699ae9a6074ab51fb32b085289c87907cda01 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:46:00 +0100 Subject: [PATCH 056/113] PDF: render each artboard rect instead of a whole-document crop --- crates/io/src/pdf.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 35c0fdecf5..a6aa68cd33 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -331,8 +331,6 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); let artboards = doc.artboards(); if !artboards.is_empty() { - // One flattened pass of the whole document; each artboard is a crop of it. - let surface = photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None); let mut pages = Vec::with_capacity(artboards.len()); for (_, name, artboard) in &artboards { ctl.check().map_err(|_| IoError::Cancelled)?; @@ -341,6 +339,8 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result if aw == 0 || ah == 0 { continue; } + // Render only this artboard's rect; the surface never holds the whole document. + let surface = photocraft_compose::composite_to_surface(doc, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None); let values = surface.read_region(rect); let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device)); for px in values.chunks(n) { From 06a6442076055b094824a0c4d1868eb37febcc96 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:57:00 +0100 Subject: [PATCH 057/113] PDF: SVG precedence, hidden artboards, export budget, writer cancellation --- crates/io/src/lib.rs | 5 +++++ crates/io/src/pdf.rs | 46 +++++++++++++++++++++++++++++++++++++------- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 285e0d8602..ebceff3642 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -985,6 +985,11 @@ pub(crate) fn route(name: &str, bytes: &[u8]) -> Route { /// Dispatches format-specific importers and propagates a structured PSD damage /// flag alongside the ordinary best-effort import result. fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result { + // SVG content wins over a misleading `.pdf` suffix, matching the preflight (which checks SVG + // before PDF). + if is_svg_input(name, bytes) { + return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth); + } // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized // raster signature wins over a misleading `.pdf` suffix. if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index a6aa68cd33..7bf228320f 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -121,12 +121,20 @@ fn marks_ops(m: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> String { /// A one-page PDF. pub fn print_pdf(page: &PrintPage) -> Vec { - print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default()) + print_pdf_pages(std::slice::from_ref(page), &[String::new()], &selection::SelectionFont::default(), &photocraft_raster::Interrupt::NONE).unwrap_or_default() } /// A PDF with one page per entry; `vectors[i]` (when present) is drawn over page `i`. -fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &selection::SelectionFont) -> Vec { - let Some(first) = pages.first() else { return Vec::new() }; +fn print_pdf_pages( + pages: &[PrintPage], + vectors: &[String], + selection_font: &selection::SelectionFont, + ctl: &photocraft_raster::Interrupt, +) -> std::result::Result, IoError> { + if ctl.check().is_err() { + return Err(IoError::Cancelled); + } + let Some(first) = pages.first() else { return Ok(Vec::new()) }; let mut out: Vec = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(); let mut offsets: Vec = Vec::new(); let mut obj = |out: &mut Vec, body: &[u8]| { @@ -232,7 +240,7 @@ fn print_pdf_pages(pages: &[PrintPage], vectors: &[String], selection_font: &sel out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); } out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); - out + Ok(out) } /// The vector operators for the contiguous visible top prefix of `doc`, top to bottom, with the @@ -331,14 +339,38 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result let icc = doc.icc_profile.as_ref().map(|p| p.to_vec()); let artboards = doc.artboards(); if !artboards.is_empty() { + // Every page's encoded pixels are kept until the PDF is assembled; bound that peak. + const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30; + let pixels: u64 = artboards.iter().map(|(_, _, a)| u64::from(a.rect.width()) * u64::from(a.rect.height())).sum(); + let estimate = pixels.saturating_mul(device as u64) + w as u64 * h as u64 * n as u64 * 4; + if estimate > MAX_PDF_EXPORT_BYTES { + return Err(IoError::Unsupported(format!( + "PDF export would need about {} MB for {} artboards; export them in smaller batches", + estimate >> 20, + artboards.len() + ))); + } let mut pages = Vec::with_capacity(artboards.len()); - for (_, name, artboard) in &artboards { + for (id, name, artboard) in &artboards { ctl.check().map_err(|_| IoError::Cancelled)?; let rect = artboard.rect; let (aw, ah) = (rect.width(), rect.height()); if aw == 0 || ah == 0 { continue; } + // A hidden artboard still gets its page, rendered from its own content rather than + // left blank by the group's visibility. + let shown; + let doc = if doc.layer(*id).is_some_and(|l| !l.visible) { + let mut copy = doc.clone(); + if let Some(layer) = copy.layer_mut(*id) { + layer.visible = true; + } + shown = copy; + &shown + } else { + doc + }; // Render only this artboard's rect; the surface never holds the whole document. let surface = photocraft_compose::composite_to_surface(doc, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None); let values = surface.read_region(rect); @@ -370,7 +402,7 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result warnings.push("free-form text metadata is not supported by PDF; it will be dropped".into()); } let vectors = vec![String::new(); pages.len()]; - return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default()), warnings }); + return Ok(ExportResult { bytes: print_pdf_pages(&pages, &vectors, &selection::SelectionFont::default(), ctl)?, warnings }); } let canvas = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); // Simple topmost shapes and text layers can be drawn over the flattened backdrop without changing @@ -407,7 +439,7 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result vectors.push_str(ops); } vectors.push_str("Q\n"); - Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font), warnings }) + Ok(ExportResult { bytes: print_pdf_pages(&[page], &[vectors], &selection_font, ctl)?, warnings }) } #[cfg(test)] From 244a6287ab8f504ad52089f2027385b78321f6c3 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:14:21 +0100 Subject: [PATCH 058/113] PDF: import options (page range, DPI, editable text/vector) and DLL packaging - ImportOptions gains pdf_pages (1-based inclusive), pdf_text and pdf_vectors; the importer maps PDF text objects to editable text layers and vector paths to shape layers through the effective DPI. - photocraft-cli convert gains --pdf-dpi and --pdf-pages. - Preferences gain pdf_dpi/pdf_pages, wired through jobs::import_options. - apps/photocraft/build.rs copies PDFIUM_DLL beside the exe; the MSI installs it. --- apps/photocraft-cli/src/args.rs | 6 ++ apps/photocraft-cli/src/document.rs | 19 +++- apps/photocraft/build.rs | 13 +++ crates/engine/src/jobs.rs | 2 + crates/engine/src/prefs.rs | 6 ++ crates/io/src/lib.rs | 9 ++ crates/io/src/pdf_import.rs | 145 ++++++++++++++++++++++++---- packaging/windows/photocraft.wxs | 2 + 8 files changed, 183 insertions(+), 19 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 3f29309ad5..e806085418 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -107,6 +107,12 @@ pub(crate) struct ConvertArgs { /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget #[arg(long)] pub(crate) approve_high_memory: bool, + /// PDF import resolution in DPI (default 300) + #[arg(long)] + pub(crate) pdf_dpi: Option, + /// PDF pages to import, 1-based: "3" or "2-7" (default all) + #[arg(long)] + pub(crate) pdf_pages: Option, #[command(flatten)] pub(crate) gpu: GpuArgs, #[command(flatten)] diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index 95e8d4d8e2..ab9e3cfd35 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -26,11 +26,28 @@ fn refuse_overwriting_input(in_place: bool, input: &Path, output: &Path) -> Resu Ok(()) } +/// `N` or `N-M`, 1-based and inclusive, into a normalized `(first, last)`. +fn parse_pdf_pages(s: &str) -> Result<(u32, u32)> { + let (a, b) = s.split_once('-').unwrap_or((s, s)); + let bad = || CliError::Other(format!("invalid --pdf-pages {s:?}; use N or N-M")); + let a = a.trim().parse::().map_err(|_| bad())?; + let b = b.trim().parse::().map_err(|_| bad())?; + if a == 0 || b == 0 { + return Err(CliError::Other(format!("--pdf-pages is 1-based; {s:?} starts at 0"))); + } + Ok((a.min(b), a.max(b))) +} + pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write) -> Result { let (input, output) = (&a.input, &a.output); let opts = ExportOptions::from(&a.export); refuse_overwriting_input(a.in_place, input, output)?; - let import_opts = photocraft_io::ImportOptions { psd_high_memory_approved: a.approve_high_memory, ..Default::default() }; + let import_opts = photocraft_io::ImportOptions { + psd_high_memory_approved: a.approve_high_memory, + pdf_dpi: a.pdf_dpi.unwrap_or(300.0), + pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?, + ..Default::default() + }; let mut o = files::open_with_options(input, &import_opts)?; // Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw. photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 48abc9f1a5..e750904018 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -11,6 +11,19 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } + // PDF import loads PDFium at runtime. When the build provides the shared library + // (`PDFIUM_DLL`, set by the release packaging step), copy it beside the executable so the + // installer's pdfium.dll and the running app agree. + println!("cargo:rerun-if-env-changed=PDFIUM_DLL"); + if let (Some(dll), Ok(out)) = (std::env::var_os("PDFIUM_DLL"), std::env::var("OUT_DIR")) { + let dll = std::path::PathBuf::from(dll); + if let Some(profile_dir) = std::path::Path::new(&out).ancestors().nth(3) { + let dest = profile_dir.join(dll.file_name().unwrap_or_default()); + if let Err(e) = std::fs::copy(&dll, &dest) { + println!("cargo:warning=could not copy PDFium to {}: {e}", dest.display()); + } + } + } // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ba82bd9028..a68606eeba 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -956,6 +956,8 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor photocraft_io::ImportOptions { max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), + pdf_dpi: prefs.file_handling.pdf_dpi, + pdf_pages: prefs.file_handling.pdf_pages, ..Default::default() } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ee61af791c..1750310d26 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -493,6 +493,10 @@ pub struct FileHandling { pub recover_on_launch: bool, /// Open a file with no ICC profile as untagged even when its EXIF ColorSpace tag says sRGB. pub ignore_exif_profile_tag: bool, + /// PDF import resolution in DPI; the document keeps it so the page's print size is preserved. + pub pdf_dpi: f32, + /// PDF import page range, 1-based and inclusive; `None` imports every page. + pub pdf_pages: Option<(u32, u32)>, /// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR /// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead. pub exr_aces_cg: bool, @@ -530,6 +534,8 @@ impl Default for FileHandling { autosave_minutes: 10, recover_on_launch: true, ignore_exif_profile_tag: false, + pdf_dpi: 300.0, + pdf_pages: None, exr_aces_cg: false, ask_before_saving_layered_tiff: true, maximize_psd_compatibility: Ask::Always, diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ebceff3642..599f110410 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -610,6 +610,12 @@ pub struct ImportOptions { /// Resolution (dots per inch) PDF pages are rendered at on import; the document keeps it so /// the page's print size is preserved. Defaults to 300. pub pdf_dpi: f32, + /// The 1-based, inclusive page range to import; `None` imports every page (up to the cap). + pub pdf_pages: Option<(u32, u32)>, + /// Import PDF text objects as editable text layers (default on). + pub pdf_text: bool, + /// Import PDF vector paths as editable shape layers (default on). + pub pdf_vectors: bool, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -625,6 +631,9 @@ impl Default for ImportOptions { psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, pdf_dpi: 300.0, + pdf_pages: None, + pdf_text: true, + pdf_vectors: true, psd_high_memory_approved: false, psd_approved_estimate: None, } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ec58153ad4..ab77a78b3e 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,13 +1,16 @@ -//! PDF import: PDFium renders every page and each page becomes an artboard. +//! PDF import: PDFium renders the selected pages and each page becomes an artboard. //! //! The document resolution is chosen so the page's physical size is preserved even when the //! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side //! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. +//! +//! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / +//! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. use crate::{ImportOptions, ImportResult, IoError}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; -use photocraft_geom::{Rect, Size}; +use photocraft_doc::{Artboard, Color, Document, Fill, Group, Knot, Layer, LayerContent, Path, PathOp, ShapeLayer, ShapeStroke, Subpath, TextLayer}; +use photocraft_geom::{Affine, Point, Rect, Size}; use photocraft_raster::{Interrupt, Surface}; /// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. @@ -21,7 +24,7 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrup Err(IoError::Unsupported("PDF import needs the desktop build".into())) } -/// Renders every PDF page and opens it as one artboard per page. +/// Renders the selected PDF pages and opens each as one artboard. #[cfg(not(target_arch = "wasm32"))] pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { use pdfium_render::prelude::*; @@ -38,19 +41,29 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let pdfium = bind()?; let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let total = document.pages().len().max(0) as usize; - let count = total.min(MAX_PAGES); - if count == 0 { - return Err(IoError::Unsupported("PDF has no pages".into())); + let (first, last) = match opts.pdf_pages { + Some((a, b)) => { + let a = (a.max(1) as usize).min(total.max(1)); + let b = (b.max(1) as usize).min(total.max(1)); + (a.min(b), a.max(b)) + } + None => (1, total), + }; + if total == 0 || first > total { + return Err(IoError::Unsupported("PDF has no pages in the requested range".into())); } + let page_count = last - first + 1; + let count = page_count.min(MAX_PAGES); // The page sizes in points first: the effective DPI must fit the budgets, and capping the // raster must not change the page's physical size. let mut sizes = Vec::with_capacity(count); for index in 0..count { ctl.check().map_err(|_| IoError::Cancelled)?; - let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page_index = first - 1 + index; + let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let (w, h) = (f64::from(page.width().value), f64::from(page.height().value)); if w <= 0.0 || h <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {} has no area", index + 1))); + return Err(IoError::Unsupported(format!("PDF page {} has no area", page_index + 1))); } sizes.push((w, h)); } @@ -76,6 +89,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut x = 0u32; for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { ctl.check().map_err(|_| IoError::Cancelled)?; + let page_index = first - 1 + index; let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the @@ -83,12 +97,12 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { return Err(IoError::Unsupported(format!( "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", - index + 1, + page_index + 1, target_width, target_height ))); } - let page = document.pages().get(index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; + let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); @@ -96,7 +110,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { return Err(IoError::Unsupported(format!( "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", - index + 1, + page_index + 1, width, height ))); @@ -113,21 +127,116 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - data.push(f32::from(chunk[3]) / 255.0); } surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); - let layer = Layer::new(format!("Page {}", index + 1), LayerContent::Raster(surface)); + let layer = Layer::new(format!("Page {}", page_index + 1), LayerContent::Raster(surface)); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); - let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - doc.layers.push(Layer::new(format!("Page {}", index + 1), LayerContent::Group(group))); + let mut children = vec![layer]; + if opts.pdf_text || opts.pdf_vectors { + children.extend(object_layers(&page, *h_pt, dpi, x, opts)); + } + let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); x += width + GAP; ctl.progress((index + 1) as f32 / count as f32); } let mut warnings = Vec::new(); - if total > count { - let reason = if count < total.min(MAX_PAGES) { "the rest would make the import canvas too large" } else { "the page limit is 16" }; - warnings.push(format!("PDF has {total} pages; imported the first {count} ({reason})")); + if first > 1 || last < total || count < page_count { + let shown_last = first + count - 1; + let reason = if count < page_count { " (the page limit is 16)" } else { "" }; + warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}")); } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// Editable text and shape layers for one rendered page, in document pixels. +#[cfg(not(target_arch = "wasm32"))] +fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f64, x: u32, opts: &ImportOptions) -> Vec { + use pdfium_render::prelude::*; + + let to_x = |v: f32| f64::from(v) * dpi / 72.0; + let objects = page.objects(); + let mut layers = Vec::new(); + for object in objects.iter() { + match object { + PdfPageObject::Text(text) if opts.pdf_text => { + let content = text.text(); + if content.trim().is_empty() { + continue; + } + let Ok(bounds) = text.bounds() else { continue }; + let x_px = to_x(bounds.left().value).round() + f64::from(x); + let y_px = (height_pt - to_x(bounds.top().value)).round(); + // The text layer's size is in points; the transform is in document pixels. + let size_pt = f64::from(text.scaled_font_size().value).max(1.0); + layers.push(Layer::new( + "Text", + LayerContent::Text(TextLayer { + text: content, + font_family: text.font().family(), + size_pt: size_pt as f32, + color: Color::BLACK, + transform: Affine::translate(x_px, y_px), + ..Default::default() + }), + )); + } + PdfPageObject::Path(path) if opts.pdf_vectors => { + let mut subpaths: Vec = Vec::new(); + let mut knots: Vec = Vec::new(); + let mut closed = false; + let mut bezier: Vec<(f64, f64)> = Vec::new(); + for segment in path.segments().iter() { + let point = || (to_x(segment.x().value).round(), (height_pt - to_x(segment.y().value)).round()); + if segment.is_close() { + closed = true; + continue; + } + match segment.segment_type() { + PdfPathSegmentType::MoveTo => { + if !knots.is_empty() { + subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); + closed = false; + } + let (px, py) = point(); + knots.push(Knot::corner(px, py)); + } + PdfPathSegmentType::LineTo => { + let (px, py) = point(); + knots.push(Knot::corner(px, py)); + } + PdfPathSegmentType::BezierTo => { + // PDF draws a cubic Bézier as three consecutive BezierTo points: the + // two control points, then the end point. + bezier.push(point()); + if bezier.len() == 3 { + let ((c1x, c1y), (c2x, c2y), (ex, ey)) = (bezier[0], bezier[1], bezier[2]); + if let Some(prev) = knots.last_mut() { + prev.out_ctrl = Point::new(c1x, c1y); + } + knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); + bezier.clear(); + } + } + PdfPathSegmentType::Unknown => {} + } + } + if !knots.is_empty() { + subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); + } + if subpaths.is_empty() { + continue; + } + let stroke = path.is_stroked().unwrap_or(false).then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + layers.push(Layer::new( + "Path", + LayerContent::Shape(ShapeLayer { path: Path::new(subpaths), fill: Some(Fill::Solid(Color::BLACK)), stroke, ..Default::default() }), + )); + } + _ => {} + } + } + layers +} + /// The highest DPI not above `requested` that keeps every page and the artboard strip within /// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. #[cfg(not(target_arch = "wasm32"))] diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index 6ff961fd99..020f7aa89c 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -71,6 +71,8 @@ + + From 7f96ce53433816fd12aec6c5ff822703c6082952 Mon Sep 17 00:00:00 2001 From: Firstbober Date: Sat, 31 Oct 2026 14:04:54 +0100 Subject: [PATCH 059/113] Preserve Indexed profiles and preview current tool colors --- crates/engine/src/cmd/color_cmds.rs | 20 ++- crates/engine/src/cmd/image_cmds.rs | 2 +- crates/engine/src/cmd/mode_cmds.rs | 24 +-- crates/engine/src/cmd/mode_cmds/tests.rs | 82 ++++++--- crates/ui-egui/src/canvas/filter_preview.rs | 3 + crates/ui-egui/src/canvas/tests.rs | 167 ++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 86 +++++---- .../src/dialogs/filter_dialog/tests.rs | 21 ++- .../ui-egui/src/dialogs/filter_preview_ui.rs | 1 + .../src/dialogs/filter_preview_worker.rs | 1 + crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/ar.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nb.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/development.md | 11 +- 38 files changed, 364 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index c7c7942d0b..9fd1762c45 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -899,7 +899,9 @@ fn ink_surface(s: &Surface, d: &Duotone) -> Surface { } /// Image › Mode › RGB/Grayscale/CMYK/Lab through the CMS. Params: `profile` (destination, -/// default the mode's working profile), `intent` (default relative), `bpc` (default true). +/// default the mode's working profile; Indexed→RGB without an explicit profile instead expands +/// the already-RGB storage without changing its encoded samples or ICC bytes), `intent` +/// (default relative), `bpc` (default true). pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result { let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; if doc.mode == ColorMode::Multichannel && mode != ColorMode::Multichannel { @@ -908,8 +910,13 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result s.color.resolve(spec, Some(doc), Some(mode))?, + None if preserve_indexed_rgb => document_profile(doc), None => s.color.working(mode), }; if space_mode(dst.color_space) @@ -923,7 +930,16 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Vec { "image.mode.rgb", "RGB Color", ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + r##"{"profile":"|working|/path/to/profile.icc"=working (Indexed→RGB preserves the document profile unless explicit),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, has_doc, |s, p| convert_mode(s, ColorMode::Rgb, p) ), diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index df14c063cc..2adde91685 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -9,7 +9,7 @@ use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind}; use photocraft_algo::transform::{Homography, Interp}; -use photocraft_cms::{ColorSpace, Transform}; +use photocraft_cms::{ColorSpace, TransformOptions}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size}; @@ -266,21 +266,21 @@ fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[ _ => crate::color_cmds::composite_profile(doc), }; let source = s.color.working(ColorMode::Rgb); - let transform = Transform::new(&source, &destination, s.color.settings.intent(), s.color.settings.bpc) + let options = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }; + let transform = photocraft_cms::transform::cached(&source, &destination, options) .map_err(|e| bad("image.mode.indexedColor", format!("cannot convert matte colour: {e}")))?; let mut output = [0.0; 16]; transform.eval(&color[..3], &mut output); - let matte = if destination.color_space == ColorSpace::Gray { - [output[0]; 3] - } else { - [output[0], output[1], output[2]] - }; - Ok(matte) + let matte = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] }; + if matte.iter().any(|v| !v.is_finite()) { + return Err(bad("image.mode.indexedColor", "cannot convert matte colour to finite document samples")); + } + Ok(matte.map(|v| v.clamp(0.0, 1.0))) } fn indexed_matte(s: &Session, p: &Value) -> Result> { const CMD: &str = "image.mode.indexedColor"; - let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let matte = match p.get("matte") { None | Some(Value::Null) => return Ok(None), Some(Value::String(value)) => match value.as_str() { @@ -289,8 +289,8 @@ fn indexed_matte(s: &Session, p: &Value) -> Result> { "black" => [0.0; 3], "gray" => [128.0 / 255.0; 3], "netscapeGray" => [192.0 / 255.0; 3], - "foreground" => working_matte_color(s, &doc, s.tools.foreground)?, - "background" => working_matte_color(s, &doc, s.tools.background)?, + "foreground" => working_matte_color(s, doc, s.tools.foreground)?, + "background" => working_matte_color(s, doc, s.tools.background)?, value if value.len() == 7 && value.starts_with('#') => p .get("matte") .and_then(parse_color) @@ -755,7 +755,7 @@ pub fn specs() -> Vec { "image.mode.indexedColor", "Indexed Color…", ["Image", "Mode"], -r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|gray|netscapeGray|#rrggbb; gray=50% Gray (#808080), netscapeGray=Netscape Gray (#c0c0c0))"##, + r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|gray|netscapeGray|#rrggbb; gray=50% Gray (#808080), netscapeGray=Netscape Gray (#c0c0c0))"##, |s| mode_is( s, &[ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Duotone, ColorMode::Cmyk, ColorMode::Lab], diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index f249f87bca..e5dc8aac33 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -247,6 +247,40 @@ fn indexed_color_palettes_and_dithers() { } } +#[test] +fn indexed_exact_preserves_profile_and_samples_through_default_rgb() { + for depth in [8, 16, 32] { + for profile in ["adobe-rgb-compat", "display-p3", "prophoto-compat", "none"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": profile})).unwrap(); + paint(&mut s, |_, _| [100.0 / 255.0, 150.0 / 255.0, 200.0 / 255.0, 1.0]); + let source_profile = doc(&s).icc_profile.clone(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap(); + assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: Indexed profile"); + assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[100, 150, 200]]); + let indexed_pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + s.execute("image.mode.rgb", json!({})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Rgb); + assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: RGB profile"); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel); + assert!(doc(&s).color_table.is_none()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Indexed); + assert_eq!(doc(&s).icc_profile, source_profile); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Rgb); + assert_eq!(doc(&s).icc_profile, source_profile); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("image.mode.rgb", json!({"profile": "srgb"})).unwrap(); + assert_eq!(doc(&s).icc_profile, Some(photocraft_cms::Builtin::Srgb.profile().to_bytes()), "an explicit target still converts"); + if profile != "none" { + assert_ne!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel); + } + } + } +} + #[test] fn indexed_matte_blends_edges_without_replacing_clear_pixels() { for depth in [8, 16, 32] { @@ -292,26 +326,30 @@ fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() { use photocraft_cms::Transform; for depth in [8, 16, 32] { - let mut s = Session::new(); - s.color.settings.working_rgb = "display-p3".into(); - s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); - s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); - s.execute("tools.setColors", json!({"foreground": "#3366cc"})).unwrap(); - paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] }); - - let source = s.color.working(ColorMode::Rgb); - let destination = crate::color_cmds::document_profile(doc(&s)); - let transform = Transform::new(&source, &destination, s.color.settings.intent(), s.color.settings.bpc).unwrap(); - let mut converted = [0.0; 16]; - transform.eval(&[0.2, 0.4, 0.8], &mut converted); - let expected = [0.5 + 0.5 * converted[0], 0.5 * converted[1], 0.5 * converted[2]]; - - s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "foreground"})).unwrap(); - let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); - for (got, want) in edge[..3].iter().zip(expected) { - assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}"); + for (matte, color) in [("foreground", [0.0, 1.0, 0.0]), ("background", [1.0, 0.0, 0.0])] { + for (intent, bpc) in [("relative", false), ("absolute", true)] { + let mut s = Session::new(); + s.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "intent": intent, "bpc": bpc})).unwrap(); + s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#00ff00", "background": "#ff0000"})).unwrap(); + paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] }); + let pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + let profile = doc(&s).icc_profile.clone(); + let source = s.color.working(ColorMode::Rgb); + let destination = crate::color_cmds::document_profile(doc(&s)); + let transform = Transform::new(&source, &destination, s.color.settings.intent(), bpc).unwrap(); + let mut converted = [0.0; 16]; + transform.eval(&color, &mut converted); + let expected = [0, 1, 2].map(|i| ((pixel[i] * pixel[3] + converted[i].clamp(0.0, 1.0) * (1.0 - pixel[3])) * 255.0).round() as u8); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap(); + let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); + assert_eq!([edge[0], edge[1], edge[2]].map(|v| (v * 255.0).round() as u8), expected, "{depth}-bit {matte} {intent}, bpc={bpc}"); + assert_eq!(edge[3], 1.0); + assert_eq!(doc(&s).icc_profile, profile); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 0)[3], 0.0); + } } - assert_eq!(edge[3], 1.0); } } @@ -321,7 +359,7 @@ fn indexed_matte_hex_stays_in_document_rgb_coordinates() { let mut s = Session::new(); s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap(); s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); - paint(&mut s, |_| [1.0, 0.0, 0.0, 0.5]); + paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]); s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "#3366cc"})).unwrap(); let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); let expected = [0.5 + 0.5 * 0.2, 0.5 * 0.4, 0.5 * 0.8]; @@ -337,10 +375,10 @@ fn indexed_matte_named_gray_choices_use_their_document_samples() { for (matte, channel) in [("gray", 128.0 / 255.0), ("netscapeGray", 192.0 / 255.0)] { let mut s = Session::new(); s.execute("file.new", json!({"width": 1, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); - paint(&mut s, |_| [1.0, 0.0, 0.0, 0.5]); + paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]); s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap(); let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0); - assert!((edge[0] - 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}"); + assert!((edge[0] - (0.5 + channel * 0.5)).abs() <= 1.0 / 255.0, "{matte}: {edge:?}"); for value in edge[1..3].iter() { assert!((*value - channel * 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}"); } diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 3a6ee54d97..7eff66f7df 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -69,6 +69,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e command: cmd, params, k, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let key = request.doc.0 ^ (1u64 << 61); // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at @@ -123,6 +124,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e task.target, &documents, &color, + Some(task.tool_colors), ) .map(|doc| { let buffer = photocraft_compose::flatten(&doc); @@ -164,6 +166,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e request.target, &documents, &app.session.color.settings, + Some(request.tool_colors), ) .map(|doc| { let buffer = photocraft_compose::flatten(&doc); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 661da5d277..eba0bf3e8b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -276,6 +276,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": 999.0}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let (told, cancelled) = std::sync::mpsc::channel(); app.filter_preview_worker @@ -329,6 +330,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn command: command.into(), params, k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let doc = app.session.documents()[0].doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); @@ -347,6 +349,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn key.target, &documents, &Default::default(), + Some(key.tool_colors), ) .map(|d| { let buffer = photocraft_compose::flatten(&d); @@ -396,6 +399,169 @@ fn a_held_preview_frame_stays_on_the_canvas_when_the_proxy_factor_changes() { assert_eq!((k, size), (1, [2400, 2200])); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn indexed_matte_preview_matches_commit_and_refreshes_tool_colors_inline_and_on_worker() { + for background in [false, true] { + for depth in [8, 16, 32] { + for matte in ["foreground", "background"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = background; + app.run("file.new", json!({"width": 64, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); + app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap(); + app.session + .edit("Translucent edge", |doc, active| { + let format = doc.pixel_format(); + doc.layer_mut(active.unwrap()) + .unwrap() + .surface_mut() + .unwrap() + .fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5])); + Ok(()) + }) + .unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte}); + crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap(); + app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone()); + let ctx = egui::Context::default(); + let mut previous = None; + for (foreground, background_color) in [("#3366cc", "#cc6633"), ("#26bf59", "#bf26a6")] { + app.session.execute("tools.setColors", json!({"foreground": foreground, "background": background_color})).unwrap(); + let colors = (app.session.tools.foreground, app.session.tools.background); + let shown = ensure_filter_preview(&mut app, 0, &ctx); + if background { + assert!(shown.is_none(), "old tool colors must not remain visible"); + } + drive_until(&mut app, &ctx, "the current matte colors", |app| { + app.filter_preview.as_ref().is_some_and(|p| p.key.tool_colors == colors && p.result.is_some()) + }); + let preview = app.filter_preview.as_ref().unwrap().result.as_ref().unwrap(); + let mut applied = photocraft_engine::Session::new(); + applied.color.settings = app.session.color.settings.clone(); + applied.tools.foreground = colors.0; + applied.tools.background = colors.1; + applied.add_document((*source).clone(), None); + applied.execute("image.mode.indexedColor", params.clone()).unwrap(); + let committed = &applied.active().unwrap().doc; + assert_eq!(preview.icc_profile, source.icc_profile); + assert_eq!(preview.color_table, committed.color_table); + let actual = preview.layers[0].surface().unwrap().read_region(preview.bounds()); + let expected = committed.layers[0].surface().unwrap().read_region(committed.bounds()); + assert_eq!(actual, expected, "{matte}, {depth}-bit, worker={background}"); + if let Some(previous) = previous { + assert_ne!(actual, previous, "changing the selected tool color refreshes the pixels"); + } + previous = Some(actual); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Rgb, "preview does not commit"); + } + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cross_scale_indexed_matte_preview_rejects_old_tool_colors_from_cached_and_worker_results() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = true; + app.run("file.new", json!({"width": 2400, "height": 2200, "depth": 8, "background": "transparent"})).unwrap(); + app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap(); + app.session + .edit("Translucent edge", |doc, active| { + let format = doc.pixel_format(); + doc.layer_mut(active.unwrap()) + .unwrap() + .surface_mut() + .unwrap() + .fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5])); + Ok(()) + }) + .unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25; + let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "foreground"}); + crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap(); + app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone()); + app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + let ctx = egui::Context::default(); + drive_until(&mut app, &ctx, "the first indexed preview", |a| a.filter_preview.as_ref().is_some_and(|p| p.result.is_some())); + let old = app.filter_preview.as_ref().expect("the first preview").key.clone(); + assert_eq!(old.k, 2, "the zoomed-out large document uses the reduced preview"); + + app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0; + let new_colors = (app.session.tools.foreground, app.session.tools.background); + let new = crate::filter_dialog::FilterPreviewKey { k: 1, tool_colors: new_colors, ..old.clone() }; + assert_ne!(old.tool_colors, new.tool_colors); + assert_ne!(old.k, new.k, "the cache and request use different preview factors"); + + // Keep the current worker pending so the only possible frame is the cached old-color one. + let (release_new, wait_new) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(new.clone(), ctx.clone(), move |_| { + wait_new.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + crate::dialogs::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .expect("the worker starts"); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the cached old-color frame is not painted while the new worker runs"); + release_new.send(()).expect("released"); + drive_until(&mut app, &ctx, "the new worker to finish", |a| !a.filter_preview_worker.busy()); + assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new); + assert!(app.filter_preview.as_ref().unwrap().result.is_none()); + + // Start an old-color worker while its request is current, then move the dialog to a new + // cross-scale request before the old result lands. Its real preview must not replace the + // current request through the loose worker-result gate. + app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25; + let old_worker = old.clone(); + let doc = app.session.documents()[0].doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let color = app.session.color.settings.clone(); + let (release_old, wait_old) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(old_worker.clone(), ctx.clone(), move |_| { + wait_old.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + old_worker.active, + &old_worker.command, + &old_worker.params, + old_worker.k, + None, + old_worker.target, + &documents, + &color, + Some(old_worker.tool_colors), + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + crate::dialogs::filter_preview_worker::Computed { result, ms: 0.0 } + }) + .expect("the worker starts"); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the old cached request is not current"); + + app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0; + app.ui.dialogs[0].fields.insert("matte".into(), json!("background")); + let mut new_late = new.clone(); + new_late.params.as_object_mut().unwrap().insert("matte".into(), json!("background")); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the current request has no result while the old worker runs"); + release_old.send(()).expect("released"); + drive_until(&mut app, &ctx, "the stale old-color worker to finish", |a| { + if let Some(shown) = &a.filter_preview { + assert_eq!(shown.key.tool_colors, new.tool_colors, "the stale old-color worker result was not painted"); + assert_ne!(shown.key.k, old.k, "the stale old-scale worker result was not painted"); + } + a.filter_preview.as_ref().is_some_and(|p| p.key == new_late && p.result.is_some()) && !a.filter_preview_worker.busy() + }); + assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new_late); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() { @@ -502,6 +668,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": moved}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let (release_empty, wait) = std::sync::mpsc::channel::<()>(); app.filter_preview_worker diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 31a7bbc03d..c8cedf7d73 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -6,7 +6,7 @@ use std::sync::Arc; -use photocraft_cms::{ColorSpace, Transform}; +use photocraft_cms::{ColorSpace, TransformOptions}; use photocraft_color::ColorMode; use photocraft_doc::Document; use photocraft_engine::color_cmds::ColorSettings; @@ -847,56 +847,59 @@ fn replace_color_result(ui: &mut egui::Ui, f: &mut Map) { const INDEXED_MATTE_FOREGROUND: &str = "__indexedMatteForeground"; const INDEXED_MATTE_BACKGROUND: &str = "__indexedMatteBackground"; +const INDEXED_MATTE_COLOR_ERROR: &str = "__indexedMatteColorError"; /// Resolve a tool colour into the encoded samples used by Indexed Color's matte. /// /// The picker and command fields carry document RGB coordinates. Tool swatches are /// working-RGB coordinates, so only the named tool choices need this conversion here. -fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32; 4]) -> [f32; 3] { +fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32; 4]) -> Result<[f32; 3], String> { let destination = match photocraft_engine::color_cmds::mode_space(doc.mode) { ColorSpace::Rgb | ColorSpace::Gray => photocraft_engine::color_cmds::document_profile(doc), _ => photocraft_engine::color_cmds::composite_profile(doc), }; let source = app.session.color.working(ColorMode::Rgb); - let Ok(transform) = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc) else { - return [color[0], color[1], color[2]]; - }; + let options = TransformOptions { intent: app.session.color.settings.intent(), bpc: app.session.color.settings.bpc, ..Default::default() }; + let transform = photocraft_cms::transform::cached(&source, &destination, options).map_err(|e| e.to_string())?; let mut output = [0.0; 16]; transform.eval(&color[..3], &mut output); - if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] } + let rgb = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] }; + if rgb.iter().any(|v| !v.is_finite()) { + return Err("cannot convert matte colour to finite document samples".into()); + } + Ok(rgb.map(|v| v.clamp(0.0, 1.0))) } fn indexed_matte_defaults(app: &PhotocraftApp, fields: &mut Map) { - let Some(doc) = app.session.active().map(|state| state.doc.clone()) else { return }; - let foreground = indexed_matte_document_color(app, &doc, app.session.tools.foreground); - let background = indexed_matte_document_color(app, &doc, app.session.tools.background); - fields.insert(INDEXED_MATTE_FOREGROUND.into(), json!(crate::color_picker_ui::hex(foreground))); - fields.insert(INDEXED_MATTE_BACKGROUND.into(), json!(crate::color_picker_ui::hex(background))); + let Some(doc) = app.session.active().map(|state| state.doc.as_ref()) else { return }; + for (key, color) in [(INDEXED_MATTE_FOREGROUND, app.session.tools.foreground), (INDEXED_MATTE_BACKGROUND, app.session.tools.background)] { + match indexed_matte_document_color(app, doc, color) { + Ok(rgb) => { + fields.insert(key.into(), json!(crate::color_picker_ui::hex(rgb))); + } + Err(error) => { + fields.insert(INDEXED_MATTE_COLOR_ERROR.into(), json!(error)); + } + } + } } -fn indexed_matte_seed(fields: &Map, value: &str) -> [f32; 3] { +fn indexed_matte_seed(fields: &Map, value: &str) -> Option<[f32; 3]> { match value { - "foreground" => fields - .get(INDEXED_MATTE_FOREGROUND) - .and_then(Value::as_str) - .and_then(crate::color_picker_ui::parse_hex) - .unwrap_or([0.0; 3]), - "background" => fields - .get(INDEXED_MATTE_BACKGROUND) - .and_then(Value::as_str) - .and_then(crate::color_picker_ui::parse_hex) - .unwrap_or([1.0; 3]), - "black" => [0.0; 3], - "gray" => [128.0 / 255.0; 3], - "netscapeGray" => [192.0 / 255.0; 3], - _ => [1.0; 3], + "foreground" => fields.get(INDEXED_MATTE_FOREGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex), + "background" => fields.get(INDEXED_MATTE_BACKGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex), + "black" => Some([0.0; 3]), + "gray" => Some([128.0 / 255.0; 3]), + "netscapeGray" => Some([192.0 / 255.0; 3]), + "none" | "white" => Some([1.0; 3]), + _ => crate::color_picker_ui::parse_hex(value), } } fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { let value = fields.get("matte").and_then(Value::as_str).unwrap_or("none"); let mut choice = if value.starts_with('#') { "custom" } else { value }; - let color = crate::color_picker_ui::parse_hex(value).unwrap_or_else(|| indexed_matte_seed(fields, value)); + let color = indexed_matte_seed(fields, value); let mut changed = false; let mut pick = false; ui.horizontal(|ui| { @@ -913,27 +916,34 @@ fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { ("white", "White"), ("black", "Black"), ("gray", "50% Gray"), - ("netscapeGray", "Netscape Gray"), + ("netscapeGray", tl!("Netscape Gray")), ("custom", "Other…"), ], 170.0, ); - if choice == "custom" { + if choice == "custom" + && let Some(color) = color + { let bytes = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); pick = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), tl!("Matte")).clicked(); } }); + if color.is_none() + && let Some(error) = fields.get(INDEXED_MATTE_COLOR_ERROR).and_then(Value::as_str) + { + ui.colored_label(Tokens::get(ui.ctx()).danger, error); + } let custom = choice == "custom"; if changed { - if custom { + if custom && let Some(color) = color { // Keep the previous matte until the picker confirms; the picker uses this only as // its initial document-encoded colour when switching from a named matte or None. fields.insert("__pickColorDefault".into(), json!(crate::color_picker_ui::hex(color))); - } else { + } else if !custom { fields.insert("matte".into(), json!(choice.to_owned())); } } - if custom && (changed || pick) { + if custom && color.is_some() && (changed || pick) { crate::color_picker_ui::request_field(fields, "matte", &crate::color_picker_ui::title_for("Matte")); } } @@ -1264,6 +1274,7 @@ pub fn preview_document_with( photocraft_engine::channel_cmds::ChannelTarget::Composite, &[], &ColorSettings::default(), + None, ) } @@ -1271,6 +1282,8 @@ pub fn preview_document_with( /// `documents` are the open documents in session order: document params (Match Color's Source, /// Displace's map) index into them. `color` is the app's Edit › Color Settings: Assign and Convert /// to Profile's `working` is the working space chosen there, not the built-in default. +/// `tool_colors` carries the caller's working-space foreground/background values; standalone +/// previews without a session use the engine's default tool colors. #[allow(clippy::too_many_arguments)] pub(crate) fn preview_document_for_target( doc: &Document, @@ -1282,6 +1295,7 @@ pub(crate) fn preview_document_for_target( target: photocraft_engine::channel_cmds::ChannelTarget, documents: &[Arc], color: &ColorSettings, + tool_colors: Option<([f32; 4], [f32; 4])>, ) -> Option { if command == crate::select_mask_view::COMMAND { return crate::select_mask_view::preview_document(doc, active, params, k, cancel); @@ -1317,6 +1331,10 @@ pub(crate) fn preview_document_for_target( } let mut s = photocraft_engine::Session::new(); s.color.settings = color.clone(); + if let Some((foreground, background)) = tool_colors { + s.tools.foreground = foreground; + s.tools.background = background; + } s.set_inline_job_ctx(cancel.cloned()); let doc_id = proxy.id; s.add_document(proxy, None); @@ -1459,11 +1477,12 @@ pub struct FilterPreviewKey { pub command: String, pub params: Value, pub k: u32, + pub tool_colors: ([f32; 4], [f32; 4]), } impl FilterPreviewKey { /// Everything except the parameters: same dialog, document, revision, layer, channel target, - /// command and proxy factor. + /// command, proxy factor and tool colors. /// /// The canvas shows whatever this preview was computed for, so a result whose parameters are /// a few frames old still belongs on screen while a slider is moving; matching on everything @@ -1485,6 +1504,7 @@ impl FilterPreviewKey { && self.active == other.active && self.target == other.target && self.command == other.command + && self.tool_colors == other.tool_colors } } diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 31786411b7..a45e30b656 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -99,7 +99,7 @@ fn indexed_matte_tool_seeds_use_document_encoded_rgb() { session.execute("file.new", json!({"width": 2, "height": 2, "background": "transparent"})).unwrap(); session.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); - let mut app = PhotocraftApp::new(session, crate::Services::default()); + let app = PhotocraftApp::new(session, crate::Services::default()); let mut fields = Map::new(); indexed_matte_defaults(&app, &mut fields); @@ -112,7 +112,10 @@ fn indexed_matte_tool_seeds_use_document_encoded_rgb() { transform.eval(&input, &mut output); let expected = crate::color_picker_ui::hex([output[0], output[1], output[2]]); assert_eq!(fields.get(key).and_then(Value::as_str), Some(expected.as_str()), "{key}"); - assert_eq!(indexed_matte_seed(&fields, if key == INDEXED_MATTE_FOREGROUND { "foreground" } else { "background" }), crate::color_picker_ui::parse_hex(&expected).unwrap()); + assert_eq!( + indexed_matte_seed(&fields, if key == INDEXED_MATTE_FOREGROUND { "foreground" } else { "background" }), + crate::color_picker_ui::parse_hex(&expected) + ); } } /// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out. @@ -131,6 +134,7 @@ fn key() -> FilterPreviewKey { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": 4.0}), k: 1, + tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), } } @@ -153,6 +157,8 @@ fn same_target_ignores_parameters_but_nothing_else() { |k: &mut FilterPreviewKey| k.target = photocraft_engine::channel_cmds::ChannelTarget::LayerMask, |k: &mut FilterPreviewKey| k.command = "filter.blur.motionBlur".into(), |k: &mut FilterPreviewKey| k.k = 2, + |k: &mut FilterPreviewKey| k.tool_colors.0 = [0.2, 0.4, 0.8, 1.0], + |k: &mut FilterPreviewKey| k.tool_colors.1 = [0.8, 0.4, 0.2, 1.0], ] { let mut other = base.clone(); break_it(&mut other); @@ -678,6 +684,7 @@ fn smart_displace_preview_uses_the_map_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap_or_else(|| panic!("map {map}: no preview")); assert!(photocraft_compose::render(&preview, doc.bounds()).px == want, "map {map}: the preview differs from what OK applies"); @@ -720,6 +727,7 @@ fn match_color_preview_uses_the_source_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap_or_else(|| panic!("{label}: no preview")); let got = preview.layers[0].surface().unwrap().pixel(24, 16); @@ -736,6 +744,7 @@ fn match_color_preview_uses_the_source_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap(); let px = preview.layers[0].surface().unwrap().pixel(12, 8); @@ -1673,12 +1682,8 @@ fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { use egui::accesskit::Role; use egui_kittest::{Harness, kittest::Queryable}; - for (choice, matte) in [ - ("Black", [0.0, 0.0, 0.0]), - ("50% Gray", [128.0 / 255.0; 3]), - ("Netscape Gray", [192.0 / 255.0; 3]), - ("Other…", [0.0, 0.0, 1.0]), - ] { + for (choice, matte) in [("Black", [0.0, 0.0, 0.0]), ("50% Gray", [128.0 / 255.0; 3]), ("Netscape Gray", [192.0 / 255.0; 3]), ("Other…", [0.0, 0.0, 1.0])] + { let mut session = photocraft_engine::Session::new(); session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); session diff --git a/crates/ui-egui/src/dialogs/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs index f83a260b0d..7378370984 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_ui.rs @@ -334,6 +334,7 @@ mod tests { ChannelTarget::Alpha(0), &[], &Default::default(), + Some((app.session.tools.foreground, app.session.tools.background)), ) .unwrap(); let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/dialogs/filter_preview_worker.rs b/crates/ui-egui/src/dialogs/filter_preview_worker.rs index 0950e67939..ad02315a8c 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_worker.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_worker.rs @@ -123,6 +123,7 @@ mod tests { command: "image.mode.indexedColor".into(), params: json!({"colors": colors}), k: 1, + tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), } } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 829e59e99e..00dc506886 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -17,6 +17,7 @@ fn filter_dialog_with_preview(background: bool) -> (PhotocraftApp, u64) { command: "filter.blur.gaussianBlur".into(), params: serde_json::json!({"radius": 4.0}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); (app, id) diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 1f79f7889c..56e946e7ce 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -3595,3 +3595,4 @@ curves Smooth تنعيم Pick a different document for each channel. اختر مستندًا مختلفًا لكل قناة. A picked document is no longer open. أحد المستندات المختارة لم يعد مفتوحًا. A picked document is no longer a grayscale document of the same size. أحد المستندات المختارة لم يعد مستندًا بتدرج الرمادي بالحجم نفسه. + Netscape Gray رمادي Netscape diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d82218a2b9..718fc73324 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4338,3 +4338,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pro každý kanál vyberte jiný dokument. A picked document is no longer open. Jeden z vybraných dokumentů už není otevřený. A picked document is no longer a grayscale document of the same size. Jeden z vybraných dokumentů už není dokument ve stupních šedi stejné velikosti. + Netscape Gray Šedá Netscape diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 2110c49ab8..87ee2025a1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4808,3 +4808,4 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet Pick a different document for each channel. Vælg et andet dokument til hver kanal. A picked document is no longer open. Et af de valgte dokumenter er ikke længere åbent. A picked document is no longer a grayscale document of the same size. Et af de valgte dokumenter er ikke længere et dokument i gråtoner i samme størrelse. + Netscape Gray Netscape-grå diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6bfdefb09d..ab81180236 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3633,3 +3633,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wählen Sie für jeden Kanal ein anderes Dokument. A picked document is no longer open. Ein ausgewähltes Dokument ist nicht mehr geöffnet. A picked document is no longer a grayscale document of the same size. Ein ausgewähltes Dokument ist kein Graustufen-Dokument derselben Größe mehr. + Netscape Gray Netscape-Grau diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3a76328295..1a8220e34f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4298,3 +4298,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Επιλέξτε διαφορετικό έγγραφο για κάθε κανάλι. A picked document is no longer open. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον ανοιχτό. A picked document is no longer a grayscale document of the same size. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον έγγραφο σε κλίμακα του γκρι ίδιου μεγέθους. + Netscape Gray Γκρι Netscape diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index fd166bb321..213bcebd62 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4498,3 +4498,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Elija un documento distinto para cada canal. A picked document is no longer open. Uno de los documentos elegidos ya no está abierto. A picked document is no longer a grayscale document of the same size. Uno de los documentos elegidos ya no es un documento en escala de grises del mismo tamaño. + Netscape Gray Gris Netscape diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7f3413ceda..aa04ad8424 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4809,3 +4809,4 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen Pick a different document for each channel. Valitse jokaiselle kanavalle eri asiakirja. A picked document is no longer open. Yksi valituista asiakirjoista ei ole enää auki. A picked document is no longer a grayscale document of the same size. Yksi valituista asiakirjoista ei ole enää samankokoinen harmaasävyasiakirja. + Netscape Gray Netscape-harmaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0b4394288d..601390a34a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4621,3 +4621,4 @@ shape Appearance Apparence Pick a different document for each channel. Choisissez un document différent pour chaque canal. A picked document is no longer open. Un des documents choisis n'est plus ouvert. A picked document is no longer a grayscale document of the same size. Un des documents choisis n'est plus un document en niveaux de gris de même taille. + Netscape Gray Gris Netscape diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index aa79f03063..35cdbf8138 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -666,3 +666,4 @@ cameraRaw Yellow पीला Pick a different document for each channel. हर चैनल के लिए अलग डॉक्यूमेंट चुनें। A picked document is no longer open. चुना गया एक डॉक्यूमेंट अब खुला नहीं है। A picked document is no longer a grayscale document of the same size. चुना गया एक डॉक्यूमेंट अब उसी आकार का ग्रेस्केल डॉक्यूमेंट नहीं है। + Netscape Gray Netscape धूसर diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bb919700eb..d990d9b002 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4505,3 +4505,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Minden csatornához másik dokumentumot válasszon. A picked document is no longer open. Az egyik kiválasztott dokumentum már nincs megnyitva. A picked document is no longer a grayscale document of the same size. Az egyik kiválasztott dokumentum már nem azonos méretű szürkeárnyalatos dokumentum. + Netscape Gray Netscape-szürke diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c62378e593..40082c16b9 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3621,3 +3621,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pilih dokumen yang berbeda untuk setiap channel. A picked document is no longer open. Salah satu dokumen yang dipilih sudah tidak terbuka. A picked document is no longer a grayscale document of the same size. Salah satu dokumen yang dipilih bukan lagi dokumen grayscale dengan ukuran yang sama. + Netscape Gray Abu-abu Netscape diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 384e18f2b8..0e63a65417 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4697,3 +4697,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Scegli un documento diverso per ogni canale. A picked document is no longer open. Uno dei documenti scelti non è più aperto. A picked document is no longer a grayscale document of the same size. Uno dei documenti scelti non è più un documento in scala di grigio delle stesse dimensioni. + Netscape Gray Grigio Netscape diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 06f61dcdd0..3df1cdd7e2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4269,3 +4269,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. チャンネルごとに別のドキュメントを選択してください。 A picked document is no longer open. 選択したドキュメントの一つが開かれていません。 A picked document is no longer a grayscale document of the same size. 選択したドキュメントの一つが、同じサイズのグレースケールのドキュメントではなくなりました。 + Netscape Gray Netscape グレー diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index c1bd0d2ca0..acb85fad65 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3824,3 +3824,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 채널마다 다른 문서를 선택하십시오. A picked document is no longer open. 선택한 문서 중 하나가 더 이상 열려 있지 않습니다. A picked document is no longer a grayscale document of the same size. 선택한 문서 중 하나가 더 이상 같은 크기의 회색 음영 문서가 아닙니다. + Netscape Gray Netscape 회색 diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index 3732fa7247..c0361d33d7 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -4808,3 +4808,4 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert Pick a different document for each channel. Velg et annet dokument for hver kanal. A picked document is no longer open. Et av de valgte dokumentene er ikke lenger åpent. A picked document is no longer a grayscale document of the same size. Et av de valgte dokumentene er ikke lenger et dokument i gråtoner av samme størrelse. + Netscape Gray Netscape-grå diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 246214818e..f48c5d85eb 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4352,3 +4352,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Kies voor elk kanaal een ander document. A picked document is no longer open. Een gekozen document is niet meer geopend. A picked document is no longer a grayscale document of the same size. Een gekozen document is geen grijswaardendocument van hetzelfde formaat meer. + Netscape Gray Netscape-grijs diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e40dece48a..2f1ff7c078 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4216,3 +4216,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wybierz inny dokument dla każdego kanału. A picked document is no longer open. Jeden z wybranych dokumentów nie jest już otwarty. A picked document is no longer a grayscale document of the same size. Jeden z wybranych dokumentów nie jest już dokumentem w skali szarości o tym samym rozmiarze. + Netscape Gray Szarość Netscape diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 122ab72265..98953712b7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4512,3 +4512,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Escolha um documento diferente para cada canal. A picked document is no longer open. Um dos documentos escolhidos não está mais aberto. A picked document is no longer a grayscale document of the same size. Um dos documentos escolhidos não é mais um documento em tons de cinza do mesmo tamanho. + Netscape Gray Cinza Netscape diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e66c3f98f3..1fda6074ad 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4783,3 +4783,4 @@ shape Appearance Оформление Pick a different document for each channel. Выберите отдельный документ для каждого канала. A picked document is no longer open. Один из выбранных документов больше не открыт. A picked document is no longer a grayscale document of the same size. Один из выбранных документов больше не является документом в градациях серого того же размера. + Netscape Gray Серый Netscape diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 3e12107087..f4e581e047 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4664,3 +4664,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Izaberite drugi dokument za svaki kanal. A picked document is no longer open. Jedan izabrani dokument više nije otvoren. A picked document is no longer a grayscale document of the same size. Jedan izabrani dokument više nije dokument u nijansama sive iste veličine. + Netscape Gray Netscape siva diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 41c77bea6b..fed35faa1b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4806,3 +4806,4 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen Pick a different document for each channel. Välj ett annat dokument för varje kanal. A picked document is no longer open. Ett av de valda dokumenten är inte längre öppet. A picked document is no longer a grayscale document of the same size. Ett av de valda dokumenten är inte längre ett gråskaledokument i samma storlek. + Netscape Gray Netscape-grå diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6d40778728..7c1f8c13e3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4329,3 +4329,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Her kanal için farklı bir belge seçin. A picked document is no longer open. Seçilen belgelerden biri artık açık değil. A picked document is no longer a grayscale document of the same size. Seçilen belgelerden biri artık aynı boyutta gri tonlamalı bir belge değil. + Netscape Gray Netscape Grisi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bca4b9619b..dbcb296b33 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4309,3 +4309,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Виберіть окремий документ для кожного каналу. A picked document is no longer open. Один із вибраних документів більше не відкрито. A picked document is no longer a grayscale document of the same size. Один із вибраних документів більше не є документом у градаціях сірого того самого розміру. + Netscape Gray Сірий Netscape diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a2f7bd141f..1397fbc39a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4102,3 +4102,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Chọn một tài liệu khác cho mỗi kênh. A picked document is no longer open. Một tài liệu đã chọn không còn mở. A picked document is no longer a grayscale document of the same size. Một tài liệu đã chọn không còn là tài liệu thang xám cùng kích thước. + Netscape Gray Xám Netscape diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d8493b38b1..41a3bedab5 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3290,3 +3290,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 请为每个通道选择不同的文档。 A picked document is no longer open. 所选的一个文档已不再打开。 A picked document is no longer a grayscale document of the same size. 所选的一个文档已不再是同样大小的灰度文档。 + Netscape Gray Netscape 灰色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 170787a915..0acf072c75 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3246,3 +3246,4 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 請為每個色版選擇不同的文件。 A picked document is no longer open. 所選的一個文件已不再開啟。 A picked document is no longer a grayscale document of the same size. 所選的一個文件已不再是相同大小的灰階文件。 + Netscape Gray Netscape 灰色 diff --git a/docs/development.md b/docs/development.md index 79ca11f377..d062dcba34 100644 --- a/docs/development.md +++ b/docs/development.md @@ -667,13 +667,18 @@ opens the picker without replacing the current matte; Cancel leaves that choice OK commits the picked `#rrggbb` in document RGB coordinates. Automation accepts `matte` as `none`, `foreground`, `background`, `white`, `black`, `gray` (50% Gray, encoded `#808080`), `netscapeGray` (Netscape Gray, encoded `#c0c0c0`) or `#rrggbb`. Foreground/background -tool colours are converted from the -working RGB profile into the document profile before blending. A selected matte blends all +tool colours are converted from the working RGB profile into the document profile and clipped +to its encodable RGB range before blending. A selected matte blends all partially transparent edges; with Transparency on, fully clear pixels stay transparent. With Transparency off, the selected matte also fills clear pixels. None retains the existing hard-edged transparency/default flattening behavior. Indexed conversion retains the document's ICC profile and encoded RGB sample representation; matte colours are interpreted in the document -RGB coordinate space. This follows Adobe's documented +RGB coordinate space. Default Indexed → RGB expands the stored RGB samples without converting +them to the working profile; an explicitly supplied destination profile still requests a CMS +conversion. Inline and worker dialog previews inherit the current foreground/background tool +colors, and changing those colors invalidates both cached frames and pending worker results, +including when the preview proxy factor changes. A same-color frame at the old factor can +remain visible during a drag until the new result arrives. This follows Adobe's documented [Indexed Color conversion options](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-modes/conversion-options-for-indexed-color-images.html). `cargo run --release -p photocraft-engine --example indexed_color_perf -- image.png` measures palette construction, Floyd–Steinberg diffusion, and the complete full-resolution CPU preview From fb66c11df6aafe5127b159e897348ab1c3fc73cf Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:35:02 +0100 Subject: [PATCH 060/113] PDF: CodeRabbit SVG signature fix, sampled text colour, Preferences page fields - A PDF named .svg now keeps the PDF importer; other signatures beat the .svg suffix fallback (regression test). - Text layers sample their fill colour from the rendered page and use the PDF font family/name. - File Handling preferences expose pdf_dpi, pdf_first_page and pdf_last_page; the page range maps to ImportOptions.pdf_pages. --- crates/io/src/lib.rs | 35 ++++++++++++++++++++++++++++++++--- crates/io/src/pdf_import.rs | 32 ++++++++++++++++++++++++++++---- 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 599f110410..54a4d1577e 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1028,10 +1028,28 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o pub fn is_svg_input(name: &str, bytes: &[u8]) -> bool { // Keep the SVG extension as a fallback for malformed files so the SVG parser can return an // actionable SVG error. A recognized raster signature still wins over a misleading `.svg` - // suffix (for example, a WebP downloaded as Firefox_logo.svg). + // suffix (for example, a WebP downloaded as Firefox_logo.svg), and so does every other + // format's signature: a PDF named `.svg` must reach the PDF importer. svg::is_svg(bytes) - || (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none()) - || (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b])) + || (has_extension(name, "svg") && photocraft_codecs::detect(bytes).is_none() && !has_format_signature(name, bytes)) + || (has_extension(name, "svgz") && bytes.starts_with(&[0x1f, 0x8b]) && !has_format_signature(name, bytes)) +} + +/// A non-raster format's signature or declared extension, checked before the `.svg` suffix +/// fallback so a misnamed file keeps its own importer. +fn has_format_signature(name: &str, bytes: &[u8]) -> bool { + is_psd(bytes) + || pdf_import::is_pdf(bytes) + || is_psd_input(name, bytes) + || raw::is_raw(bytes) + || affinity::is_affinity(bytes) + || ora::is_ora(bytes) + || kra::is_kra(bytes) + || xcf::is_xcf(bytes) + || has_extension(name, "pdn") + || bytes.starts_with(b"PDN3") + || photocraft_format::is_pcraft(bytes) + || has_extension(name, photocraft_format::EXTENSION) } fn extension(name_or_ext: &str) -> String { @@ -1599,4 +1617,15 @@ mod tests { assert_eq!(d.bounds().height(), 8, "{name}"); } } + + /// A PDF named `.svg` (a save-as mistake) must reach the PDF importer, not the SVG parser; + /// SVG content still wins over a `.pdf` suffix. + #[test] + fn a_pdf_named_svg_stays_a_pdf() { + let pdf = b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"; + assert!(!is_svg_input("drawing.svg", pdf)); + assert!(!is_svg_input("drawing.svgz", pdf)); + assert!(is_svg_input("drawing.svg", b"")); + assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat); + } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index ab77a78b3e..e82bc20c84 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -131,7 +131,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, *h_pt, dpi, x, opts)); + children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &bitmap.as_rgba_bytes(), width, height })); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -147,11 +147,23 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// One rendered page's frame: its point height, DPI, document x, and the RGBA pixels. +struct PageFrame<'a> { + height_pt: f64, + dpi: f64, + x: u32, + rgba: &'a [u8], + width: u32, + height: u32, +} + /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f64, x: u32, opts: &ImportOptions) -> Vec { +fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; + let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; + let to_x = |v: f32| f64::from(v) * dpi / 72.0; let objects = page.objects(); let mut layers = Vec::new(); @@ -166,14 +178,26 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, height_pt: f64, dpi: f6 let x_px = to_x(bounds.left().value).round() + f64::from(x); let y_px = (height_pt - to_x(bounds.top().value)).round(); // The text layer's size is in points; the transform is in document pixels. + // The text object does not expose its fill colour; sample the rendered page at the + // text's centre so the editable layer starts with the right colour. + let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); + let cy = ((height_pt - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); + let i = (cy as usize * page_width as usize + cx as usize) * 4; + let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { + Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) + } else { + Color::BLACK + }; let size_pt = f64::from(text.scaled_font_size().value).max(1.0); + let font = text.font(); + let family = if font.family().is_empty() { font.name() } else { font.family() }; layers.push(Layer::new( "Text", LayerContent::Text(TextLayer { text: content, - font_family: text.font().family(), + font_family: family, size_pt: size_pt as f32, - color: Color::BLACK, + color, transform: Affine::translate(x_px, y_px), ..Default::default() }), From 84644de10225b17c39bae4e5b595abf224854639 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:36:49 +0100 Subject: [PATCH 061/113] PDF: expose the page range as two Preferences numbers --- crates/engine/src/jobs.rs | 5 ++++- crates/engine/src/prefs.rs | 9 ++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index a68606eeba..ddd9ac1f68 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -957,7 +957,10 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), pdf_dpi: prefs.file_handling.pdf_dpi, - pdf_pages: prefs.file_handling.pdf_pages, + pdf_pages: (prefs.file_handling.pdf_first_page > 0).then(|| { + let first = prefs.file_handling.pdf_first_page; + (first, prefs.file_handling.pdf_last_page.max(first)) + }), ..Default::default() } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1750310d26..19c114fa29 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -495,8 +495,10 @@ pub struct FileHandling { pub ignore_exif_profile_tag: bool, /// PDF import resolution in DPI; the document keeps it so the page's print size is preserved. pub pdf_dpi: f32, - /// PDF import page range, 1-based and inclusive; `None` imports every page. - pub pdf_pages: Option<(u32, u32)>, + /// The first PDF page to import (1-based; 0 imports from the first page). + pub pdf_first_page: u32, + /// The last PDF page to import (1-based; 0 imports to the last page). + pub pdf_last_page: u32, /// Most renderers write ACEScg EXRs without stating the colour space. With this on, an EXR /// that would otherwise open as linear sRGB opens as ACEScg (AP1, linear) instead. pub exr_aces_cg: bool, @@ -535,7 +537,8 @@ impl Default for FileHandling { recover_on_launch: true, ignore_exif_profile_tag: false, pdf_dpi: 300.0, - pdf_pages: None, + pdf_first_page: 0, + pdf_last_page: 0, exr_aces_cg: false, ask_before_saving_layered_tiff: true, maximize_psd_compatibility: Ask::Always, From adbe906eaf0fb2c5d669ca6a7330274c3e3e55c0 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:11:03 +0100 Subject: [PATCH 062/113] PDF: fix CI packaging and CodeRabbit findings - Stage pdfium.dll for the MSI fixtures (install-policy payload) and for the real package stage/portable zip; the package script downloads it before cargo. - Regenerate docs/scorecard.md for the new Preferences fields. - Text y positions convert the page height to pixels; invisible PDF text stays hidden. - Page ranges that start past the PDF are refused; zero first/last bounds are independent. --- crates/engine/src/jobs.rs | 11 +++++++---- crates/io/src/pdf_import.rs | 22 +++++++++++++++------- docs/scorecard.md | 4 ++-- packaging/windows/install-policy.json | 3 ++- packaging/windows/package.ps1 | 19 +++++++++++++++++++ 5 files changed, 45 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ddd9ac1f68..13c36a82c1 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -957,10 +957,13 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), pdf_dpi: prefs.file_handling.pdf_dpi, - pdf_pages: (prefs.file_handling.pdf_first_page > 0).then(|| { - let first = prefs.file_handling.pdf_first_page; - (first, prefs.file_handling.pdf_last_page.max(first)) - }), + pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) { + (0, 0) => None, + (first, last) => { + let first = first.max(1); + Some((first, if last == 0 { u32::MAX } else { last.max(first) })) + } + }, ..Default::default() } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index e82bc20c84..48b8d51858 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -43,9 +43,12 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let total = document.pages().len().max(0) as usize; let (first, last) = match opts.pdf_pages { Some((a, b)) => { - let a = (a.max(1) as usize).min(total.max(1)); - let b = (b.max(1) as usize).min(total.max(1)); - (a.min(b), a.max(b)) + let a = a.max(1); + let b = if b == 0 { u32::MAX } else { b.max(a) }; + if u64::from(a) > total as u64 { + return Err(IoError::Unsupported(format!("PDF page range starts at {a}, but the PDF has {total} pages"))); + } + ((a as usize).min(total), (b as usize).min(total)) } None => (1, total), }; @@ -163,6 +166,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f use pdfium_render::prelude::*; let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; + let height_px = height_pt * dpi / 72.0; let to_x = |v: f32| f64::from(v) * dpi / 72.0; let objects = page.objects(); @@ -176,12 +180,12 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } let Ok(bounds) = text.bounds() else { continue }; let x_px = to_x(bounds.left().value).round() + f64::from(x); - let y_px = (height_pt - to_x(bounds.top().value)).round(); + let y_px = (height_px - to_x(bounds.top().value)).round(); // The text layer's size is in points; the transform is in document pixels. // The text object does not expose its fill colour; sample the rendered page at the // text's centre so the editable layer starts with the right colour. let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = ((height_pt - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); + let cy = ((height_px - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); let i = (cy as usize * page_width as usize + cx as usize) * 4; let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) @@ -191,7 +195,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; - layers.push(Layer::new( + let mut layer = Layer::new( "Text", LayerContent::Text(TextLayer { text: content, @@ -201,7 +205,11 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f transform: Affine::translate(x_px, y_px), ..Default::default() }), - )); + ); + if !text.is_visible() { + layer.visible = false; + } + layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { let mut subpaths: Vec = Vec::new(); diff --git a/docs/scorecard.md b/docs/scorecard.md index a3ecd984cb..ece2924bed 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 192 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 195 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 660 of 660 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 192** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 195** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json index fcba1850ae..8d01fab4ac 100644 --- a/packaging/windows/install-policy.json +++ b/packaging/windows/install-policy.json @@ -15,7 +15,8 @@ ], "payloads": [ "photocraft-cli.exe", - "photocraft.exe" + "photocraft.exe", + "pdfium.dll" ], "registry": [ [ diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index d984e3930a..1f072fedb5 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -55,6 +55,23 @@ New-Item -ItemType Directory -Force -Path $Dist | Out-Null if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's +# build script copies it beside the exe and both the MSI and the portable ZIP ship it. +$PdfiumDir = Join-Path $Root "target\pdfium\$Arch" +$PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' +if (-not (Test-Path -LiteralPath $PdfiumDll)) { + $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" + Invoke-Native "download PDFium ($Arch)" { + Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-win-$Arch.tgz" -OutFile $tgz + New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null + tar -xzf $tgz -C $PdfiumDir + $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' + if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } + Move-Item -Force $extracted $PdfiumDll + } +} +$env:PDFIUM_DLL = $PdfiumDll + Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -89,6 +106,7 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage +Copy-Item -LiteralPath $PdfiumDll -Destination $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -171,6 +189,7 @@ $Portable = Join-Path $TargetDir "windows-package\photocraft-$Version-windows-$A Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable +Copy-Item -LiteralPath $PdfiumDll -Destination $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } From 393ccdc124ba97e529e673bca1b9c800897d8d00 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 11:25:47 -0800 Subject: [PATCH 063/113] Match measured Free Transform edge handle zones --- .../src/canvas/transform_controls_tests.rs | 13 ++-- .../src/tools/transform_tool/pointer.rs | 65 +++++++++++-------- .../ui-egui/src/transform_hit_zone_tests.rs | 43 ++++++++++-- 3 files changed, 78 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/canvas/transform_controls_tests.rs b/crates/ui-egui/src/canvas/transform_controls_tests.rs index c977a84d6d..ef5e5668d3 100644 --- a/crates/ui-egui/src/canvas/transform_controls_tests.rs +++ b/crates/ui-egui/src/canvas/transform_controls_tests.rs @@ -323,18 +323,14 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti (r.center_bottom(), egui::CursorIcon::ResizeVertical), (r.right_center(), egui::CursorIcon::ResizeHorizontal), (r.left_center(), egui::CursorIcon::ResizeHorizontal), - // An outward edge band resizes between handles. Beyond it the curved rotate arrow - // replaces the pointer (#4658). - (pos2(r.left() + r.width() * 0.25, r.top() - 11.0), egui::CursorIcon::ResizeVertical), + // Just beyond the outward edge band, the curved rotate arrow replaces the pointer (#4658). (pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None), ] { assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}"); assert!(transform_controls_hit(r, p), "same region must start a transform"); } assert_eq!(transform_controls_cursor(r, r.center()), Some(egui::CursorIcon::Default), "interior stays Move"); - let far = pos2(r.center().x, r.top() - 30.0); - assert_eq!(transform_controls_cursor(r, far), Some(egui::CursorIcon::None)); - assert!(!transform_controls_hit(r, far), "far hover must not consume a Move press"); + assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), Some(egui::CursorIcon::None)); // The rotate arrow points into the nearest edge or corner. Handles and the interior have none. let into = |p: Pos2| transform_controls_turn(r, p); assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some(vec2(0.0, 16.0)), "top edge"); @@ -353,11 +349,10 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti } #[test] -fn transform_control_hit_resizes_or_rotates_within_the_press_zones() { +fn transform_control_hit_keeps_move_interior_free_and_has_rotation_band() { let r = Rect::from_min_max(pos2(20.0, 30.0), pos2(100.0, 70.0)); assert!(transform_controls_hit(r, r.left_top())); assert!(transform_controls_hit(r, pos2(60.0, 18.0))); assert!(!transform_controls_hit(r, r.center())); - assert!(transform_controls_hit(r, pos2(60.0, 12.0)), "the 18-point rotation band still starts a transform"); - assert!(!transform_controls_hit(r, pos2(60.0, 11.0)), "beyond the band a press stays with Move"); + assert!(!transform_controls_hit(r, pos2(60.0, 4.0))); } diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index e1457bf208..04ae5ad522 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -19,8 +19,8 @@ pub(crate) enum Hit { /// Screen-sized corner and outward edge bands, shared with Move's unopened controls. impl TransformSession { /// Classify a document point with screen-sized corner and outward edge zones. - /// Corners outrank free edge bands; overlapping painted handles keep nearest-handle priority. - /// Only projection-scale rounding is treated as an edge on the interior side. + /// On and outward from an edge, the nearest corner or midpoint wins, with the corner + /// reach capped along the edge. Inside and beyond the edge ends use the corner radius. pub(crate) fn box_hit(quad: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> Hit { // `tol` is the existing 12 pt handle tolerance, divided by the view zoom. let corner_radius = tol * (8.0 / HANDLE_PX); @@ -30,32 +30,40 @@ impl TransformSession { let line_epsilon = tol.abs() * (1e-3 / HANDLE_PX); let distance = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); let interior = inside(quad, p); - let edge_distance = |i| { - let (_, q) = edge_projection(quad, i, p)?; - let d = distance(q); - (d <= edge_width && (!interior || d <= line_epsilon)).then_some(d) - }; - if let Some((i, corner_distance)) = + let edge = (0..4) + .filter_map(|i| { + let (u, q) = edge_projection(quad, i, p)?; + let d = distance(q); + (d <= edge_width && (!interior || d <= line_epsilon)).then_some((i, u, d)) + }) + .min_by(|a, b| a.2.total_cmp(&b.2)); + if let Some((i, u, _)) = edge + && (0.0..=1.0).contains(&u) + { + let next = (i + 1) % 4; + let (a, b) = (quad[i], quad[next]); + let length = (b[0] - a[0]).hypot(b[1] - a[1]); + let quarter = length * 0.25; + let tie_epsilon = line_epsilon.min(quarter * 0.5); + // Projected distances rank the handles along this edge. At the measured + // quarter-point ties, prefer the earlier handle in edge order. + let from_start = u * length; + let from_end = (1.0 - u) * length; + if from_start <= quarter + tie_epsilon && from_start <= edge_width + line_epsilon { + return Hit::Corner(i); + } + if from_end < quarter - tie_epsilon && from_end <= edge_width + line_epsilon { + return Hit::Corner(next); + } + return Hit::Edge(i); + } + if let Some((i, _)) = quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) { - // Preserve nearest-handle priority only when the midpoint itself falls in the - // corner zone. A separate midpoint must not take over a nearby corner press. - let painted_edge = (0..4) - .filter_map(|k| { - edge_distance(k)?; - let (a, b) = (quad[k], quad[(k + 1) % 4]); - let midpoint = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; - let corner = quad[i]; - let d = distance(midpoint); - let overlaps_corner = (midpoint[0] - corner[0]).hypot(midpoint[1] - corner[1]) <= corner_radius; - (overlaps_corner && d < corner_distance).then_some((k, d)) - }) - .min_by(|a, b| a.1.total_cmp(&b.1)); - return painted_edge.map_or(Hit::Corner(i), |(k, _)| Hit::Edge(k)); + return Hit::Corner(i); } - let edge = (0..4).filter_map(|i| edge_distance(i).map(|d| (i, d))).min_by(|a, b| a.1.total_cmp(&b.1)); match edge { - Some((i, _)) => Hit::Edge(i), + Some((i, _, _)) => Hit::Edge(i), None if interior => Hit::Inside, None => Hit::Outside, } @@ -95,8 +103,8 @@ impl TransformSession { } } -/// The nearest point on an edge segment and its clamped parameter. Degenerate edges have no -/// band or normal; the other edges and corner handles remain usable. +/// The unclamped projection parameter and the nearest point on the segment. Degenerate +/// edges have no band or normal; the other edges and corner handles remain usable. fn edge_projection(quad: &[[f64; 2]; 4], i: usize, p: [f64; 2]) -> Option<(f64, [f64; 2])> { let (a, b) = (quad[i], quad[(i + 1) % 4]); let d = [b[0] - a[0], b[1] - a[1]]; @@ -104,8 +112,9 @@ fn edge_projection(quad: &[[f64; 2]; 4], i: usize, p: [f64; 2]) -> Option<(f64, if !len2.is_finite() || len2 <= 1e-18 { return None; } - let u = (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / len2).clamp(0.0, 1.0); - Some((u, [a[0] + u * d[0], a[1] + u * d[1]])) + let u = ((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / len2; + let on_segment = u.clamp(0.0, 1.0); + Some((u, [a[0] + on_segment * d[0], a[1] + on_segment * d[1]])) } /// The shared box zones, retaining the nearest pivot's existing grab priority on small boxes. diff --git a/crates/ui-egui/src/transform_hit_zone_tests.rs b/crates/ui-egui/src/transform_hit_zone_tests.rs index 394e32a278..9cd109b9e5 100644 --- a/crates/ui-egui/src/transform_hit_zone_tests.rs +++ b/crates/ui-egui/src/transform_hit_zone_tests.rs @@ -94,13 +94,39 @@ fn small_boxes_keep_their_painted_mid_edge_handles() { } } +/// Match the measured #11097 boundaries and ties on the top edge and one point outside it. #[test] -fn a_midpoint_outside_the_corner_zone_cannot_steal_its_press() { - for zoom in [1.0, 2.0] { - let quad = [[0.0, 0.0], [20.0, 0.0], [20.0, 20.0], [0.0, 20.0]].map(|p| p.map(|v| v / zoom)); - let tol = 12.0 / zoom; - assert_eq!(TransformSession::box_hit(&quad, [7.0 / zoom, -1.0 / zoom], tol), Hit::Corner(0)); - assert_eq!(TransformSession::box_hit(&quad, [9.0 / zoom, 0.0], tol), Hit::Edge(0)); +fn measured_edge_corner_and_midpoint_zones_at_100_and_200_percent() { + use Hit::{Corner, Edge}; + let matrix: &[(f64, &[(f64, Hit)])] = &[ + (12.0, &[(3.0, Corner(0)), (4.0, Edge(0)), (5.0, Edge(0)), (6.0, Edge(0)), (9.0, Edge(0)), (10.0, Corner(1))]), + (24.0, &[(6.0, Corner(0)), (7.0, Edge(0)), (18.0, Edge(0)), (19.0, Corner(1))]), + (40.0, &[(10.0, Corner(0)), (11.0, Edge(0)), (30.0, Edge(0)), (31.0, Corner(1))]), + (100.0, &[(11.0, Corner(0)), (12.0, Edge(0))]), + ]; + for zoom in [1.0_f32, 2.0] { + let scale = |p: [f64; 2]| p.map(|v| v / f64::from(zoom)); + let xf = view(zoom); + for &(side, samples) in matrix { + let quad = [[0.0, 0.0], [side, 0.0], [side, side], [0.0, side]].map(scale); + let mut app = app(quad, zoom); + app.ui.tool_options.transform_reference_point = false; + let t = app.ui.transform.as_ref().unwrap(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(side as f32, side as f32)); + for y in [0.0, -1.0] { + for &(x, expected) in samples { + let p = scale([x, y]); + let icon = match expected { + Corner(0) => CursorIcon::ResizeNwSe, + Corner(1) => CursorIcon::ResizeNeSw, + _ => CursorIcon::ResizeVertical, + }; + assert_eq!(crate::transform_tool::box_hit(&app, t, p, 12.0 / f64::from(zoom)), expected, "{side}, {zoom}, {x}, {y}"); + assert_eq!(cursor(&app, &xf, p, Modifiers::NONE), Some(icon)); + assert_eq!(transform_controls_cursor(rect, pos2(x as f32, y as f32)), Some(icon)); + } + } + } } } @@ -169,6 +195,8 @@ fn turned_box_zones_and_resize_cursors_follow_the_quad() { let t = app.ui.transform.as_ref().unwrap(); for (p, expected, icon) in [ ([500.0, 100.0], Hit::Corner(1), CursorIcon::ResizeHorizontal), + ([111.0, 99.0], Hit::Corner(0), CursorIcon::ResizeVertical), + ([112.0, 99.0], Hit::Edge(0), CursorIcon::ResizeNeSw), ([180.0, 95.0], Hit::Edge(0), CursorIcon::ResizeNeSw), ([505.0, 150.0], Hit::Edge(1), CursorIcon::ResizeNwSe), ([180.0, 101.0], Hit::Inside, CursorIcon::Default), @@ -268,8 +296,11 @@ fn unopened_move_controls_share_hover_but_keep_the_move_press_band() { for (p, starts_transform) in [ (pos2(100.0, 100.0), true), (pos2(180.0, 95.0), true), + (pos2(180.0, 89.0), true), (pos2(505.0, 150.0), true), (pos2(518.0, 150.0), true), + (pos2(519.0, 150.0), false), + (pos2(300.0, 70.0), false), (pos2(180.0, 101.0), false), (pos2(620.0, 200.0), false), (pos2(-20.0, -20.0), false), From 90c03eba3988f69834a830318fa4e2af86bff222 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 6 Nov 2026 11:30:26 -0800 Subject: [PATCH 064/113] Format Free Transform corner fallback --- crates/ui-egui/src/tools/transform_tool/pointer.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 04ae5ad522..49f0c3a06b 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -57,9 +57,7 @@ impl TransformSession { } return Hit::Edge(i); } - if let Some((i, _)) = - quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) - { + if let Some((i, _)) = quad.iter().enumerate().map(|(i, &q)| (i, distance(q))).filter(|(_, d)| *d <= corner_radius).min_by(|a, b| a.1.total_cmp(&b.1)) { return Hit::Corner(i); } match edge { From 36e7c50178460e2b45a9245c7d0079c9f3169e54 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:34:01 +0100 Subject: [PATCH 065/113] PDF: transform imported paths by their object matrix - Apply PdfPageObject::matrix() to path segments: PDFium returns raw object-space points, so scaled or rotated paths landed in the wrong place. - Flip path y with the page height in pixels, not points; paths were off-canvas at any DPI other than 72. - Take fill and stroke presence from the path's draw mode: stroke-only paths no longer get a black fill, and paths that are neither filled nor stroked are skipped. - Estimate import pixel memory as retained tiles (4 B/px over all pages) plus the converting page's peak (24 B/px), defaulting to a 2 GiB budget when the caller sets none. Reuse the RGBA copy and reserve the f32 buffer fallibly. --- crates/io/src/pdf_import.rs | 49 ++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 48b8d51858..34db0767d8 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -36,6 +36,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. const MAX_PAGE_PIXELS: f64 = 100_000_000.0; const MAX_UNION_PIXELS: u64 = 200_000_000; + /// The default pixel-memory budget when the caller sets none: a zero + /// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import. + const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30; let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; let pdfium = bind()?; @@ -76,15 +79,20 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if doc_width == 0 || doc_height == 0 { return Err(IoError::Unsupported("PDF pages have no area".into())); } - // The aggregate budget: the rendered pages and the document's raster tiles both hold pixels. - let page_pixels = sizes.iter().map(|(w, h)| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0)).sum::(); - // The RGBA bitmap, the f32 conversion buffer (16 bytes/px) and the document tiles. - let estimate = (page_pixels * 24.0) as u64; - if opts.flat_max_pixel_bytes > 0 && estimate > opts.flat_max_pixel_bytes { + // The aggregate budget: the document keeps every page's raster tiles, while one page at a + // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. + let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); + let page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).sum::(); + let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); + // 4 bytes/px of retained RGBA tiles for every page, plus 24 bytes/px (bitmap, RGBA copy, + // f32 conversion buffer) for the page being converted. + let estimate = (page_pixels * 4.0 + max_page_pixels * 24.0) as u64; + let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; + if estimate > budget { return Err(IoError::Unsupported(format!( "PDF import needs about {} MB of pixel memory; the limit is {} MB (lower the import DPI)", estimate >> 20, - opts.flat_max_pixel_bytes >> 20 + budget >> 20 ))); } let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); @@ -122,7 +130,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); let rgba = bitmap.as_rgba_bytes(); - let mut data = Vec::with_capacity(rgba.len()); + let mut data = Vec::new(); + if data.try_reserve_exact(rgba.len()).is_err() { + return Err(IoError::Unsupported(format!("PDF page {} needs more memory than is available", page_index + 1))); + } for chunk in rgba.as_chunks::<4>().0 { for &v in &chunk[..3] { data.push(f32::from(v) / 255.0); @@ -134,7 +145,7 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &bitmap.as_rgba_bytes(), width, height })); + children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &rgba, width, height })); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -212,12 +223,21 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { + // PDFium reports the segments in object space; the object's matrix places them on + // the page. Without it, scaled or rotated paths land in the wrong place. + let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); + // The fill and stroke modes are exposed; the colours and dash pattern are not. + let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); + let stroked = path.is_stroked().unwrap_or(false); + if !filled && !stroked { + continue; + } let mut subpaths: Vec = Vec::new(); let mut knots: Vec = Vec::new(); let mut closed = false; let mut bezier: Vec<(f64, f64)> = Vec::new(); - for segment in path.segments().iter() { - let point = || (to_x(segment.x().value).round(), (height_pt - to_x(segment.y().value)).round()); + for segment in path.segments().transform(matrix).iter() { + let point = || (to_x(segment.x().value).round(), (height_px - to_x(segment.y().value)).round()); if segment.is_close() { closed = true; continue; @@ -257,10 +277,15 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if subpaths.is_empty() { continue; } - let stroke = path.is_stroked().unwrap_or(false).then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); layers.push(Layer::new( "Path", - LayerContent::Shape(ShapeLayer { path: Path::new(subpaths), fill: Some(Fill::Solid(Color::BLACK)), stroke, ..Default::default() }), + LayerContent::Shape(ShapeLayer { + path: Path::new(subpaths), + fill: filled.then_some(Fill::Solid(Color::BLACK)), + stroke, + ..Default::default() + }), )); } _ => {} From 192b075bfacb1b805c0fdcb83e0534eb0c033299 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:29:06 +0100 Subject: [PATCH 066/113] PDF: map editable objects through one page-to-document transform - Paths on page 2+ were placed without the page's document X offset; text and paths now share PageFrame::to_doc, which applies the DPI scale, the Y flip and the page offset in one place. - Flip Y in pixels and round once, so text placement, text colour sampling and path points all stay in the same coordinate system. - Add unit tests for 72/300 dpi, the page-2 offset and the sampled colour; they need no PDFium. --- crates/io/src/pdf_import.rs | 71 ++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 34db0767d8..0597354826 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -171,15 +171,32 @@ struct PageFrame<'a> { height: u32, } +impl PageFrame<'_> { + /// Maps a point in PDF page space (points, origin bottom-left) to document pixels: the Y flip + /// and the page's X offset both belong to this mapping. + fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { + let x_px = f64::from(x_pt) * self.dpi / 72.0 + f64::from(self.x); + let y_px = (self.height_pt - f64::from(y_pt)) * self.dpi / 72.0; + (x_px.round(), y_px.round()) + } + + /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. + fn color_at(&self, x: u32, y: u32) -> Color { + let i = (y as usize * self.width as usize + x as usize) * 4; + if i + 3 < self.rgba.len() && self.rgba[i + 3] > 0 { + Color::rgb(f32::from(self.rgba[i]) / 255.0, f32::from(self.rgba[i + 1]) / 255.0, f32::from(self.rgba[i + 2]) / 255.0) + } else { + Color::BLACK + } + } +} + /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; - let PageFrame { height_pt, dpi, x, rgba, width: page_width, height: page_height } = *frame; - let height_px = height_pt * dpi / 72.0; - - let to_x = |v: f32| f64::from(v) * dpi / 72.0; + let PageFrame { x, width: page_width, height: page_height, .. } = *frame; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { @@ -190,19 +207,13 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f continue; } let Ok(bounds) = text.bounds() else { continue }; - let x_px = to_x(bounds.left().value).round() + f64::from(x); - let y_px = (height_px - to_x(bounds.top().value)).round(); + let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); // The text layer's size is in points; the transform is in document pixels. // The text object does not expose its fill colour; sample the rendered page at the - // text's centre so the editable layer starts with the right colour. - let cx = (to_x(bounds.left().value).round().max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = ((height_px - to_x(bounds.top().value)).round().max(0.0) as u32).min(page_height.saturating_sub(1)); - let i = (cy as usize * page_width as usize + cx as usize) * 4; - let color = if i + 3 < rgba.len() && rgba[i + 3] > 0 { - Color::rgb(f32::from(rgba[i]) / 255.0, f32::from(rgba[i + 1]) / 255.0, f32::from(rgba[i + 2]) / 255.0) - } else { - Color::BLACK - }; + // text's top-left corner so the editable layer starts with the right colour. + let cx = ((x_px - f64::from(x)).max(0.0) as u32).min(page_width.saturating_sub(1)); + let cy = (y_px.max(0.0) as u32).min(page_height.saturating_sub(1)); + let color = frame.color_at(cx, cy); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; @@ -237,7 +248,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let mut closed = false; let mut bezier: Vec<(f64, f64)> = Vec::new(); for segment in path.segments().transform(matrix).iter() { - let point = || (to_x(segment.x().value).round(), (height_px - to_x(segment.y().value)).round()); + let point = || frame.to_doc(segment.x().value, segment.y().value); if segment.is_close() { closed = true; continue; @@ -331,3 +342,31 @@ fn bind() -> Result { })?; Ok(Pdfium::new(bindings)) } + +#[cfg(test)] +mod tests { + use super::PageFrame; + + fn frame(dpi: f64, x: u32) -> PageFrame<'static> { + PageFrame { height_pt: 842.0, dpi, x, rgba: &[], width: 595, height: 842 } + } + + #[test] + fn page_points_map_to_document_pixels() { + assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); + // The same point at four times the resolution. + assert_eq!(frame(300.0, 0).to_doc(60.0, 420.0), (250.0, 1758.0)); + // Page 2 starts after page 1's width: the document X offset is part of the mapping. + assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); + } + + #[test] + fn samples_the_rendered_page() { + // Two pixels: white then black. + let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; + let page = PageFrame { height_pt: 842.0, dpi: 72.0, x: 0, rgba: &rgba, width: 2, height: 1 }; + assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); + assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); + assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); + } +} From fabfbb5d5a2f7a727d1658244a736874752ca19b Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:15:50 +0100 Subject: [PATCH 067/113] PDF: fix segment closing, admission, glyph colour and PDFium reuse - Process a closing segment's own geometry before marking the subpath closed, so a closing Bezier endpoint cannot leak control points into the next curve. - Estimate retained memory from tile-aligned page bounds (including the page's X offset) instead of raw pixels: a 1 x 10,000 px page admits its 40 tiles, not 10,000 pixels. - Sample text colour from the glyph ink (the pixel farthest from the box's dominant colour) instead of the bounds' top-left corner, which was usually background or antialiasing. - Cache the PDFium bind: pdfium-render binds once per process, so a second PDF import in one session failed with PdfiumLibraryBindingsAlreadyInitialized. - Add a PDFium-backed two-page end-to-end test with a transformed path on page 2 and non-origin red/green text at 72 and 300 dpi; it prints an explicit SKIPPED line when PDFium is unavailable. - package.ps1: pin pdfium-binaries chromium/8138, verify the archive and any cached DLL against SHA-256, drop a stale bin/pdfium.dll before extraction and check tar's exit status. --- crates/io/src/pdf_import.rs | 137 +++++++++++++++++++++++------ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/pdf_import.rs | 143 +++++++++++++++++++++++++++++++ packaging/windows/package.ps1 | 40 ++++++++- 4 files changed, 291 insertions(+), 30 deletions(-) create mode 100644 crates/io/tests/it/pdf_import.rs diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 0597354826..679198ff8b 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -82,11 +82,21 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - // The aggregate budget: the document keeps every page's raster tiles, while one page at a // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); - let page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).sum::(); let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); - // 4 bytes/px of retained RGBA tiles for every page, plus 24 bytes/px (bitmap, RGBA copy, - // f32 conversion buffer) for the page being converted. - let estimate = (page_pixels * 4.0 + max_page_pixels * 24.0) as u64; + // Retained backing: a page occupies whole 256 px tiles, including the ones its document X + // offset steps into. A 1 x 10,000 px page is 40 tiles (10 MiB), not 10,000 pixels. + const TILE: u64 = 256; + let mut retained: u64 = 0; + let mut page_x: u64 = 0; + for &(w, h) in &sizes { + let px = (w * dpi / 72.0).round().max(1.0) as u64; + let py = (h * dpi / 72.0).round().max(1.0) as u64; + let tiles_x = (page_x + px).div_ceil(TILE) - page_x / TILE; + retained = retained.saturating_add(tiles_x.saturating_mul(py.div_ceil(TILE)).saturating_mul(TILE * TILE * 4)); + page_x += px + u64::from(GAP); + } + // Plus 24 bytes/px (bitmap, RGBA copy, f32 conversion buffer) for the page being converted. + let estimate = retained.saturating_add((max_page_pixels * 24.0) as u64); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -189,6 +199,56 @@ impl PageFrame<'_> { Color::BLACK } } + + /// The ink colour of the text in `bounds` (page points). + /// + /// The box holds both glyphs and the page behind them, so sampling one corner usually finds + /// background or an antialiased edge. Take the pixel farthest from the box's most common + /// colour instead: for dark text on a light page that is a glyph core, and for light text on a + /// dark page it is the glyph rather than the background. + fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { + let x0 = (f64::from(left) * self.dpi / 72.0).floor().max(0.0) as u32; + let x1 = (f64::from(right) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.width)) as u32; + // PDF's Y grows up; the rendered page's Y grows down. + let y0 = ((self.height_pt - f64::from(top)) * self.dpi / 72.0).floor().max(0.0) as u32; + let y1 = ((self.height_pt - f64::from(bottom)) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.height)) as u32; + if x1 <= x0 || y1 <= y0 { + return Color::BLACK; + } + // At most ~4096 samples, so a page-sized text box stays cheap. + let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); + let mut samples: Vec<[f32; 3]> = Vec::new(); + let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); + let mut y = y0; + while y < y1 { + let mut x = x0; + while x < x1 { + let c = self.color_at(x, y); + let rgb = [c.c[0], c.c[1], c.c[2]]; + let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; + let entry = buckets.entry(key).or_insert((0, [0.0; 3])); + entry.0 += 1; + for (sum, v) in entry.1.iter_mut().zip(rgb) { + *sum += v; + } + samples.push(rgb); + x += step; + } + y += step; + } + let Some((_, (count, sum))) = buckets.iter().max_by_key(|(_, (count, _))| *count) else { return Color::BLACK }; + let mode = [sum[0] / *count as f32, sum[1] / *count as f32, sum[2] / *count as f32]; + let mut best = mode; + let mut best_distance = -1.0f32; + for rgb in samples { + let distance = (rgb[0] - mode[0]).powi(2) + (rgb[1] - mode[1]).powi(2) + (rgb[2] - mode[2]).powi(2); + if distance > best_distance { + best_distance = distance; + best = rgb; + } + } + Color::rgb(best[0], best[1], best[2]) + } } /// Editable text and shape layers for one rendered page, in document pixels. @@ -196,7 +256,6 @@ impl PageFrame<'_> { fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { use pdfium_render::prelude::*; - let PageFrame { x, width: page_width, height: page_height, .. } = *frame; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { @@ -208,12 +267,9 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } let Ok(bounds) = text.bounds() else { continue }; let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. - // The text object does not expose its fill colour; sample the rendered page at the - // text's top-left corner so the editable layer starts with the right colour. - let cx = ((x_px - f64::from(x)).max(0.0) as u32).min(page_width.saturating_sub(1)); - let cy = (y_px.max(0.0) as u32).min(page_height.saturating_sub(1)); - let color = frame.color_at(cx, cy); + // The text layer's size is in points; the transform is in document pixels. The + // text object does not expose its fill colour; sample the glyph ink from the page. + let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); let family = if font.family().is_empty() { font.name() } else { font.family() }; @@ -249,10 +305,6 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f let mut bezier: Vec<(f64, f64)> = Vec::new(); for segment in path.segments().transform(matrix).iter() { let point = || frame.to_doc(segment.x().value, segment.y().value); - if segment.is_close() { - closed = true; - continue; - } match segment.segment_type() { PdfPathSegmentType::MoveTo => { if !knots.is_empty() { @@ -281,6 +333,11 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f } PdfPathSegmentType::Unknown => {} } + // A closing segment can also be the endpoint that closes a Bézier; process it + // above before marking the subpath closed so its control points are consumed. + if segment.is_close() { + closed = true; + } } if !knots.is_empty() { subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); @@ -325,22 +382,35 @@ fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, } /// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). +/// +/// pdfium-render keeps the bindings in a process-wide static: the first import initializes them +/// and later `bind_to_library` calls fail with `PdfiumLibraryBindingsAlreadyInitialized`. Remember +/// the outcome and reuse the initialized bindings, so opening a second PDF in one session works. #[cfg(not(target_arch = "wasm32"))] fn bind() -> Result { use pdfium_render::prelude::Pdfium; - let dir = std::env::var_os("PDFIUM_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); - let library = Pdfium::pdfium_platform_library_name_at_path(&dir); - let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); - let bindings = Pdfium::bind_to_library(&library).map_err(|e| { - IoError::Unsupported(format!( - "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", - library.display() - )) - })?; - Ok(Pdfium::new(bindings)) + static INIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let init = INIT.get_or_init(|| { + let dir = std::env::var_os("PDFIUM_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); + let library = Pdfium::pdfium_platform_library_name_at_path(&dir); + let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); + match Pdfium::bind_to_library(&library) { + Ok(bindings) => { + // Initializes the library inside pdfium-render's process-wide bindings. + drop(Pdfium::new(bindings)); + Ok(()) + } + Err(e) => Err(format!("PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display())), + } + }); + match init { + // The bindings are already initialized; `default()` re-uses them. + Ok(()) => Ok(Pdfium::default()), + Err(message) => Err(IoError::Unsupported(message.clone())), + } } #[cfg(test)] @@ -369,4 +439,17 @@ mod tests { assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); } + + #[test] + fn text_colour_samples_the_glyph_ink() { + // An 8 x 4 white page with one black glyph pixel at (2, 1). + let mut rgba = vec![255u8; 8 * 4 * 4]; + let glyph = (8 + 2) * 4; + rgba[glyph..glyph + 3].fill(0); + let page = PageFrame { height_pt: 4.0, dpi: 72.0, x: 0, rgba: &rgba, width: 8, height: 4 }; + // The whole page box contains the glyph: the ink wins over the white background. + assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); + // A box that contains only background keeps the background colour. + assert_eq!(page.text_color(4.0, 4.0, 8.0, 2.0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); + } } diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index db6fc6cdf3..476818fa44 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -44,6 +44,7 @@ mod orientation; mod pattern_fill_psd; mod pcraft_full_composite; mod pcraft_manifest_name; +mod pdf_import; mod pdn_corpus; mod png_steps; mod png_text_metadata; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs new file mode 100644 index 0000000000..0e1c36eba2 --- /dev/null +++ b/crates/io/tests/it/pdf_import.rs @@ -0,0 +1,143 @@ +//! PDF import end-to-end through PDFium. +//! +//! A synthetic two-page PDF with non-origin red text, a transformed blue rectangle and green text +//! is imported at 72 and 300 DPI, and the resulting editable layers are checked against the +//! fixture's geometry and pixels. PDFium is loaded at run time: when it is unavailable (no +//! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and +//! returns instead of pretending the end-to-end wiring passed. + +use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; +use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; +use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; + +const PAGE_W: f64 = 200.0; +const PAGE_H: f64 = 100.0; +const GAP: f64 = 80.0; + +#[test] +fn imports_text_and_a_transformed_path_on_two_pages() { + let pdf = two_page_pdf(); + for dpi in [72.0f32, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { + Ok(result) => result, + Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { + eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); + return; + } + Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), + }; + check(&result.document, dpi); + } +} + +/// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by +/// (10, 5) — corners (30, 25)..(70, 45) — plus green 48 pt text at (20, 20). +fn two_page_pdf() -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let font_id = pdf.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "Type1", + "BaseFont" => "Helvetica", + }); + let resources = pdf.add_object(dictionary! { + "Font" => dictionary! { "F1" => font_id }, + }); + let contents = ["1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", "0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET"]; + let mut kids = Vec::new(); + for content in contents { + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![0.into(), 0.into(), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "Contents" => content_id, + "Resources" => resources, + }); + kids.push(Object::Reference(page_id)); + } + let count = kids.len() as i64; + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => count, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the PDF fixture"); + bytes +} + +fn check(document: &Document, dpi: f32) { + let scale = f64::from(dpi) / 72.0; + let page_two_x = (PAGE_W * scale).round() + GAP; + + // Page 1: the editable text keeps its position and takes the red ink from the page. + let text = text_layer(page_children(document, 1)); + assert_red(&text.color, "page 1 text"); + let x = text.transform.m[4]; + let y = text.transform.m[5]; + assert!((x - 20.0 * scale).abs() < 8.0 * scale, "page 1 text x is {x} at {dpi} dpi"); + // 48 pt Helvetica's bounds top is about 35 pt above the baseline at y = 50. + assert!((y - 15.0 * scale).abs() < 20.0 * scale, "page 1 text y is {y} at {dpi} dpi"); + + // Page 2: the transformed rectangle lands at (30, 25)..(70, 45) plus the page's document X. + let shape = shape_layer(page_children(document, 2)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + assert!((min_x - (page_two_x + 30.0 * scale)).abs() < 4.0, "path min x is {min_x}, page 2 starts at {page_two_x} ({dpi} dpi)"); + assert!((max_x - (page_two_x + 70.0 * scale)).abs() < 4.0, "path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - (PAGE_H - 45.0) * scale).abs() < 4.0, "path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - (PAGE_H - 25.0) * scale).abs() < 4.0, "path max y is {max_y} ({dpi} dpi)"); + + let text = text_layer(page_children(document, 2)); + assert_green(&text.color, "page 2 text"); + assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); +} + +fn page_children(document: &Document, page: usize) -> &[Layer] { + let name = format!("Page {page}"); + let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); + match &layer.content { + LayerContent::Group(group) => &group.children, + _ => panic!("{name} is not a group"), + } +} + +fn text_layer(children: &[Layer]) -> &TextLayer { + children + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Text(text) => Some(text), + _ => None, + }) + .expect("a text layer") +} + +fn shape_layer(children: &[Layer]) -> &ShapeLayer { + children + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Shape(shape) => Some(shape), + _ => None, + }) + .expect("a shape layer") +} + +fn assert_red(color: &Color, what: &str) { + assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); +} + +fn assert_green(color: &Color, what: &str) { + assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); +} diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 1f072fedb5..6efb64e770 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -57,17 +57,51 @@ if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).T # PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's # build script copies it beside the exe and both the MSI and the portable ZIP ship it. +# +# Pinned to a reviewed pdfium-binaries release: the archive is verified before extraction and a +# cached DLL is verified before reuse, so a moved or compromised "latest" cannot be packaged. +# Bump the release and both hashes together after re-checking the published build. +$PdfiumRelease = 'chromium/8138' +$PdfiumArchiveSha256 = @{ + x64 = '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5' + x86 = '5c32d44711a73ed8ae86b85322078da8444fc696b9326527eed2d9fcd620fc84' + arm64 = '5e04abdb36ba9b4b5c8630123eaf042036f8a62abda6e5529708fee3d35fbf4f' +} +$PdfiumDllSha256 = @{ + x64 = '71a3e63e6ab8f5746a0fc9de9bc3d0c0dc07eb60990dfd37d9db7fc891821943' + x86 = 'ee592bd01eaef454aada95ed483ceca1c4f6ce0f0b9568608f40c3861fbda035' + arm64 = '0b1b9a52b3297448cbe461ffbca1455603d85161d5e96090e1a89bd7c4a62a33' +} $PdfiumDir = Join-Path $Root "target\pdfium\$Arch" $PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' + +function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } + +if (Test-Path -LiteralPath $PdfiumDll) { + $actualDll = Get-Sha256 $PdfiumDll + if ($actualDll -ne $PdfiumDllSha256[$Arch]) { + Write-Warning "cached PDFium DLL is not the pinned $PdfiumRelease build ($actualDll); re-downloading" + Remove-Item -LiteralPath $PdfiumDll -Force + } +} if (-not (Test-Path -LiteralPath $PdfiumDll)) { + $expectedArchive = $PdfiumArchiveSha256[$Arch] + if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" - Invoke-Native "download PDFium ($Arch)" { - Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/latest/download/pdfium-win-$Arch.tgz" -OutFile $tgz + Invoke-Native "download PDFium ($Arch, $PdfiumRelease)" { + Remove-Item -LiteralPath $tgz -Force -ErrorAction SilentlyContinue + Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/download/$PdfiumRelease/pdfium-win-$Arch.tgz" -OutFile $tgz + $actualArchive = Get-Sha256 $tgz + if ($actualArchive -ne $expectedArchive) { throw "PDFium $Arch archive checksum $actualArchive does not match the pinned $expectedArchive" } New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null - tar -xzf $tgz -C $PdfiumDir + # A DLL left in bin\ by an earlier run must not be mistaken for this archive's extraction. $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' + Remove-Item -LiteralPath $extracted -Force -ErrorAction SilentlyContinue + tar -xzf $tgz -C $PdfiumDir + if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } Move-Item -Force $extracted $PdfiumDll + Remove-Item -LiteralPath $tgz -Force } } $env:PDFIUM_DLL = $PdfiumDll From 95908e2b92476733f25efbb922e072fa5d91a582 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:16:32 +0100 Subject: [PATCH 068/113] Pin pdfium-render exactly to the verified wrapper Same reasoning as the wintab-sys pin in #11331: PDFium is FFI-loaded at run time, so a lockfile refresh must not move the wrapper under the pinned DLL release. Bump deliberately and re-check both the wrapper and the DLL release pin in packaging/windows/package.ps1. --- crates/io/Cargo.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index ef151b80cf..c8885d5e9b 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -52,7 +52,10 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } # PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. -pdfium-render = "0.9" +# Pinned exactly, like the WinTab wrappers in photocraft-tablet: PDFium is FFI-loaded at run time +# and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh +# must not move the wrapper under it. Bump deliberately and re-check both. +pdfium-render = "=0.9.5" image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] From 4f585f704b781f9241311eaaa6db4c4b96766ed7 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:48:30 +0100 Subject: [PATCH 069/113] PDF: rotate/offset-aware objects, cancellation, licences, CI PDFium - Map editable text and paths through the page's crop box and /Rotate, matching the rendered raster: box offsets, 90/180/270 rotation, rotated text transforms and rotation-aware colour sampling. - Check cancellation while traversing page objects and before returning the import; cap text colour samples at 4096. - The cached PDFium failure now says to restart the application after fixing the library path. - package.ps1 stages PDFium's LICENSE and bundled licence files flat for the MSI and the portable ZIP, tags the cache with the pinned release, and verifies freshly extracted DLLs. - ci.yml provisions the pinned PDFium for the Windows integration leg and requires it there; local runs still skip explicitly. --- .github/workflows/ci.yml | 18 +++ crates/io/src/pdf_import.rs | 193 ++++++++++++++++++++++++++----- crates/io/tests/it/pdf_import.rs | 52 +++++++-- packaging/windows/package.ps1 | 24 +++- packaging/windows/photocraft.wxs | 5 + 5 files changed, 251 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c3597f5ee..4422f41a22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -251,6 +251,24 @@ jobs: with: tool: cargo-nextest@0.9.150 + # The PDF import integration test loads PDFium at run time. Provision the pinned build for + # the integration leg and make an unavailable library fail there; local runs still skip. + - name: PDFium for the PDF import test + if: matrix.part == 'integration' + shell: pwsh + run: | + $dir = Join-Path $env:RUNNER_TEMP 'pdfium' + New-Item -ItemType Directory -Force $dir | Out-Null + $tgz = Join-Path $env:RUNNER_TEMP 'pdfium-win-x64.tgz' + Invoke-WebRequest -Uri 'https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/8138/pdfium-win-x64.tgz' -OutFile $tgz + $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $tgz).Hash.ToLowerInvariant() + if ($hash -ne '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5') { + throw "PDFium archive checksum $hash does not match the pinned chromium/8138 build" + } + tar -xzf $tgz -C $dir + "PDFIUM_DIR=$dir\bin" >> $env:GITHUB_ENV + "PHOTOCRAFT_REQUIRE_PDFIUM=1" >> $env:GITHUB_ENV + # The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every # integration-test target); the feature selection stays the same, so both legs share the # dependency cache. diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 679198ff8b..82233b2abc 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -60,19 +60,17 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } let page_count = last - first + 1; let count = page_count.min(MAX_PAGES); - // The page sizes in points first: the effective DPI must fit the budgets, and capping the - // raster must not change the page's physical size. - let mut sizes = Vec::with_capacity(count); + // The page geometry first: the effective DPI must fit the budgets, capping the raster must + // not change the page's physical size, and editable objects are mapped through the same page + // box and rotation the raster uses. + let mut geoms = Vec::with_capacity(count); for index in 0..count { ctl.check().map_err(|_| IoError::Cancelled)?; let page_index = first - 1 + index; let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let (w, h) = (f64::from(page.width().value), f64::from(page.height().value)); - if w <= 0.0 || h <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {} has no area", page_index + 1))); - } - sizes.push((w, h)); + geoms.push(page_geometry(&page, page_index + 1)?); } + let sizes: Vec<(f64, f64)> = geoms.iter().map(|g| (g.width_pt, g.height_pt)).collect(); let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); @@ -108,7 +106,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x = 0u32; - for (index, (w_pt, h_pt)) in sizes.iter().enumerate() { + for (index, geometry) in geoms.iter().enumerate() { + let (w_pt, h_pt) = (geometry.width_pt, geometry.height_pt); ctl.check().map_err(|_| IoError::Cancelled)?; let page_index = first - 1 + index; let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; @@ -155,7 +154,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { - children.extend(object_layers(&page, opts, &PageFrame { height_pt: *h_pt, dpi, x, rgba: &rgba, width, height })); + let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; + children.extend(object_layers(&page, opts, &frame, ctl)?); } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); @@ -171,9 +171,54 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } -/// One rendered page's frame: its point height, DPI, document x, and the RGBA pixels. -struct PageFrame<'a> { +/// A page's visible area and rotation, in PDF points. +#[derive(Clone, Copy)] +struct PageGeometry { + /// Displayed size (rotation applied): the size the raster is rendered into. + width_pt: f64, height_pt: f64, + /// The crop box origin in unrotated PDF user space. + origin_x: f64, + origin_y: f64, + /// The crop box size in unrotated PDF user space. + crop_w: f64, + crop_h: f64, + /// Clockwise rotation the renderer applies: 0, 90, 180 or 270. + rotation: u16, +} + +/// The page's visible box and rotation. PDF page objects stay in unrotated user space, while the +/// raster is rendered through the crop box and the page's `/Rotate`, so editable layers must use +/// the same transform. +#[cfg(not(target_arch = "wasm32"))] +fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> Result { + let width_pt = f64::from(page.width().value); + let height_pt = f64::from(page.height().value); + if width_pt <= 0.0 || height_pt <= 0.0 { + return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); + } + let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); + let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().crop().or_else(|_| page.boundaries().media()) { + Ok(boundary) => { + let r = boundary.bounds; + (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) + } + Err(_) => (0.0, 0.0, width_pt, height_pt), + }; + // A malformed box falls back to the displayed size; 90 and 270 swap the axes. + let (crop_w, crop_h) = if crop_w > 0.0 && crop_h > 0.0 { + (crop_w, crop_h) + } else if rotation == 90 || rotation == 270 { + (height_pt, width_pt) + } else { + (width_pt, height_pt) + }; + Ok(PageGeometry { width_pt, height_pt, origin_x, origin_y, crop_w, crop_h, rotation }) +} + +/// One rendered page's frame: its geometry, DPI, document x, and the RGBA pixels. +struct PageFrame<'a> { + geometry: PageGeometry, dpi: f64, x: u32, rgba: &'a [u8], @@ -182,12 +227,38 @@ struct PageFrame<'a> { } impl PageFrame<'_> { - /// Maps a point in PDF page space (points, origin bottom-left) to document pixels: the Y flip - /// and the page's X offset both belong to this mapping. + /// Maps a point in PDF page space to the page's own pixels: crop box, rotation and scale. + fn to_page_px(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { + let g = &self.geometry; + let u = f64::from(x_pt) - g.origin_x; + let v = f64::from(y_pt) - g.origin_y; + let (dx, dy) = match g.rotation { + 90 => (v, u), + 180 => (g.crop_w - u, v), + 270 => (g.crop_h - v, g.crop_w - u), + _ => (u, g.crop_h - v), + }; + let scale = self.dpi / 72.0; + (dx * scale, dy * scale) + } + + /// Maps a point in PDF page space to document pixels: the page's own pixels plus its X offset. fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let x_px = f64::from(x_pt) * self.dpi / 72.0 + f64::from(self.x); - let y_px = (self.height_pt - f64::from(y_pt)) * self.dpi / 72.0; - (x_px.round(), y_px.round()) + let (px, py) = self.to_page_px(x_pt, y_pt); + ((px + f64::from(self.x)).round(), py.round()) + } + + /// The text layer's transform at document pixel (`x`, `y`): the page rotation turns the text + /// layout too, so rotated pages get rotated editable text rather than upright text at a + /// rotated position. + fn text_transform(&self, x: f64, y: f64) -> Affine { + let (a, b, c, d) = match self.geometry.rotation { + 90 => (0.0, 1.0, -1.0, 0.0), + 180 => (-1.0, 0.0, 0.0, -1.0), + 270 => (0.0, -1.0, 1.0, 0.0), + _ => (1.0, 0.0, 0.0, 1.0), + }; + Affine { m: [a, b, c, d, x, y] } } /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. @@ -207,22 +278,33 @@ impl PageFrame<'_> { /// colour instead: for dark text on a light page that is a glyph core, and for light text on a /// dark page it is the glyph rather than the background. fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { - let x0 = (f64::from(left) * self.dpi / 72.0).floor().max(0.0) as u32; - let x1 = (f64::from(right) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.width)) as u32; - // PDF's Y grows up; the rendered page's Y grows down. - let y0 = ((self.height_pt - f64::from(top)) * self.dpi / 72.0).floor().max(0.0) as u32; - let y1 = ((self.height_pt - f64::from(bottom)) * self.dpi / 72.0).ceil().clamp(0.0, f64::from(self.height)) as u32; + // The box's four corners through the same rotation-aware mapping as the glyphs. + let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for (x, y) in [(left, bottom), (left, top), (right, top), (right, bottom)] { + let (px, py) = self.to_page_px(x, y); + x0 = x0.min(px); + x1 = x1.max(px); + y0 = y0.min(py); + y1 = y1.max(py); + } + let x0 = x0.floor().max(0.0) as u32; + let x1 = x1.ceil().clamp(0.0, f64::from(self.width)) as u32; + let y0 = y0.floor().max(0.0) as u32; + let y1 = y1.ceil().clamp(0.0, f64::from(self.height)) as u32; if x1 <= x0 || y1 <= y0 { return Color::BLACK; } - // At most ~4096 samples, so a page-sized text box stays cheap. + // At most 4096 samples, so a page-sized text box stays cheap. let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); let mut samples: Vec<[f32; 3]> = Vec::new(); let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); let mut y = y0; - while y < y1 { + 'rows: while y < y1 { let mut x = x0; while x < x1 { + if samples.len() >= 4096 { + break 'rows; + } let c = self.color_at(x, y); let rgb = [c.c[0], c.c[1], c.c[2]]; let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; @@ -253,12 +335,15 @@ impl PageFrame<'_> { /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame) -> Vec { +fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame, ctl: &Interrupt) -> Result, IoError> { use pdfium_render::prelude::*; let objects = page.objects(); let mut layers = Vec::new(); for object in objects.iter() { + if ctl.check().is_err() { + return Err(IoError::Cancelled); + } match object { PdfPageObject::Text(text) if opts.pdf_text => { let content = text.text(); @@ -280,7 +365,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f font_family: family, size_pt: size_pt as f32, color, - transform: Affine::translate(x_px, y_px), + transform: frame.text_transform(x_px, y_px), ..Default::default() }), ); @@ -359,7 +444,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f _ => {} } } - layers + Ok(layers) } /// The highest DPI not above `requested` that keeps every page and the artboard strip within @@ -403,7 +488,10 @@ fn bind() -> Result { drop(Pdfium::new(bindings)); Ok(()) } - Err(e) => Err(format!("PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR", library.display())), + Err(e) => Err(format!( + "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR, then restart the application", + library.display() + )), } }); match init { @@ -415,10 +503,14 @@ fn bind() -> Result { #[cfg(test)] mod tests { - use super::PageFrame; + use super::{PageFrame, PageGeometry}; + + fn geometry(rotation: u16) -> PageGeometry { + PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } + } fn frame(dpi: f64, x: u32) -> PageFrame<'static> { - PageFrame { height_pt: 842.0, dpi, x, rgba: &[], width: 595, height: 842 } + PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } } #[test] @@ -430,11 +522,41 @@ mod tests { assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); } + #[test] + fn crop_box_offsets_and_rotations_map_like_the_raster() { + // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. + let rotated = |rotation| PageFrame { + geometry: PageGeometry { width_pt: 100.0, height_pt: 200.0, origin_x: 10.0, origin_y: 20.0, crop_w: 200.0, crop_h: 100.0, rotation }, + dpi: 72.0, + x: 0, + rgba: &[], + width: 100, + height: 200, + }; + // At 72 dpi the rectangle (20, 30)..(60, 70) lands at (10, 10)..(50, 50). + assert_eq!(rotated(90).to_doc(20.0, 30.0), (10.0, 10.0)); + assert_eq!(rotated(90).to_doc(60.0, 70.0), (50.0, 50.0)); + // 180 mirrors X; 270 swaps the axes back. + assert_eq!(rotated(180).to_doc(20.0, 30.0), (190.0, 10.0)); + assert_eq!(rotated(270).to_doc(20.0, 30.0), (90.0, 190.0)); + // The page's document X offset is added after the page-space mapping. + let mut offset = rotated(90); + offset.x = 500; + assert_eq!(offset.to_doc(20.0, 30.0), (510.0, 10.0)); + } + #[test] fn samples_the_rendered_page() { // Two pixels: white then black. let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; - let page = PageFrame { height_pt: 842.0, dpi: 72.0, x: 0, rgba: &rgba, width: 2, height: 1 }; + let page = PageFrame { + geometry: PageGeometry { width_pt: 2.0, height_pt: 1.0, origin_x: 0.0, origin_y: 0.0, crop_w: 2.0, crop_h: 1.0, rotation: 0 }, + dpi: 72.0, + x: 0, + rgba: &rgba, + width: 2, + height: 1, + }; assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); @@ -446,7 +568,14 @@ mod tests { let mut rgba = vec![255u8; 8 * 4 * 4]; let glyph = (8 + 2) * 4; rgba[glyph..glyph + 3].fill(0); - let page = PageFrame { height_pt: 4.0, dpi: 72.0, x: 0, rgba: &rgba, width: 8, height: 4 }; + let page = PageFrame { + geometry: PageGeometry { width_pt: 8.0, height_pt: 4.0, origin_x: 0.0, origin_y: 0.0, crop_w: 8.0, crop_h: 4.0, rotation: 0 }, + dpi: 72.0, + x: 0, + rgba: &rgba, + width: 8, + height: 4, + }; // The whole page box contains the glyph: the ink wins over the white background. assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); // A box that contains only background keeps the background colour. diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 0e1c36eba2..9bee105b0c 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -16,24 +16,30 @@ const GAP: f64 = 80.0; #[test] fn imports_text_and_a_transformed_path_on_two_pages() { - let pdf = two_page_pdf(); + let pdf = three_page_pdf(); for dpi in [72.0f32, 300.0] { let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { Ok(result) => result, Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); + // The Windows integration leg provisions PDFium and sets this: there a missing + // library must fail rather than let the runner report an unreached pass. + assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for this test but could not load: {message}"); return; } Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), }; check(&result.document, dpi); + eprintln!("PDF import executed at {dpi} dpi: {} page groups, layer checks passed", result.document.layers.len()); } } /// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by -/// (10, 5) — corners (30, 25)..(70, 45) — plus green 48 pt text at (20, 20). -fn two_page_pdf() -> Vec { +/// (10, 5) - corners (30, 25)..(70, 45) - plus green 48 pt text at (20, 20). Page 3: a crop box +/// offset to (10, 20, 210, 120) and rotated 90 degrees clockwise, with a 40 x 40 pt rectangle at +/// (20, 30)..(60, 70) that renders at (10, 10)..(50, 50) on a 100 x 200 page. +fn three_page_pdf() -> Vec { let mut pdf = PdfDocument::with_version("1.5"); let pages_id = pdf.new_object_id(); let font_id = pdf.add_object(dictionary! { @@ -44,17 +50,25 @@ fn two_page_pdf() -> Vec { let resources = pdf.add_object(dictionary! { "Font" => dictionary! { "F1" => font_id }, }); - let contents = ["1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", "0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET"]; + let pages = [ + ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None), + ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None), + ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64)), + ]; let mut kids = Vec::new(); - for content in contents { + for (content, [left, bottom, right, top], rotate) in pages { let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); - let page_id = pdf.add_object(dictionary! { + let mut page = dictionary! { "Type" => "Page", "Parent" => pages_id, - "MediaBox" => Object::Array(vec![0.into(), 0.into(), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "MediaBox" => Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]), "Contents" => content_id, "Resources" => resources, - }); + }; + if let Some(rotate) = rotate { + page.set("Rotate", rotate); + } + let page_id = pdf.add_object(page); kids.push(Object::Reference(page_id)); } let count = kids.len() as i64; @@ -103,6 +117,28 @@ fn check(document: &Document, dpi: f32) { let text = text_layer(page_children(document, 2)); assert_green(&text.color, "page 2 text"); assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); + + // Page 3: the crop box (10, 20, 210, 120) and /Rotate 90 put the rectangle at (10..50, 10..50). + let shape = shape_layer(page_children(document, 3)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + let page_three_x = 2.0 * (PAGE_W * scale).round() + 2.0 * GAP; + assert!((min_x - (page_three_x + 10.0 * scale)).abs() < 3.0, "rotated path min x is {min_x}, page 3 starts at {page_three_x} ({dpi} dpi)"); + assert!((max_x - (page_three_x + 50.0 * scale)).abs() < 3.0, "rotated path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - 10.0 * scale).abs() < 3.0, "rotated path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - 50.0 * scale).abs() < 3.0, "rotated path max y is {max_y} ({dpi} dpi)"); + + // Rotated text: the layer's transform carries the 90 degree turn, not just its position. + let text = text_layer(page_children(document, 3)); + let m = text.transform.m; + assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); + assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); + assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); } fn page_children(document: &Document, page: usize) -> &[Layer] { diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 6efb64e770..8b4e8d0fea 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -74,9 +74,17 @@ $PdfiumDllSha256 = @{ } $PdfiumDir = Join-Path $Root "target\pdfium\$Arch" $PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' +$PdfiumLicense = Join-Path $PdfiumDir 'LICENSE' +$PdfiumLicenses = Join-Path $PdfiumDir 'licenses' +$PdfiumTag = Join-Path $PdfiumDir 'release.txt' function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } +# A cache from another pinned release (or missing its licence set) is discarded whole. +$cachedRelease = if (Test-Path -LiteralPath $PdfiumTag) { (Get-Content -Raw -LiteralPath $PdfiumTag).Trim() } else { '' } +if ($cachedRelease -ne $PdfiumRelease) { + Remove-Item -LiteralPath $PdfiumDir -Recurse -Force -ErrorAction SilentlyContinue +} if (Test-Path -LiteralPath $PdfiumDll) { $actualDll = Get-Sha256 $PdfiumDll if ($actualDll -ne $PdfiumDllSha256[$Arch]) { @@ -84,7 +92,7 @@ if (Test-Path -LiteralPath $PdfiumDll) { Remove-Item -LiteralPath $PdfiumDll -Force } } -if (-not (Test-Path -LiteralPath $PdfiumDll)) { +if (-not ((Test-Path -LiteralPath $PdfiumDll) -and (Test-Path -LiteralPath $PdfiumLicense) -and (Test-Path -LiteralPath $PdfiumLicenses))) { $expectedArchive = $PdfiumArchiveSha256[$Arch] if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" @@ -101,11 +109,23 @@ if (-not (Test-Path -LiteralPath $PdfiumDll)) { if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } Move-Item -Force $extracted $PdfiumDll + Set-Content -LiteralPath $PdfiumTag -Value $PdfiumRelease -NoNewline + if ((Get-Sha256 $PdfiumDll) -ne $PdfiumDllSha256[$Arch]) { throw "extracted PDFium $Arch DLL checksum does not match the pinned build" } Remove-Item -LiteralPath $tgz -Force } } $env:PDFIUM_DLL = $PdfiumDll +# PDFium's BSD licence and the licences of the libraries bundled into its DLL ship beside it. They +# are staged flat with a `pdfium-` prefix, so both the MSI's INSTALLFOLDER and the portable root +# carry them whether the DLL came from this download or the cache. +function Stage-PdfiumLicences([string] $Dest) { + Copy-Item -LiteralPath $PdfiumLicense -Destination (Join-Path $Dest 'pdfium-LICENSE.txt') -Force + Get-ChildItem -LiteralPath $PdfiumLicenses -File | ForEach-Object { + Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $Dest ("pdfium-license-" + $_.Name)) -Force + } +} + Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -141,6 +161,7 @@ Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage Copy-Item -LiteralPath $PdfiumDll -Destination $Stage +Stage-PdfiumLicences $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -224,6 +245,7 @@ Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable Copy-Item -LiteralPath $PdfiumDll -Destination $Portable +Stage-PdfiumLicences $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index 020f7aa89c..f727880a5a 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -33,6 +33,7 @@ + + + + From 20142544b02e3a4488e3fff18b3729cc9e2116e5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 23:03:17 +0100 Subject: [PATCH 070/113] Regenerate docs/scorecard.md after merging main Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index a3158616b2..dee4b48c6d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 36 | 9 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 192 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | +| [Automation](#automation) | 5 | 4 | 2 | 661 of 661 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -268,7 +268,7 @@ Menu wiring (`docs/parity-checklist.md`): 661 of 661 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds/batch_run.rs and batch_naming.rs: flat subfolder output and last-result-wins names measured in Photoshop 2026; live open-document source; file naming components and serials; UTF-16 LE error log; stop-on-error; CLI and Batch dialog, #4579. Desktop Esc asks Continue/Stop, retaining one plan and error log; a read-only canvas preview shows each scratch-session input without a progress bar. Inputs are not live tabs with Layers panel content, so full window parity remains open. | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | From ed0b2a726b617f8f17d57e34ecbd62d6c9f63034 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 23:10:58 +0100 Subject: [PATCH 071/113] Address CodeRabbit review: draw pattern scales below 0.1 % (#9256) A preview at a reduced work scale (4 %) takes a stored 2 % pattern to 0.08 %, which Placement::anchored and the GPU planner's placement treated as invalid and drew at 100 %. Any positive finite scale now draws, floored at 1e-6 to keep tile coordinates finite. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/pattern.rs | 32 +++++++++++++++++++++++++++++++- crates/gpu/src/plan/lower.rs | 2 +- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index b351bdef06..30c64c7bdf 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -344,6 +344,9 @@ impl Tile { /// Most taps per axis of the minification filter (the WGSL mirror uses the same cap). const MAX_TAPS: usize = 8; +/// The smallest pattern scale a placement draws at (a fraction): keeps tile coordinates finite. +pub const MIN_PLACEMENT_SCALE: f64 = 1e-6; + /// Taps per axis for a placement whose inverse scale is `inv_scale`: one pixel covers /// `inv_scale` tile pixels, so that many taps (capped) box-filter it. 1 at 100 % and above. fn pixel_taps(inv_scale: f64) -> usize { @@ -387,7 +390,9 @@ impl Placement { let base = if link { anchor } else { (0.0, 0.0) }; let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); let s = f64::from(scale); - let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; + // Any positive scale draws: a preview at a reduced work scale takes a stored 2 % pattern + // well below 0.1 %. Only 0, negatives and non-finite values fall back to 100 %. + let inv_scale = if s.is_finite() && s > 0.0 { 1.0 / s.max(MIN_PLACEMENT_SCALE) } else { 1.0 }; let a = f64::from(angle).to_radians(); Placement { origin, cs: (a.cos(), a.sin()), inv_scale } } @@ -608,6 +613,31 @@ mod tests { assert_eq!((row[0][0], row[1][0]), (0.0, 1.0)); } + /// Review of #9256: a preview at 4 % work scale draws a stored 2 % pattern at 0.08 %, which + /// used to fall back to 100 % and show the stripes full size. + #[test] + fn placement_keeps_scales_below_a_tenth_of_a_percent() { + let place = Placement::new(Rect::EMPTY, false, (0.0, 0.0), 0.0008, 0.0); + let (u, v) = place.map(1.0, 2.0); + assert!((u - 1250.0).abs() < 1e-3 && (v - 2500.0).abs() < 1e-3, "{u},{v}"); + // 1-px dark / light stripes: at 100 % the pixels alternate 0 / 1; at 0.08 % each pixel + // covers 1250 of them, so every pixel is their mean. + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 1.0, 1.0, 1.0]); + for x in (0..8).step_by(2) { + s.fill_rect(Rect::new(x, 0, x + 1, 8), &[0.0, 0.0, 0.0, 1.0]); + } + let t = Tile::new(&Pattern::new("stripes", s, 8, 8)).unwrap(); + for p in render(&t, &place, Rect::new(0, 0, 8, 1)) { + assert!((p[0] - 0.5).abs() < 0.1, "{p:?}"); + } + // 0, negative and non-finite scales still draw at 100 %. + for bad in [0.0, -0.5, f32::NAN, f32::INFINITY] { + let p = Placement::new(Rect::EMPTY, false, (0.0, 0.0), bad, 0.0); + assert_eq!(p.map(3.0, 0.0).0, 3.0, "{bad}"); + } + } + #[test] fn sampling_at_hostile_phases_does_not_overflow() { let patterns = [checker()]; diff --git a/crates/gpu/src/plan/lower.rs b/crates/gpu/src/plan/lower.rs index 202f0216e1..4bda862af1 100644 --- a/crates/gpu/src/plan/lower.rs +++ b/crates/gpu/src/plan/lower.rs @@ -24,7 +24,7 @@ pub(super) fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale let base = if link { anchor } else { (0.0, 0.0) }; let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); let s = f64::from(scale); - let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; + let inv_scale = if s.is_finite() && s > 0.0 { 1.0 / s.max(photocraft_compose::pattern::MIN_PLACEMENT_SCALE) } else { 1.0 }; let a = f64::from(angle).to_radians(); Placement { origin, cs: (a.cos(), a.sin()), inv_scale } } From 00a1b1cd3ebedfc090d5bc361b406adf5160c9a1 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:12:14 +0100 Subject: [PATCH 072/113] PDF: use PDFium's page bounding box; bound editable objects - Map editable objects through the page's effective bounding box (media box clipped to the crop box) rather than the raw CropBox: an oversized CropBox no longer offsets text or paths from the rendered page. Covered by a fourth fixture page with CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox. - Add a document-wide editable-object budget (20,000 layers, 1,000,000 path knots). A page that exceeds it keeps its raster, warns that its editable objects were omitted, and the unit test covers the accounting. --- crates/io/src/pdf_import.rs | 98 +++++++++++++++++++++++++++++--- crates/io/tests/it/pdf_import.rs | 30 ++++++++-- 2 files changed, 117 insertions(+), 11 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 82233b2abc..10d88beaf8 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -103,6 +103,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - budget >> 20 ))); } + let mut object_budget = ObjectBudget::default(); + let mut object_warnings: Vec = Vec::new(); let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x = 0u32; @@ -155,14 +157,18 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut children = vec![layer]; if opts.pdf_text || opts.pdf_vectors { let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; - children.extend(object_layers(&page, opts, &frame, ctl)?); + let (layers, truncated) = object_layers(&page, opts, &frame, ctl, &mut object_budget)?; + children.extend(layers); + if truncated { + object_warnings.push(format!("PDF page {}: editable text/vector layers omitted at the import limit (the raster page is kept)", page_index + 1)); + } } let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); x += width + GAP; ctl.progress((index + 1) as f32 / count as f32); } - let mut warnings = Vec::new(); + let mut warnings = object_warnings; if first > 1 || last < total || count < page_count { let shown_last = first + count - 1; let reason = if count < page_count { " (the page limit is 16)" } else { "" }; @@ -171,6 +177,39 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// Document-wide bound on editable objects. Text layers and path knots are allocated outside the +/// pixel-memory estimate, so a pathological PDF could otherwise exhaust memory. +const MAX_OBJECT_LAYERS: usize = 20_000; +const MAX_PATH_KNOTS: usize = 1_000_000; + +/// Tracks the editable objects created so far, document-wide. +#[derive(Default)] +struct ObjectBudget { + layers: usize, + knots: usize, +} + +impl ObjectBudget { + /// Claims one editable layer; false once the document-wide limit is reached. + fn claim_layer(&mut self) -> bool { + if self.layers >= MAX_OBJECT_LAYERS { + false + } else { + self.layers += 1; + true + } + } + + /// Claims `count` path knots; false if that would pass the document-wide limit. + fn claim_knots(&mut self, count: usize) -> bool { + if self.knots.saturating_add(count) > MAX_PATH_KNOTS { + false + } else { + self.knots += count; + true + } + } +} /// A page's visible area and rotation, in PDF points. #[derive(Clone, Copy)] struct PageGeometry { @@ -198,7 +237,9 @@ fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); } let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); - let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().crop().or_else(|_| page.boundaries().media()) { + // The page's effective box, as PDFium renders it: the bounding box (media box clipped to the + // crop box), not the raw crop box, which may extend past the media box. + let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().bounding().or_else(|_| page.boundaries().crop()).or_else(|_| page.boundaries().media()) { Ok(boundary) => { let r = boundary.bounds; (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) @@ -335,12 +376,23 @@ impl PageFrame<'_> { /// Editable text and shape layers for one rendered page, in document pixels. #[cfg(not(target_arch = "wasm32"))] -fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, frame: &PageFrame, ctl: &Interrupt) -> Result, IoError> { +fn object_layers( + page: &pdfium_render::prelude::PdfPage, + opts: &ImportOptions, + frame: &PageFrame, + ctl: &Interrupt, + budget: &mut ObjectBudget, +) -> Result<(Vec, bool), IoError> { use pdfium_render::prelude::*; let objects = page.objects(); let mut layers = Vec::new(); - for object in objects.iter() { + let mut truncated = false; + 'objects: for object in objects.iter() { + if budget.layers >= MAX_OBJECT_LAYERS { + truncated = true; + break; + } if ctl.check().is_err() { return Err(IoError::Cancelled); } @@ -372,6 +424,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if !text.is_visible() { layer.visible = false; } + if !budget.claim_layer() { + truncated = true; + break 'objects; + } layers.push(layer); } PdfPageObject::Path(path) if opts.pdf_vectors => { @@ -396,10 +452,18 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); closed = false; } + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } let (px, py) = point(); knots.push(Knot::corner(px, py)); } PdfPathSegmentType::LineTo => { + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } let (px, py) = point(); knots.push(Knot::corner(px, py)); } @@ -412,6 +476,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f if let Some(prev) = knots.last_mut() { prev.out_ctrl = Point::new(c1x, c1y); } + if !budget.claim_knots(1) { + truncated = true; + break 'objects; + } knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); bezier.clear(); } @@ -431,6 +499,10 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f continue; } let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); + if !budget.claim_layer() { + truncated = true; + break 'objects; + } layers.push(Layer::new( "Path", LayerContent::Shape(ShapeLayer { @@ -444,7 +516,7 @@ fn object_layers(page: &pdfium_render::prelude::PdfPage, opts: &ImportOptions, f _ => {} } } - Ok(layers) + Ok((layers, truncated)) } /// The highest DPI not above `requested` that keeps every page and the artboard strip within @@ -503,7 +575,7 @@ fn bind() -> Result { #[cfg(test)] mod tests { - use super::{PageFrame, PageGeometry}; + use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; fn geometry(rotation: u16) -> PageGeometry { PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } @@ -522,6 +594,18 @@ mod tests { assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); } + #[test] + fn object_budget_stops_at_its_limits() { + let mut budget = ObjectBudget::default(); + for _ in 0..MAX_OBJECT_LAYERS { + assert!(budget.claim_layer()); + } + assert!(!budget.claim_layer()); + let mut knots = ObjectBudget::default(); + assert!(knots.claim_knots(MAX_PATH_KNOTS)); + assert!(!knots.claim_knots(1)); + assert!(!knots.claim_knots(usize::MAX)); + } #[test] fn crop_box_offsets_and_rotations_map_like_the_raster() { // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 9bee105b0c..f659eb5166 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -51,12 +51,15 @@ fn three_page_pdf() -> Vec { "Font" => dictionary! { "F1" => font_id }, }); let pages = [ - ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None), - ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None), - ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64)), + ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), + ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), + ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64), None), + // A CropBox larger than the MediaBox: the rendered page and the mapping use the + // intersection, so the rectangle must not be offset by the crop box's negative origin. + ("0 0.5 0 rg 20 30 40 40 re f", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, Some([-50.0f32, -50.0, 250.0, 150.0])), ]; let mut kids = Vec::new(); - for (content, [left, bottom, right, top], rotate) in pages { + for (content, [left, bottom, right, top], rotate, crop) in pages { let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); let mut page = dictionary! { "Type" => "Page", @@ -68,6 +71,9 @@ fn three_page_pdf() -> Vec { if let Some(rotate) = rotate { page.set("Rotate", rotate); } + if let Some([left, bottom, right, top]) = crop { + page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); + } let page_id = pdf.add_object(page); kids.push(Object::Reference(page_id)); } @@ -139,6 +145,22 @@ fn check(document: &Document, dpi: f32) { assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); + + // Page 4: a CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox must not offset the rect. + let shape = shape_layer(page_children(document, 4)); + let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + min_x = min_x.min(knot.anchor.x); + max_x = max_x.max(knot.anchor.x); + min_y = min_y.min(knot.anchor.y); + max_y = max_y.max(knot.anchor.y); + } + // Page 3 is rotated 90 degrees, so it is 100 pt wide on the strip, not 200. + let page_four_x = 2.0 * (PAGE_W * scale).round() + (100.0 * scale).round() + 3.0 * GAP; + assert!((min_x - (page_four_x + 20.0 * scale)).abs() < 3.0, "oversized-crop path min x is {min_x}, page 4 starts at {page_four_x} ({dpi} dpi)"); + assert!((max_x - (page_four_x + 60.0 * scale)).abs() < 3.0, "oversized-crop path max x is {max_x} ({dpi} dpi)"); + assert!((min_y - 30.0 * scale).abs() < 3.0, "oversized-crop path min y is {min_y} ({dpi} dpi)"); + assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); } fn page_children(document: &Document, page: usize) -> &[Layer] { From eda8759d118bf6cf2cb6be965cec5f0fa05ad085 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:35:28 +0100 Subject: [PATCH 073/113] PDF: document the import test helpers Raise docstring coverage on the functions this PR adds: the fixture/assertion helpers in the end-to-end test and the importer's test frame builders now have doc comments. No behaviour change. --- crates/io/src/pdf_import.rs | 2 ++ crates/io/tests/it/pdf_import.rs | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 10d88beaf8..5a4908c108 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -577,10 +577,12 @@ fn bind() -> Result { mod tests { use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; + /// A 595 x 842 pt page with no offset, rotated by `rotation` degrees. fn geometry(rotation: u16) -> PageGeometry { PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } } + /// A full-page frame at `dpi`, starting at document x `x`. fn frame(dpi: f64, x: u32) -> PageFrame<'static> { PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } } diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index f659eb5166..d84fb03230 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -14,6 +14,7 @@ const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; const GAP: f64 = 80.0; +/// Imports the four-page fixture at 72 and 300 DPI and checks every layer it produces. #[test] fn imports_text_and_a_transformed_path_on_two_pages() { let pdf = three_page_pdf(); @@ -93,6 +94,7 @@ fn three_page_pdf() -> Vec { bytes } +/// Asserts the imported text and path layers at one DPI against the fixture geometry. fn check(document: &Document, dpi: f32) { let scale = f64::from(dpi) / 72.0; let page_two_x = (PAGE_W * scale).round() + GAP; @@ -163,6 +165,7 @@ fn check(document: &Document, dpi: f32) { assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); } +/// The layer children of the imported `Page N` group. fn page_children(document: &Document, page: usize) -> &[Layer] { let name = format!("Page {page}"); let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); @@ -172,6 +175,7 @@ fn page_children(document: &Document, page: usize) -> &[Layer] { } } +/// The first text layer among `children`. fn text_layer(children: &[Layer]) -> &TextLayer { children .iter() @@ -182,6 +186,7 @@ fn text_layer(children: &[Layer]) -> &TextLayer { .expect("a text layer") } +/// The first shape layer among `children`. fn shape_layer(children: &[Layer]) -> &ShapeLayer { children .iter() @@ -192,10 +197,12 @@ fn shape_layer(children: &[Layer]) -> &ShapeLayer { .expect("a shape layer") } +/// Asserts `color` is the fixture's red ink. fn assert_red(color: &Color, what: &str) { assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); } +/// Asserts `color` is the fixture's green ink. fn assert_green(color: &Color, what: &str) { assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); } From 2f95eac75b2f6bb1201c5570be512ba45bb4a83d Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:41:53 +0100 Subject: [PATCH 074/113] PDF: document the importer's known limits Module docs now state that pdfium-render 0.9.5 exposes path fill/stroke presence but not paint, width or dash (black paints, 1 pt stroke); that text colour is sampled and fonts are matched by family/name; and that only package.ps1 provisions PDFium, not the shared release workflow. The text and path extraction comments say the same where the code relies on it. --- crates/io/src/pdf_import.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 5a4908c108..cdb56c9d62 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -6,6 +6,15 @@ //! //! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / //! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. +//! +//! # Known limits +//! +//! - pdfium-render 0.9.5 exposes a path's fill/stroke *presence* but not its paint colour, stroke +//! width or dash pattern, so imported paths are painted black (1 pt centre stroke when stroked). +//! - A text object exposes no fill colour: the colour is sampled from the rendered page's glyph +//! ink, and the font is matched by family/name rather than embedded or loaded from the PDF. +//! - PDFium is provisioned by `packaging/windows/package.ps1` (pinned release, verified DLL); the +//! shared craft-common-actions release workflow does not stage it. use crate::{ImportOptions, ImportResult, IoError}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; @@ -404,8 +413,10 @@ fn object_layers( } let Ok(bounds) = text.bounds() else { continue }; let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. The - // text object does not expose its fill colour; sample the glyph ink from the page. + // The text layer's size is in points; the transform is in document pixels. + // The text object does not expose its fill colour; sample the glyph ink from the + // page. The font is matched by family/name, not embedded: a document font that is + // not installed renders with the closest family the text engine has. let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); let size_pt = f64::from(text.scaled_font_size().value).max(1.0); let font = text.font(); @@ -434,7 +445,8 @@ fn object_layers( // PDFium reports the segments in object space; the object's matrix places them on // the page. Without it, scaled or rotated paths land in the wrong place. let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); - // The fill and stroke modes are exposed; the colours and dash pattern are not. + // The fill and stroke modes are exposed; the colours, stroke width and dash + // pattern are not, so both paints are black and a stroke is 1 pt wide. let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); let stroked = path.is_stroked().unwrap_or(false); if !filled && !stroked { From 7e1de84bceae3903b92d11b1b3d4e97235b8a54e Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:44:59 +0100 Subject: [PATCH 075/113] PDF: document the added test functions Every function this PR adds now has a doc comment, including the test functions in the importer, PDF export and layers_to_files suites. No behaviour change. --- crates/engine/src/cmd/file_cmds/tests.rs | 1 + crates/io/src/pdf/tests.rs | 1 + crates/io/src/pdf_import.rs | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 6a14a7542b..afb74faa5b 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2539,6 +2539,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } #[test] +/// `groups: "layers"` walks into a group and writes each visible leaf as its own file. fn layers_to_files_exports_group_children_as_loose_files() { let dir = tmp("layers-groups"); let mut s = session(8, 8, 8); diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 30c38a2698..6741fea346 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -395,6 +395,7 @@ fn leading_newline_stays_in_the_first_selection_span() { } #[test] +/// Each artboard becomes one labelled page, in document order. fn artboards_export_as_one_page_each() { use photocraft_doc::{Artboard, Group}; let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index cdb56c9d62..7cb1da50c2 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -600,6 +600,7 @@ mod tests { } #[test] + /// Page points map through the DPI scale, the Y flip and the page's document X offset. fn page_points_map_to_document_pixels() { assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); // The same point at four times the resolution. @@ -609,6 +610,7 @@ mod tests { } #[test] + /// The document-wide budget refuses layers and knots once its limits are reached. fn object_budget_stops_at_its_limits() { let mut budget = ObjectBudget::default(); for _ in 0..MAX_OBJECT_LAYERS { @@ -621,6 +623,7 @@ mod tests { assert!(!knots.claim_knots(usize::MAX)); } #[test] + /// Crop-box offsets and 90/180/270 rotations land where the raster renders them. fn crop_box_offsets_and_rotations_map_like_the_raster() { // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. let rotated = |rotation| PageFrame { @@ -644,6 +647,7 @@ mod tests { } #[test] + /// The page sampler reads the requested pixel and reports black outside the page. fn samples_the_rendered_page() { // Two pixels: white then black. let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; @@ -661,6 +665,7 @@ mod tests { } #[test] + /// Glyph ink wins over the background inside a text box, while an empty box keeps background. fn text_colour_samples_the_glyph_ink() { // An 8 x 4 white page with one black glyph pixel at (2, 1). let mut rgba = vec![255u8; 8 * 4 * 4]; From b57603708e737c92ff7212cd48b4b722f3242f27 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:47:23 +0100 Subject: [PATCH 076/113] PDF: drop the unused image dependency from photocraft-io The PDF export codec goes through photocraft-codecs; nothing in the crate used the image crate, so the dependency and its lockfile edge are removed. pdfium-render stays pinned exactly. --- Cargo.lock | 1 - crates/io/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3221556bc..1a3f307c2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5464,7 +5464,6 @@ dependencies = [ "craft-docpath", "crc32fast", "flate2", - "image", "imagesize", "lopdf", "miniz_oxide 0.9.1", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index c8885d5e9b..dd5a232f32 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -56,7 +56,6 @@ ttf-parser = { version = "0.25", default-features = false } # and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh # must not move the wrapper under it. Bump deliberately and re-check both. pdfium-render = "=0.9.5" -image = { workspace = true, features = ["png"] } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } From f7dfe7a017f92453500a35339aabe108b6d0e2cf Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 02:34:55 +0100 Subject: [PATCH 077/113] PDF: test last-object cancellation and raster fidelity - A complete import makes a fixed number of cancellation checks; cancelling on the last per-object check and on the public boundary check must both return Cancelled and never a document. - Six page variants (plain, CropBox offset, rotations 90/180/270, oversized CropBox) compare each stored page raster with a direct PDFium render at 72, 150 and 300 DPI: 18/18 byte-identical, and the sizes prove the crop intersection (190x80) and oversized CropBox (200x100) cases. - Both tests skip without PDFium and fail under PHOTOCRAFT_REQUIRE_PDFIUM, like the existing end-to-end test. --- crates/io/tests/it/pdf_import.rs | 155 ++++++++++++++++++++++++++++++- 1 file changed, 154 insertions(+), 1 deletion(-) diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index d84fb03230..ef02111309 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -6,9 +6,15 @@ //! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and //! returns instead of pretending the end-to-end wiring passed. +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; +use pdfium_render::prelude::{PdfRenderConfig, Pdfium}; use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; -use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; +use photocraft_geom::Rect; +use photocraft_io::{ImportOptions, ImportResult, IoError, import_with_options_and_interrupt}; +use photocraft_raster::Interrupt; const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; @@ -206,3 +212,150 @@ fn assert_red(color: &Color, what: &str) { fn assert_green(color: &Color, what: &str) { assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); } + +/// Imports `bytes`, or prints SKIPPED and returns `None` when PDFium cannot load. The Windows +/// integration leg sets `PHOTOCRAFT_REQUIRE_PDFIUM`, where a missing library must fail. +fn imported_or_skipped(bytes: &[u8], options: &ImportOptions, ctl: &Interrupt<'_>, what: &str) -> Option { + match import_with_options_and_interrupt("probe.pdf", bytes, options, ctl) { + Ok(result) => Some(result), + Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { + eprintln!("SKIPPED {what}: PDFium is unavailable ({message})"); + assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for {what} but could not load: {message}"); + None + } + Err(error) => panic!("{what} failed: {error}"), + } +} + +/// Six one-page variants for the cancellation and fidelity probes: plain, a CropBox offset to +/// (10, 20, 210, 120), rotations of 90, 180 and 270 degrees, and an oversized CropBox +/// (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page draws a 40 x 40 blue rectangle +/// and a 10 x 10 red one at (20, 30). +fn variant_pdf() -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let pages: [(Option, Option<[f32; 4]>); 6] = [ + (None, None), + (None, Some([10.0, 20.0, 210.0, 120.0])), + (Some(90), None), + (Some(180), None), + (Some(270), None), + (None, Some([-50.0, -50.0, 250.0, 150.0])), + ]; + let mut kids = Vec::new(); + for (rotate, crop) in pages { + let content = b"0 0 1 rg 20 30 40 40 re f 1 0 0 rg 20 30 10 10 re f"; + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); + let mut page = dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(PAGE_W as f32), Object::Real(PAGE_H as f32)]), + "Contents" => content_id, + "Resources" => dictionary! {}, + }; + if let Some(rotate) = rotate { + page.set("Rotate", rotate); + } + if let Some([left, bottom, right, top]) = crop { + page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); + } + kids.push(Object::Reference(pdf.add_object(page))); + } + let count = kids.len() as i64; + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(kids), + "Count" => count, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the variant PDF"); + bytes +} + +/// A cancel that lands on the last object's check, or on the public boundary after +/// `import_stages`, must be reported as `Cancelled` rather than returning a document. +#[test] +fn cancelling_on_the_last_checks_is_reported() { + let pdf = variant_pdf(); + let options = ImportOptions { pdf_dpi: 72.0, ..Default::default() }; + let count = AtomicUsize::new(0); + let cancel = || { + count.fetch_add(1, Ordering::SeqCst); + false + }; + let ctl = Interrupt::cancel_only(&cancel); + if imported_or_skipped(&pdf, &options, &ctl, "the last-check cancellation test").is_none() { + return; + } + let total = count.load(Ordering::SeqCst); + assert!(total >= 3, "a complete import should check cancellation at least three times, got {total}"); + for (label, threshold) in [("the last per-object check", total - 1), ("the public boundary check", total)] { + let seen = AtomicUsize::new(0); + let cancel = || seen.fetch_add(1, Ordering::SeqCst) + 1 >= threshold; + let ctl = Interrupt::cancel_only(&cancel); + let started = Instant::now(); + let result = import_with_options_and_interrupt("probe.pdf", &pdf, &options, &ctl); + let elapsed = started.elapsed(); + assert_eq!(seen.load(Ordering::SeqCst), threshold, "cancelling on {label} should stop at check {threshold} of {total}"); + match result { + Err(IoError::Cancelled) => {} + Ok(_) => panic!("cancelling on {label} returned a document"), + Err(error) => panic!("cancelling on {label} returned {error:?}"), + } + assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}"); + } +} + +/// Every imported page's stored raster must equal a direct PDFium render of the same page at the +/// same target width: crop intersection, rotation and the strip placement may not move or resample +/// a pixel. At 72, 150 and 300 DPI over the six variants that is 18 page renders. +#[test] +fn raster_matches_a_direct_pdfium_render() { + let pdf = variant_pdf(); + let mut compared = 0; + for dpi in [72.0f32, 150.0, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let Some(result) = imported_or_skipped(&pdf, &options, &Interrupt::NONE, "the raster fidelity matrix") else { + return; + }; + let pdfium = Pdfium::default(); + let reference = pdfium.load_pdf_from_byte_slice(&pdf, None).expect("reference PDF"); + assert_eq!(reference.pages().len() as usize, result.document.layers.len(), "page count at {dpi} dpi"); + for (index, layer) in result.document.layers.iter().enumerate() { + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("page layer {} is not a group", layer.name), + }; + let artboard = group.artboard.as_ref().expect("page artboard").rect; + let raster = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); + let (width, height) = (artboard.width(), artboard.height()); + let mut got = vec![[0u8; 4]; (width as usize) * (height as usize)]; + raster.read_rgba8_into(Rect::from_xywh(artboard.x0, artboard.y0, width, height), &mut got); + + let page = reference.pages().get(index as i32).expect("reference page"); + let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(width as i32)).expect("reference render"); + assert_eq!((bitmap.width() as u32, bitmap.height() as u32), (width, height), "page {} size at {dpi} dpi", index + 1); + let want = bitmap.as_rgba_bytes(); + + let mut max_diff = 0u32; + let mut sum = 0u64; + for (pixel, reference) in got.iter().zip(want.as_chunks::<4>().0.iter()) { + for channel in 0..4 { + let diff = (pixel[channel] as i32 - reference[channel] as i32).unsigned_abs(); + sum += u64::from(diff); + max_diff = max_diff.max(diff); + } + } + let channels = u64::from(width) * u64::from(height) * 4; + let mean = sum as f64 / channels as f64; + assert!(max_diff <= 1, "page {} at {dpi} dpi differs from the direct render: max channel diff {max_diff}, mean {mean:.4}", index + 1); + compared += 1; + } + } + assert_eq!(compared, 18, "six pages at three DPIs should all be compared"); +} From 2cb4a88dd6e54217e95780d445c79883d382c485 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 02:39:16 +0100 Subject: [PATCH 078/113] Brush: opacity minimum 1 % and "00" sets 100 % (#11812) The Brush, Pencil and Eraser Opacity fields take whole numbers from 1 to 100, as in the reference application (0 and -10 become 1, 150 becomes 100, 33.7 a whole number). The digit keys "00" set the Brush to 100 % instead of 0 %, and tools.setBrush floors opacity at 0.01, so a brush can no longer be set to paint nothing. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 4 +- .../src/brush_opacity_minimum_tests.rs | 119 ++++++++++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 18 +-- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/options_bar.rs | 16 ++- 5 files changed, 146 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/brush_opacity_minimum_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index e09ff2098c..9f371bcd17 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1105,6 +1105,8 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result { } b = merge_brush(&b, &patch, cmd)?; validate_brush(&b, cmd)?; + // The painting tools' Opacity takes 1-100 %, as in Photoshop: a 0 % brush paints nothing (#11812). + b.opacity = b.opacity.max(0.01); // Loading a stored tip can fail. Finish preparing the brush before changing its identity or // foreground colour, so a failed pick leaves the entire current brush state intact. s.load_brush_tips(&mut b).map_err(|e| bad(cmd, e))?; @@ -1365,7 +1367,7 @@ pub fn specs() -> Vec { spec!( "tools.setBrush", "Set Brush", - r##"{"preset":name?,"reset":bool?,…BrushSettings fields (camelCase, deep-merged; pose.overrideTiltX/Y:bool; pose.overrideTilt:legacy combined alias)}"##, + r##"{"preset":name?,"reset":bool?,…BrushSettings fields (camelCase, deep-merged; pose.overrideTiltX/Y:bool; pose.overrideTilt:legacy combined alias; opacity floors at 0.01)}"##, always, set_brush, true diff --git a/crates/ui-egui/src/brush_opacity_minimum_tests.rs b/crates/ui-egui/src/brush_opacity_minimum_tests.rs new file mode 100644 index 0000000000..cbceaef52c --- /dev/null +++ b/crates/ui-egui/src/brush_opacity_minimum_tests.rs @@ -0,0 +1,119 @@ +//! The Brush's Opacity starts at 1 %, as in Photoshop (#11812): its options-bar field takes whole +//! numbers from 1 to 100, the digit keys `00` set 100 %, and `tools.setBrush` floors opacity at 1 %. + +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = tool; + app +} + +fn options_bar(tool: Tool, theme: crate::theme::ThemeKind) -> Harness<'static, PhotocraftApp> { + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), theme); + ready = true; + return; + } + crate::panels::options_bar(app, ui); + }, + app(tool), + ); + h.run_steps(4); + h +} + +/// Types `text` into the options bar's Opacity field and presses Enter. +fn type_opacity(h: &mut Harness<'_, PhotocraftApp>, text: &str) -> f32 { + // "Opacity:" in the Photoshop-look themes, "Opacity" in the others. + let field = h + .query_all(egui_kittest::kittest::by().role(egui::accesskit::Role::SpinButton)) + .find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Opacity")) + .unwrap_or_else(|| panic!("the {:?} Opacity field", h.state().ui.tool)) + .rect(); + h.hover_at(field.center()); + h.run(); + h.drag_at(field.center()); + h.run(); + h.drop_at(field.center()); + h.run_steps(2); + h.event(Event::Key { key: Key::A, physical_key: Some(Key::A), pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + h.run(); + h.event(Event::Text(text.into())); + h.run_steps(2); + h.event(Event::Key { key: Key::Enter, physical_key: Some(Key::Enter), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + h.state().session.tools.brush.opacity +} + +/// In the Photoshop-look themes and the others (their options bars lay the Brush out apart); the +/// Pencil and Eraser fields take 1-100 whole numbers in Photoshop too. +#[test] +fn the_brush_opacity_field_takes_whole_numbers_from_1_to_100() { + use crate::theme::ThemeKind; + for theme in [ThemeKind::ProMedium, ThemeKind::Studio] { + for tool in [Tool::Brush, Tool::Pencil, Tool::Eraser] { + let mut h = options_bar(tool, theme); + for (typed, want) in [("0", 0.01), ("-10", 0.01), ("150", 1.0), ("45", 0.45), ("33.7", 0.34)] { + let got = type_opacity(&mut h, typed); + assert!((got - want).abs() < 1e-6, "{theme:?} {tool:?} typed {typed}: {got}, want {want}"); + } + } + } +} + +#[test] +fn double_zero_sets_the_brush_to_100_percent() { + let mut a = app(Tool::Brush); + a.run("tools.setBrush", json!({"brush": {"opacity": 0.3}})).unwrap(); + press(&mut a, 0, false, 0.0); + press(&mut a, 0, false, 100.0); + assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%"); + // Other pairs are the exact value; single digits are tens; 0 alone is 100%. + for (digits, want) in [([0, 7], 0.07), ([4, 5], 0.45)] { + press(&mut a, digits[0], false, 10_000.0); + press(&mut a, digits[1], false, 10_100.0); + assert!((a.session.tools.brush.opacity - want).abs() < 1e-6, "{digits:?}"); + } + for (d, want) in [(3, 0.3), (9, 0.9), (0, 1.0), (1, 0.1)] { + press(&mut a, d, false, 20_000.0 + f64::from(d) * 10_000.0); + assert!((a.session.tools.brush.opacity - want).abs() < 1e-6, "{d}"); + } + // With build-up on, ⇧ digits set the opacity: `00` is 100% there too. + a.session.tools.brush.build_up = true; + press(&mut a, 2, true, 200_000.0); + press(&mut a, 0, true, 300_000.0); + press(&mut a, 0, true, 300_100.0); + assert_eq!(a.session.tools.brush.opacity, 1.0); +} + +#[test] +fn double_zero_on_flow_keeps_its_one_percent() { + let mut a = app(Tool::Brush); + press(&mut a, 0, true, 0.0); + press(&mut a, 0, true, 100.0); + assert_eq!(a.session.tools.brush.flow, 0.01, "⇧00 is Flow's 1%, unchanged"); +} + +#[test] +fn set_brush_floors_opacity_at_one_percent() { + let mut a = app(Tool::Brush); + for params in [json!({"brush": {"opacity": 0}}), json!({"opacity": 0.0}), json!({"brush": {"opacity": 0.004}})] { + a.run("tools.setBrush", json!({"brush": {"opacity": 0.5}})).unwrap(); + a.run("tools.setBrush", params.clone()).unwrap(); + assert_eq!(a.session.tools.brush.opacity, 0.01, "{params}"); + } + a.run("tools.setBrush", json!({"brush": {"opacity": 0.37}})).unwrap(); + assert!((a.session.tools.brush.opacity - 0.37).abs() < 1e-6, "values above the floor are kept"); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 7f02c0c77b..6c1312a7fb 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -1,5 +1,5 @@ //! Number keys set opacity (#352): 1 = 10% … 9 = 90%, 0 = 100%; two digits -//! typed quickly set an exact value (4 then 5 = 45%, 0 then 0 = 0%). With the Brush, Pencil or +//! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush, #11812). With the Brush, Pencil or //! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the //! active layer's Opacity (⇧: Fill). Tools whose number is a strength or exposure are left alone. @@ -107,9 +107,13 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { let shift = shift ^ (build_up && matches!(target(tool), Target::Brush { flow: true })); match (target(app.ui.tool), shift) { (Target::Brush { .. }, false) => { - // Clone Stamp's and History Brush's Opacity fields (and their strokes) start at 1%, so - // `00` sets the 1% they actually paint with rather than showing a 0% they can't do. - let v = if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { v.max(0.01) } else { v }; + // The painting tools' Opacity fields (and `tools.setBrush`) start at 1%, so `00` sets the + // 1% they actually paint with rather than a 0% they can't do. The Brush's `00` is 100%, + // as in Photoshop (#11812); only `00` gives 0 here. + let v = match tool { + Tool::Brush if v <= 0.0 => 1.0, + _ => v.max(0.01), + }; let _ = app.run("tools.setBrush", json!({ "brush": { "opacity": v } })); } // The options bar's Flow field starts at 1%. @@ -163,7 +167,7 @@ mod tests { press(&mut a, 0, false, 9000.0); assert_eq!(a.session.tools.brush.opacity, 1.0, "0 = 100%"); press(&mut a, 0, false, 9100.0); - assert_eq!(a.session.tools.brush.opacity, 0.0, "00 = 0%"); + assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%"); press(&mut a, 2, true, 20000.0); assert!((a.session.tools.brush.flow - 0.2).abs() < 1e-6); press(&mut a, 0, true, 30000.0); @@ -224,10 +228,6 @@ mod tests { press(&mut a, 0, false, 100.0); assert!((a.session.tools.brush.opacity - 0.01).abs() < 1e-6, "{tool:?}"); } - let mut a = app(Tool::Brush); - press(&mut a, 0, false, 0.0); - press(&mut a, 0, false, 100.0); - assert!(a.session.tools.brush.opacity.abs() < 1e-6, "the Brush itself still goes to 0%"); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7fd35442cc..17b99b7460 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -978,6 +978,8 @@ mod menu_item_labels_tests; #[cfg(test)] mod pen_path_ownership_tests; +#[cfg(test)] +mod brush_opacity_minimum_tests; #[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 15c602ae99..6f0d2718c7 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -172,7 +172,8 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); } ui.add_enabled_ui(!block, |ui| { - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); + // A whole number from 1 to 100, as in Photoshop: 0 paints nothing (#11812). + whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 62.0); if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { b.pressure_opacity = !b.pressure_opacity; } @@ -206,7 +207,7 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, opt_label(ui, tl!("Mode")); let held = app.held_erase; paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 }); + whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, if t.pro { 62.0 } else { 66.0 }); opt_label(ui, tl!("Smoothing")); smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 }); widgets::vline(ui, 22.0); @@ -233,7 +234,7 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, // A Pencil-mode Eraser is always hard and at full flow (Photoshop). let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); + ui.add_enabled_ui(!block, |ui| whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 66.0)); ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); opt_label(ui, tl!("Smoothing")); smoothing_field(ui, b, 66.0); @@ -803,6 +804,15 @@ fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::op } } +/// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). +fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) { + opt_label(ui, label); + let mut percent = *value * 100.0; + if widgets::value_field_named(ui, label, &mut percent, range.clone(), "%", width).changed() { + *value = percent.round().max(*range.start()).min(*range.end()) / 100.0; + } +} + fn hint(ui: &mut egui::Ui, s: &str) { let t = Tokens::get(ui.ctx()); ui.label(RichText::new(s).color(t.text_faint)); From 2eb4e8441180a114da40cf0f3e498d75f45e6d66 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 6 Nov 2026 21:23:30 -0800 Subject: [PATCH 079/113] Use toolbar order for fresh tool shortcuts --- crates/ui-egui/src/input/shortcuts.rs | 11 ++- .../src/input/tool_key_default_tests.rs | 85 +++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/input/tool_key_default_tests.rs diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 0abd096530..63444f628a 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -916,15 +916,16 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im if cycle_shift || pressed(k) { let before = app.ui.tool; let mut group: Vec = Tool::ALL.iter().copied().filter(|x| x.key() == t.key() && crate::tool_shortcuts::uses_default(app, *x)).collect(); - // Shift+key (the cycle and the fallback to the group's first tool) uses the toolbar - // flyout's order; plain keys keep the `Tool::ALL` order. + // Shift+key cycles in toolbar flyout order. if cycle_shift { group.sort_by_key(|x| crate::panels::toolbar::toolbar_position(*x)); } app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) { Some(i) if shift_switch && !cycle_shift => group[i], Some(i) => group[(i + 1) % group.len()], - None => app.ui.group_tool(t.key()).filter(|last| group.contains(last)).unwrap_or(group[0]), + None => app.ui.group_tool(t.key()).filter(|last| group.contains(last)).unwrap_or_else(|| { + group.iter().copied().min_by_key(|tool| crate::panels::toolbar::toolbar_position(*tool)).unwrap_or(t) + }), }; crate::tool_memory::ended_by_tool(app); // `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded. @@ -942,3 +943,7 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "tool_key_default_tests.rs"] +mod tool_key_default_tests; diff --git a/crates/ui-egui/src/input/tool_key_default_tests.rs b/crates/ui-egui/src/input/tool_key_default_tests.rs new file mode 100644 index 0000000000..6e5347ed17 --- /dev/null +++ b/crates/ui-egui/src/input/tool_key_default_tests.rs @@ -0,0 +1,85 @@ +use super::{Key, Modifiers, PhotocraftApp, Tool, handle}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::spring_tools::key_of; +use std::collections::HashSet; + +fn app() -> PhotocraftApp { + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) +} + +fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) { + let raw = egui::RawInput { + events: vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }; + ctx.begin_pass(raw); + handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +#[test] +fn fresh_tool_letters_pick_the_first_tool_in_toolbar_order() { + for shift_switch in [true, false] { + let mut checked = HashSet::new(); + for tool in TOOL_SECTIONS.iter().flat_map(|section| section.iter()).flat_map(|slot| slot.iter()).copied() { + let Some(key) = key_of(tool.key()) else { continue }; + if !checked.insert(key) { + continue; + } + + let mut app = app(); + app.session.edit_prefs(|prefs| prefs.tools.use_shift_key_for_tool_switch = shift_switch); + if app.ui.tool.key() == tool.key() { + app.ui.tool = Tool::Brush; + } + press(&mut app, &egui::Context::default(), key, Modifiers::NONE); + assert_eq!(app.ui.tool, tool, "{key:?}, Shift switch: {shift_switch}"); + } + assert_eq!(checked, Tool::ALL.into_iter().filter_map(|tool| key_of(tool.key())).collect::>()); + } +} + +#[test] +fn plain_w_returns_to_the_remembered_magic_wand() { + for hidden in [false, true] { + let mut app = app(); + let ctx = egui::Context::default(); + if hidden { + app.session.edit_prefs(|prefs| prefs.toolbar.hidden = vec!["MagicWand".to_owned()]); + } + app.ui.tool = Tool::MagicWand; + press(&mut app, &ctx, Key::B, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Brush); + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagicWand, "hidden: {hidden}"); + } +} + +#[test] +fn shift_w_cycles_in_toolbar_order() { + let mut app = app(); + let ctx = egui::Context::default(); + app.ui.tool = Tool::ObjectSelection; + + for expected in [Tool::QuickSelection, Tool::MagicWand, Tool::ObjectSelection] { + press(&mut app, &ctx, Key::W, Modifiers::SHIFT); + assert_eq!(app.ui.tool, expected); + } + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::ObjectSelection); +} + +#[test] +fn remapped_first_tool_is_skipped_by_its_default_letter() { + let mut app = app(); + let ctx = egui::Context::default(); + app.run("prefs.set", serde_json::json!({"path": "shortcuts.tools.select.objectSelection", "value": "F6"})).unwrap(); + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::QuickSelection); + press(&mut app, &ctx, Key::F6, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::ObjectSelection); +} From 26a8215043ece846add6b03b745cb2bd55c7d799 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 6 Nov 2026 21:58:06 -0800 Subject: [PATCH 080/113] Format the fresh tool shortcut fallback --- crates/ui-egui/src/input/shortcuts.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 63444f628a..212d16b63d 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -923,9 +923,11 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) { Some(i) if shift_switch && !cycle_shift => group[i], Some(i) => group[(i + 1) % group.len()], - None => app.ui.group_tool(t.key()).filter(|last| group.contains(last)).unwrap_or_else(|| { - group.iter().copied().min_by_key(|tool| crate::panels::toolbar::toolbar_position(*tool)).unwrap_or(t) - }), + None => app + .ui + .group_tool(t.key()) + .filter(|last| group.contains(last)) + .unwrap_or_else(|| group.iter().copied().min_by_key(|tool| crate::panels::toolbar::toolbar_position(*tool)).unwrap_or(t)), }; crate::tool_memory::ended_by_tool(app); // `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded. From 4551b2a2007bd378629654089074391e7e47c2cf Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 6 Nov 2026 23:13:48 -0800 Subject: [PATCH 081/113] Document tool shortcut selection behavior --- crates/ui-egui/src/input/shortcuts.rs | 5 +++-- crates/ui-egui/src/input/tool_key_default_tests.rs | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 212d16b63d..cf23556c35 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -903,8 +903,9 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::opacity_keys::handle(app, ctx); } -/// Selects a tool from its letter key. Pressing the key of the current group cycles within it; with -/// the Shift-switch preference only ⇧+key cycles. Returns true when a tool key was handled. +/// Selects a tool from its letter key. Entering a group uses its remembered eligible tool or the +/// first eligible tool in toolbar order. Pressing the key of the current group cycles within it. +/// With the Shift-switch preference, only ⇧+key cycles. Returns true when a tool key was handled. fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &impl Fn(Key) -> bool) -> bool { let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch; for t in Tool::ALL { diff --git a/crates/ui-egui/src/input/tool_key_default_tests.rs b/crates/ui-egui/src/input/tool_key_default_tests.rs index 6e5347ed17..5b846d5e7f 100644 --- a/crates/ui-egui/src/input/tool_key_default_tests.rs +++ b/crates/ui-egui/src/input/tool_key_default_tests.rs @@ -21,6 +21,7 @@ fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modi ctx.end_pass().textures_delta.clear(); } +/// A fresh app enters each default letter group at its first toolbar tool under either preference. #[test] fn fresh_tool_letters_pick_the_first_tool_in_toolbar_order() { for shift_switch in [true, false] { @@ -43,6 +44,7 @@ fn fresh_tool_letters_pick_the_first_tool_in_toolbar_order() { } } +/// A remembered Magic Wand takes precedence over the fresh W default, even when hidden. #[test] fn plain_w_returns_to_the_remembered_magic_wand() { for hidden in [false, true] { @@ -59,6 +61,8 @@ fn plain_w_returns_to_the_remembered_magic_wand() { } } +/// Shift+W follows the flyout order and wraps. With the default preference, plain W keeps +/// the current tool when it already belongs to the group. #[test] fn shift_w_cycles_in_toolbar_order() { let mut app = app(); From f52206293613436e518a7c964ce30c2e415c35fe Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 7 Nov 2026 02:45:20 -0800 Subject: [PATCH 082/113] Expect Object Selection on the first W press --- crates/ui-egui/src/tool_shift_cycle_order_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index 83c3ca33cc..e49077c4ff 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -160,5 +160,5 @@ fn a_plain_w_from_outside_the_group_keeps_selecting_what_it_selected_before() { ctx.begin_pass(raw); crate::shortcuts::handle(&mut app, &ctx); ctx.end_pass().textures_delta.clear(); - assert_eq!(app.ui.tool, Tool::MagicWand, "the first W tool in Tool::ALL, not the first in the flyout"); + assert_eq!(app.ui.tool, Tool::ObjectSelection, "fresh W selects the first tool in the flyout"); } From 5fa91a09395b9d4c205558a185baef47e37baaf4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 12:05:58 +0100 Subject: [PATCH 083/113] Address CodeRabbit review: whole-percent Opacity display, Pencil "00" = 100 % (#11812) The Opacity field now shows a value set elsewhere (a tools.setBrush fraction, an older saved 0) as the whole percent in 1-100 it can hold, without writing it back. "00" sets the Pencil to 100 % like the Brush, as measured in the reference application. Co-Authored-By: Claude Opus 5.5 --- .../src/brush_opacity_minimum_tests.rs | 27 +++++++++++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 8 +++--- crates/ui-egui/src/panels/options_bar.rs | 5 ++-- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/brush_opacity_minimum_tests.rs b/crates/ui-egui/src/brush_opacity_minimum_tests.rs index cbceaef52c..77f84a7b41 100644 --- a/crates/ui-egui/src/brush_opacity_minimum_tests.rs +++ b/crates/ui-egui/src/brush_opacity_minimum_tests.rs @@ -117,3 +117,30 @@ fn set_brush_floors_opacity_at_one_percent() { a.run("tools.setBrush", json!({"brush": {"opacity": 0.37}})).unwrap(); assert!((a.session.tools.brush.opacity - 0.37).abs() < 1e-6, "values above the floor are kept"); } + +/// The Pencil's `00` is 100 % too (the Pencil has no Flow, so ⇧ digits are not involved). +#[test] +fn double_zero_sets_the_pencil_to_100_percent() { + let mut a = app(Tool::Pencil); + a.run("tools.setBrush", json!({"brush": {"opacity": 0.3}})).unwrap(); + press(&mut a, 0, false, 0.0); + press(&mut a, 0, false, 100.0); + assert_eq!(a.session.tools.brush.opacity, 1.0, "00 = 100%"); +} + +/// An opacity set outside the field (a `tools.setBrush` fraction, an older saved 0) shows as the +/// whole percent in 1-100 the field can hold. +#[test] +fn the_opacity_field_shows_outside_values_as_whole_percents() { + let mut h = options_bar(Tool::Brush, crate::theme::ThemeKind::ProMedium); + for (stored, shown) in [(0.337, 34.0), (0.0, 1.0), (0.004, 1.0)] { + h.state_mut().session.tools.brush.opacity = stored; + h.run_steps(2); + let value = h + .query_all(egui_kittest::kittest::by().role(egui::accesskit::Role::SpinButton)) + .find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Opacity")) + .and_then(|n| n.accesskit_node().numeric_value()); + assert_eq!(value, Some(shown), "stored {stored}"); + assert_eq!(h.state().session.tools.brush.opacity, stored, "showing it does not change it"); + } +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 6c1312a7fb..167261e417 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -1,5 +1,5 @@ //! Number keys set opacity (#352): 1 = 10% … 9 = 90%, 0 = 100%; two digits -//! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush, #11812). With the Brush, Pencil or +//! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush and the Pencil, #11812). With the Brush, Pencil or //! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the //! active layer's Opacity (⇧: Fill). Tools whose number is a strength or exposure are left alone. @@ -108,10 +108,10 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { match (target(app.ui.tool), shift) { (Target::Brush { .. }, false) => { // The painting tools' Opacity fields (and `tools.setBrush`) start at 1%, so `00` sets the - // 1% they actually paint with rather than a 0% they can't do. The Brush's `00` is 100%, - // as in Photoshop (#11812); only `00` gives 0 here. + // 1% they actually paint with rather than a 0% they can't do. The Brush's and the + // Pencil's `00` is 100%, as in Photoshop (#11812); only `00` gives 0 here. let v = match tool { - Tool::Brush if v <= 0.0 => 1.0, + Tool::Brush | Tool::Pencil if v <= 0.0 => 1.0, _ => v.max(0.01), }; let _ = app.run("tools.setBrush", json!({ "brush": { "opacity": v } })); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 6f0d2718c7..aa39becba5 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -804,10 +804,11 @@ fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::op } } -/// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). +/// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). A value set elsewhere (a +/// `tools.setBrush` fraction, an older saved 0) shows as the whole percent in range. fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) { opt_label(ui, label); - let mut percent = *value * 100.0; + let mut percent = (*value * 100.0).round().max(*range.start()).min(*range.end()); if widgets::value_field_named(ui, label, &mut percent, range.clone(), "%", width).changed() { *value = percent.round().max(*range.start()).min(*range.end()) / 100.0; } From 6d3e9e71bf1aefa1db0ec8e7623506889d1525c5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 13:00:55 +0100 Subject: [PATCH 084/113] Color Sampler: right-click menu on the canvas (#11733) A right-click with the Color Sampler opens its menu in the reference application's order: Delete, then the readout modes. Delete removes the sampler under the pointer (view.colorSamplers.delete) and the rest are renumbered. Off a sampler every row is greyed. The readout rows stay greyed until samplers have their own readout mode (#11735). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 62 +++++- crates/ui-egui/src/tools/analysis_ui.rs | 12 ++ .../tools/analysis_ui/sampler_menu_tests.rs | 190 ++++++++++++++++++ crates/ui-egui/src/transform_type_tests.rs | 1 + 4 files changed, 264 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index b2e377e0ec..098304d147 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -46,6 +46,10 @@ pub struct CanvasToolMenu { /// had when it opened. #[serde(default)] pub crop: Option>, + /// The Color Sampler menu's sampler: the one under the pointer when it opened (its index), + /// `None` off a sampler, where every row is greyed. + #[serde(default)] + pub sampler: Option, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -303,6 +307,7 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; guide: false, spelling: None, crop: Some(users), + sampler: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -445,7 +450,42 @@ pub const PEN_MENU: &[Row] = &[ Some(("Disable Symmetry Path", "paint.symmetryDisable")), ]; -/// Tools whose plain canvas right-click offers selection actions. +/// The Color Sampler menu's Delete row: removes the sampler the menu opened on. +pub const SAMPLER_DELETE: &str = "view.colorSamplers.delete"; + +/// The Color Sampler's canvas menu (#11733), in the reference application's order: Delete, then +/// the readout modes for the sampler under the pointer. The readout rows are this menu's own ids +/// and stay greyed until samplers have their own readout mode. +pub const SAMPLER_MENU: &[Row] = &[ + Some(("Delete", SAMPLER_DELETE)), + None, + Some(("Actual Color", "colorSampler.readout.actual")), + Some(("Proof Color", "colorSampler.readout.proof")), + None, + Some(("Grayscale", "colorSampler.readout.gray")), + Some(("RGB Color", "colorSampler.readout.rgb")), + Some(("Web Color", "colorSampler.readout.web")), + Some(("HSB Color", "colorSampler.readout.hsb")), + Some(("HSL Color", "colorSampler.readout.hsl")), + Some(("CMYK Color", "colorSampler.readout.cmyk")), + Some(("Lab Color", "colorSampler.readout.lab")), + None, + Some(("Grayscale 16 bit", "colorSampler.readout.gray16")), + Some(("RGB 16 bit", "colorSampler.readout.rgb16")), + Some(("CMYK 16 bit", "colorSampler.readout.cmyk16")), + Some(("Lab 16 bit", "colorSampler.readout.lab16")), + None, + Some(("Total Ink", "colorSampler.readout.totalInk")), +]; + +/// Is `menu` the Color Sampler's own menu (not the pasteboard, guide or transform menu opened +/// with it)? +fn sampler_menu(menu: &CanvasToolMenu) -> bool { + menu.tool == Tool::ColorSampler && !menu.transform && !menu.pasteboard && !menu.guide && menu.crop.is_none() && menu.anchor.is_none() +} + +/// Tools whose plain canvas right-click opens a menu: the selection tools' actions, the path +/// menu and the Color Sampler's. pub fn applies(tool: Tool) -> bool { matches!( tool, @@ -461,6 +501,7 @@ pub fn applies(tool: Tool) -> bool { // Its brush is set from the options bar's chip; the canvas right-click is the // selection menu, as in Photoshop (#7268). | Tool::QuickSelection + | Tool::ColorSampler ) || path_menu(tool) } @@ -510,6 +551,8 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { TYPE_LAYER_MENU } else if path_menu(menu.tool) { PEN_MENU + } else if sampler_menu(menu) { + SAMPLER_MENU } else { selection_rows(menu.has_selection) } @@ -649,6 +692,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> guide: false, spelling: None, crop: None, + sampler: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -674,6 +718,9 @@ pub fn engine_call(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> _ => (command.into(), json!({})), }; } + if sampler_menu(menu) { + return (command.into(), menu.sampler.map_or(json!({}), |i| json!({"index": i}))); + } match pasteboard_choice(command) { Some(c) if menu.pasteboard => ("prefs.set".into(), json!({"values": {"interface.canvasColor": c.name()}})), _ if menu.pasteboard => ("prefs.set".into(), json!({})), @@ -727,6 +774,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: guide: false, spelling: None, crop: None, + sampler: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -758,6 +806,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui guide: true, spelling: None, crop: None, + sampler: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -810,6 +859,11 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) if menu.type_layer { return TYPE_LAYER_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command); } + // Off a sampler every row is greyed. The readout rows wait for per-sampler readout modes. + if sampler_menu(menu) { + let count = app.session.active().map_or(0, |d| d.color_samplers.len()); + return command == SAMPLER_DELETE && menu.sampler.is_some_and(|i| i < count); + } if menu.transform || !path_menu(menu.tool) { return crate::menus::is_enabled(app, command); } @@ -870,6 +924,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; + let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; app.ui.canvas_tool_menu = Some(CanvasToolMenu { pos, tool, @@ -884,6 +939,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] guide: false, spelling, crop: None, + sampler, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -911,6 +967,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; guide: false, spelling: None, crop: None, + sampler: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -964,6 +1021,9 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { choose_type(app, ctx, command) } else if path_menu(menu.tool) && !menu.transform { choose_pen(app, ctx, &menu, command) + } else if sampler_menu(&menu) { + let (id, params) = engine_call(app, &menu, command); + app.run(&id, params).map(|_| ()) } else if command == "select.toWorkPath" { // Photoshop's Make Work Path… asks for the tolerance first. spec_dialog(app, command, "Make Work Path", r##"{"tolerance":0.5..10=2}"##, serde_json::Map::new()); diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index ed113909a6..4f6f49eae2 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -392,6 +392,18 @@ fn nearest_sampler(points: &[[f64; 2]], at: [f64; 2], tol: f64) -> Option points.iter().enumerate().filter(|(_, q)| dist(**q, at) <= tol).min_by(|a, b| dist(*a.1, at).total_cmp(&dist(*b.1, at))).map(|(i, _)| i) } +/// The Color Sampler point under document point `at` on the active document, by the same hit test +/// a click uses, so the right-click menu acts on the sampler a click would grab. +pub(crate) fn sampler_at(app: &PhotocraftApp, at: [f64; 2]) -> Option { + if !at.iter().all(|v| v.is_finite()) { + return None; + } + nearest_sampler(&app.session.active()?.color_samplers, at, tolerance(app)) +} + +#[cfg(test)] +mod sampler_menu_tests; + /// Show a command error in the status bar without treating the sample-limit message as a fault. fn status_on_err(app: &mut PhotocraftApp, r: Result) { if let Err(e) = r { diff --git a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs new file mode 100644 index 0000000000..feef455427 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs @@ -0,0 +1,190 @@ +//! #11733: the Color Sampler's right-click menu on the canvas. + +use egui::{Event, Modifiers, PointerButton, vec2}; +use egui_kittest::Harness; +use serde_json::{Value, json}; + +use crate::canvas_tool_menu::{SAMPLER_DELETE, SAMPLER_MENU}; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::{PhotocraftApp, Tool}; + +/// A 200 x 100 document with the Color Sampler and samplers at (20, 20) and (120, 60). +fn app() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 20, "y": 20})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 120, "y": 60})).unwrap(); + app.ui.tool = Tool::ColorSampler; + (app, egui::Context::default()) +} + +fn control(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + let Outcome::Done(v) = handle(app, ctx, &req) else { panic!("{method} replies at once") }; + v +} + +/// An agent's right-click at document point (x, y), as `ui.pointer` sends it. +fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64) { + let r = control(app, ctx, "ui.pointer", json!({"button": "secondary", "events": [{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]})); + assert_eq!(r["ok"], json!(true), "{r}"); +} + +fn entries(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { + let r = control(app, ctx, "ui.inspect", json!({})); + r["result"]["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_else(|| panic!("no canvasToolMenu: {r}")) +} + +fn samplers(app: &PhotocraftApp) -> Vec<[f64; 2]> { + app.session.active().unwrap().color_samplers.clone() +} + +/// The reference application's rows, in order, with `|` for a separator. +const EXPECTED: &[&str] = &[ + "Delete", + "|", + "Actual Color", + "Proof Color", + "|", + "Grayscale", + "RGB Color", + "Web Color", + "HSB Color", + "HSL Color", + "CMYK Color", + "Lab Color", + "|", + "Grayscale 16 bit", + "RGB 16 bit", + "CMYK 16 bit", + "Lab 16 bit", + "|", + "Total Ink", +]; + +fn labels(entries: &[Value]) -> Vec { + entries.iter().map(|e| if e["separator"] == json!(true) { "|".to_string() } else { e["label"].as_str().unwrap().to_string() }).collect() +} + +#[test] +fn right_click_on_a_sampler_lists_the_menu_in_order_with_delete_enabled() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 20.5, 20.5); + let menu = app.ui.canvas_tool_menu.clone().expect("the Color Sampler menu opens"); + assert_eq!(menu.tool, Tool::ColorSampler); + assert_eq!(menu.sampler, Some(0)); + let entries = entries(&mut app, &ctx); + assert_eq!(labels(&entries), EXPECTED); + let enabled: Vec<&str> = entries.iter().filter(|e| e["enabled"] == json!(true)).filter_map(|e| e["id"].as_str()).collect(); + // The readout rows wait for per-sampler readout modes (#11735) and stay greyed until then. + assert_eq!(enabled, [SAMPLER_DELETE]); + for (_, id) in SAMPLER_MENU.iter().flatten() { + assert!(!crate::canvas_tool_menu::mode_checked(&app, &menu, id), "{id} shows no checkmark"); + } + assert_eq!(samplers(&app).len(), 2, "the right-click places no sampler"); +} + +#[test] +fn right_click_off_a_sampler_greys_every_row() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 70.0, 40.0); + let menu = app.ui.canvas_tool_menu.clone().expect("the menu opens off a sampler too"); + assert_eq!(menu.sampler, None); + let entries = entries(&mut app, &ctx); + assert_eq!(labels(&entries), EXPECTED); + assert!(entries.iter().all(|e| e["enabled"] != json!(true)), "every row greyed: {entries:?}"); + let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); + assert_eq!(r["ok"], json!(false), "a greyed Delete does nothing: {r}"); + assert_eq!(samplers(&app).len(), 2, "nothing deleted, no sampler placed"); +} + +#[test] +fn delete_removes_the_sampler_under_the_pointer_and_renumbers_the_rest() { + let (mut app, ctx) = app(); + app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); + right_click(&mut app, &ctx, 120.0, 60.0); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); + assert_eq!(r["ok"], json!(true), "{r}"); + assert_eq!(samplers(&app), [[20.0, 20.0], [180.0, 90.0]], "#3 became #2"); + assert!(app.ui.canvas_tool_menu.is_none(), "choosing closes the menu"); + let listed = app.run("view.colorSamplers.list", json!({})).unwrap(); + assert_eq!(listed["samplers"][1]["number"], json!(2)); +} + +#[test] +fn readout_rows_do_nothing_until_samplers_have_readout_modes() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 20.0, 20.0); + let before = app.session.active().unwrap().revision; + let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": "colorSampler.readout.hsl"})); + assert_eq!(r["ok"], json!(false), "{r}"); + assert_eq!(app.session.active().unwrap().revision, before); + assert_eq!(samplers(&app).len(), 2); +} + +#[test] +fn a_stale_sampler_or_odd_point_fails_gracefully() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 120.0, 60.0); + // The sampler went away while the menu was open: Delete greys out instead of removing another. + app.run("view.colorSamplers.clear", json!({})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!crate::canvas_tool_menu::entry_enabled(&app, &menu, SAMPLER_DELETE)); + crate::canvas_tool_menu::choose(&mut app, &ctx, SAMPLER_DELETE); + assert_eq!(samplers(&app), [[5.0, 5.0]]); + for p in [[f64::NAN, 5.0], [f64::INFINITY, 5.0], [5.0, f64::NEG_INFINITY]] { + assert_eq!(super::sampler_at(&app, p), None); + } + // No document: the menu opens greyed, nothing panics. + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty.ui.tool = Tool::ColorSampler; + assert_eq!(super::sampler_at(&empty, [1.0, 1.0]), None); + if crate::canvas_tool_menu::open_at(&mut empty, &ctx, Tool::ColorSampler, [10.0, 10.0], Some([1.0, 1.0])) { + let menu = empty.ui.canvas_tool_menu.clone().unwrap(); + assert!(SAMPLER_MENU.iter().flatten().all(|(_, id)| !crate::canvas_tool_menu::entry_enabled(&empty, &menu, id))); + crate::canvas_tool_menu::choose(&mut empty, &ctx, SAMPLER_DELETE); + } +} + +#[test] +fn other_tools_keep_their_menus() { + let (mut app, ctx) = app(); + app.ui.tool = Tool::RectMarquee; + right_click(&mut app, &ctx, 20.0, 20.0); + let menu = app.ui.canvas_tool_menu.clone().expect("the selection menu"); + assert_eq!(crate::canvas_tool_menu::rows(&menu), crate::canvas_tool_menu::NO_SELECTION_MENU); + app.ui.canvas_tool_menu = None; + app.ui.tool = Tool::Pen; + right_click(&mut app, &ctx, 20.0, 20.0); + let menu = app.ui.canvas_tool_menu.clone().expect("the path menu"); + assert_eq!(crate::canvas_tool_menu::rows(&menu), crate::canvas_tool_menu::PEN_MENU); + app.ui.canvas_tool_menu = None; + // Outside the image the Color Sampler keeps the pasteboard menu. + app.ui.tool = Tool::ColorSampler; + right_click(&mut app, &ctx, 250.0, 40.0); + assert!(app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard)); +} + +/// A real right-click on the canvas over sampler #2 opens the menu on it. +#[test] +fn canvas_right_click_opens_the_menu_on_the_sampler() { + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app().0 + }); + h.run_steps(5); + let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); + let at = xf.to_screen(120.5, 60.5); + h.event(Event::PointerMoved(at)); + h.run_steps(2); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + let menu = h.state().ui.canvas_tool_menu.clone().expect("the Color Sampler menu opens"); + assert_eq!((menu.tool, menu.sampler), (Tool::ColorSampler, Some(1))); + assert_eq!(h.state().session.active().unwrap().color_samplers.len(), 2, "no sampler was placed or moved"); +} diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index eeb91f44b9..c62e7cf87d 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -56,6 +56,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { guide: false, spelling: None, crop: None, + sampler: None, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); From 9db78c5d317235a2618e2f7a7bf2347d811722c8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 13:02:04 +0100 Subject: [PATCH 085/113] Background Eraser: number keys set the Tolerance (#11907) With the Background Eraser active, 1-9 set its Tolerance to 10-90 %, 0 to 100 %, and two digits typed quickly to that exact value, as the number keys set Opacity for the painting tools. Shift+digit and "00" keep today's behaviour. Other tools' digits are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/background_eraser_digit_keys_tests.rs | 125 ++++++++++++++++++ crates/ui-egui/src/input/opacity_keys.rs | 8 +- crates/ui-egui/src/lib.rs | 3 + 3 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/background_eraser_digit_keys_tests.rs diff --git a/crates/ui-egui/src/background_eraser_digit_keys_tests.rs b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs new file mode 100644 index 0000000000..9cddb5a7eb --- /dev/null +++ b/crates/ui-egui/src/background_eraser_digit_keys_tests.rs @@ -0,0 +1,125 @@ +//! #11907: with the Background Eraser active, the number keys set its Tolerance as they set Opacity +//! for the painting tools (3 = 30%, 0 = 100%, 5 then 5 typed quickly = 55%), as in the reference +//! application. Other tools' digits are unchanged. + +use egui::{Event, Key, Modifiers}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +fn tolerance(app: &PhotocraftApp) -> f32 { + app.ui.tool_options.bg_tolerance +} + +fn layer(app: &PhotocraftApp) -> (f32, f32) { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + (l.opacity, l.fill_opacity) +} + +#[test] +fn single_digits_set_the_tolerance() { + let mut a = app(Tool::BackgroundEraser); + assert_eq!(tolerance(&a), 50.0, "default"); + press(&mut a, 3, false, 0.0); + assert_eq!(tolerance(&a), 30.0); + press(&mut a, 0, false, 5000.0); + assert_eq!(tolerance(&a), 100.0, "0 = 100%"); + press(&mut a, 1, false, 10000.0); + assert_eq!(tolerance(&a), 10.0); +} + +#[test] +fn two_quick_digits_set_an_exact_tolerance() { + let mut a = app(Tool::BackgroundEraser); + press(&mut a, 5, false, 0.0); + press(&mut a, 5, false, 300.0); + assert_eq!(tolerance(&a), 55.0); + // A slow second digit starts over. + press(&mut a, 4, false, 5000.0); + press(&mut a, 2, false, 9000.0); + assert_eq!(tolerance(&a), 20.0); +} + +#[test] +fn the_tolerance_is_shown_in_ui_inspect() { + let mut a = app(Tool::BackgroundEraser); + press(&mut a, 3, false, 0.0); + let options = serde_json::to_value(&a.ui.tool_options).unwrap(); + assert_eq!(options["bg_tolerance"], json!(30.0)); +} + +#[test] +fn background_eraser_digits_leave_the_brush_and_the_layer_alone() { + let mut a = app(Tool::BackgroundEraser); + let brush = a.session.tools.brush.clone(); + press(&mut a, 7, false, 0.0); + assert_eq!(a.session.tools.brush, brush); + assert_eq!(layer(&a), (1.0, 1.0)); + assert_eq!(a.ui.tool_options.fill_opacity, 100.0); +} + +#[test] +fn unmeasured_shift_digits_and_double_zero_keep_the_tolerance() { + let mut a = app(Tool::BackgroundEraser); + press(&mut a, 3, true, 0.0); + assert_eq!(tolerance(&a), 50.0, "⇧3 changes nothing"); + press(&mut a, 0, false, 5000.0); + press(&mut a, 0, false, 5100.0); + assert_eq!(tolerance(&a), 100.0, "00 keeps the 100% of the first 0"); +} + +#[test] +fn other_tools_digits_are_unchanged() { + for tool in [Tool::Brush, Tool::Pencil, Tool::Eraser] { + let mut a = app(tool); + press(&mut a, 3, false, 0.0); + assert!((a.session.tools.brush.opacity - 0.3).abs() < 1e-6, "{tool:?}"); + assert_eq!(tolerance(&a), 50.0, "{tool:?}"); + } + for tool in [Tool::Gradient, Tool::PaintBucket] { + let mut a = app(tool); + press(&mut a, 3, false, 0.0); + assert_eq!(a.ui.tool_options.fill_opacity, 30.0, "{tool:?}"); + assert_eq!(tolerance(&a), 50.0, "{tool:?}"); + } + let mut a = app(Tool::Move); + press(&mut a, 3, false, 0.0); + assert!((layer(&a).0 - 0.3).abs() < 1e-6); + assert_eq!(tolerance(&a), 50.0); + // The tools whose number is a strength, exposure or tolerance of their own still ignore the digits. + for tool in [Tool::ColorReplacement, Tool::Dodge, Tool::Smudge, Tool::MagicEraser] { + let mut a = app(tool); + let before = (a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone()); + press(&mut a, 3, false, 0.0); + assert_eq!((a.session.tools.brush.clone(), layer(&a), a.ui.tool_options.clone()), before, "{tool:?}"); + } +} + +/// Through the whole app: number keys typed over the canvas (no widget focused). +#[test] +fn number_keys_set_the_tolerance_in_the_app() { + use egui_kittest::Harness; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app(Tool::BackgroundEraser) + }); + h.run_steps(4); + let key = |h: &mut Harness<'_, PhotocraftApp>, k: Key| { + h.event(Event::Key { key: k, physical_key: Some(k), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.event(Event::Key { key: k, physical_key: Some(k), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + }; + key(&mut h, Key::Num3); + assert_eq!(tolerance(h.state()), 30.0); +} diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 7f02c0c77b..2874efeba9 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -2,7 +2,8 @@ //! typed quickly set an exact value (4 then 5 = 45%, 0 then 0 = 0%). With the Brush, Pencil or //! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the -//! active layer's Opacity (⇧: Fill). Tools whose number is a strength or exposure are left alone. +//! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose +//! number is a strength or exposure are left alone. use egui::{Event, Key}; use serde_json::json; @@ -25,6 +26,8 @@ enum Target { }, /// The Gradient / Paint Bucket opacity option. ToolOpacity, + /// The Background Eraser's Tolerance option. + BgTolerance, /// The active layer's opacity (⇧: fill). Layer, None, @@ -35,6 +38,7 @@ fn target(tool: Tool) -> Target { Tool::Brush | Tool::Eraser | Tool::CloneStamp | Tool::HistoryBrush => Target::Brush { flow: true }, Tool::Pencil => Target::Brush { flow: false }, Tool::Gradient | Tool::PaintBucket => Target::ToolOpacity, + Tool::BackgroundEraser => Target::BgTolerance, // Their options-bar number is a strength, exposure or tolerance, not this opacity. t if t.is_brushlike() || t == Tool::MagicEraser => Target::None, _ => Target::Layer, @@ -117,6 +121,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { let _ = app.run("tools.setBrush", json!({ "brush": { "flow": v.max(0.01) } })); } (Target::ToolOpacity, false) => app.ui.tool_options.fill_opacity = percent, + // The Tolerance field starts at 1%; `00` (0%) keeps today's value rather than guessing. + (Target::BgTolerance, false) if percent >= 1.0 => app.ui.tool_options.bg_tolerance = percent, (Target::Layer, _) => { // The locked Background has no opacity or fill. let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 89d83237e5..3ecdc3daf2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -996,3 +996,6 @@ mod preferences_submenu_tests; mod selection_move_step_tests; #[cfg(test)] mod view_guides_submenu_tests; + +#[cfg(test)] +mod background_eraser_digit_keys_tests; From 41d6490ef2c40723401717659e36099cd1dcdbe8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 16:34:06 +0100 Subject: [PATCH 086/113] test(compose): CMYK reference keeps the source ink over nothing (#12079) The reference's source-over computed s * sa / sa over an empty backdrop, one ulp off the stored ink. Behind a Paint.NET Color Burn of a Posterize that lands exactly on 73.5/255, the ulp flipped the 8-bit rounding and random_documents_match_the_reference failed on main. Keep the source ink when nothing shows through or both inks agree, as cmyk::normal does. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/cmyk/tests.rs | 37 +++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/cmyk/tests.rs b/crates/compose/src/cmyk/tests.rs index 8deaa68de3..952d29be63 100644 --- a/crates/compose/src/cmyk/tests.rs +++ b/crates/compose/src/cmyk/tests.rs @@ -60,7 +60,11 @@ fn over(b: Cmyka, s: Cmyka, opacity: f32) -> Cmyka { } let mut o = [0.0; 5]; for i in 0..4 { - o[i] = (s[i] * sa + b[i] * b[4] * (1.0 - sa)) / a; + // Over nothing, under a covering source, or where both inks agree, the result is the + // source's ink exactly: `s * sa / sa` can be one ulp off, which a later mode or + // rounding step can turn into a whole level. + let shows_through = b[4] > 0.0 && sa < 1.0; + o[i] = if !shows_through || b[i] == s[i] { s[i] } else { (s[i] * sa + b[i] * b[4] * (1.0 - sa)) / a }; } o[4] = a; o @@ -762,6 +766,37 @@ fn clips_onto_pass_through(layers: &[LayerSpec]) -> bool { }) || layers.iter().any(|l| matches!(l, LayerSpec::Group { children, .. } if clips_onto_pass_through(children))) } +/// A proptest case from main's CI: a masked shape below 100% Fill, then Posterize in Color +/// Burn (Paint.NET) inside an isolated group. The burned brightness is exactly 73.5/255. +#[test] +fn posterize_in_paint_net_color_burn_on_a_rounding_tie_matches_the_reference() { + let shape = LayerSpec::Pixels { + kind: Kind::Shape, + blend: BlendMode::Normal, + fills: vec![(Rect::new(0, 0, 1, 1), [0.47422728, 0.0, 0.0, 0.0, 1.0])], + opacity: 1.0, + fill: 0.876696, + clipped: false, + visible: true, + mask: Some(MaskSpec { rects: vec![], default: 0.06425183, density: 1.0, enabled: true }), + }; + let posterize = LayerSpec::Pixels { + kind: Kind::Adjust(AdjSpec::Posterize(4)), + blend: BlendMode::PaintNetColorBurn, + fills: vec![(Rect::new(0, 0, 1, 1), [0.0; 5])], + opacity: 1.0, + fill: 1.0, + clipped: false, + visible: true, + mask: None, + }; + let group = LayerSpec::Group { children: vec![shape, posterize], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None }; + let s = Spec { w: 8, h: 6, layers: vec![group] }; + let mut d = doc(s.w as u32, s.h as u32); + d.layers = s.layers.iter().map(build).collect(); + assert_matches_reference(&d); +} + proptest! { #![proptest_config(ProptestConfig { cases: 400, ..ProptestConfig::default() })] From 2ce48d4b6ab7fd8e7c710a7105cda96cee3f9541 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 17:30:24 +0100 Subject: [PATCH 087/113] PR #5250: name the Scatter slider by its caption and find captions after the merge Main's slider rows now name their slider after the caption and link the caption to the value field, so get_by_label("Scatter") found the field instead of the caption. The tests use caption_rect, and scatter_row names its slider like slider_row does, with a test that fails without it. Co-Authored-By: augrclk Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/brush_sections.rs | 24 ++++++++++++------- .../src/panels/brush_sections/tests.rs | 9 +++++-- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/brush_sections.rs b/crates/ui-egui/src/panels/brush_sections.rs index 8affedef37..5a5507db1b 100644 --- a/crates/ui-egui/src/panels/brush_sections.rs +++ b/crates/ui-egui/src/panels/brush_sections.rs @@ -383,15 +383,21 @@ fn scatter_row(ui: &mut egui::Ui, amount: &mut f32, both_axes: &mut bool) { let t = Tokens::get(ui.ctx()); let mut percent = (*amount * 100.0).round(); let mut changed = false; - ui.horizontal(|ui| { - let label = ui.label(RichText::new(tl!("Scatter")).color(t.text_dim)); - widgets::scrub_label_within(ui, &label, f32::INFINITY); - widgets::checkbox(ui, both_axes, tl!("Both Axes")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - changed = widgets::value_field(ui, &mut percent, 0.0..=1000.0, "%", 74.0).changed(); - }); - }); - changed |= widgets::slider(ui, &mut percent, 0.0..=1000.0, None).changed(); + let label = ui + .horizontal(|ui| { + let label = ui.label(RichText::new(tl!("Scatter")).color(t.text_dim)); + widgets::scrub_label_within(ui, &label, f32::INFINITY); + widgets::checkbox(ui, both_axes, tl!("Both Axes")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed = widgets::value_field(ui, &mut percent, 0.0..=1000.0, "%", 74.0).changed(); + }); + label.id + }) + .inner; + // Named by its caption, like every `slider_row` slider. + let slider = widgets::slider(ui, &mut percent, 0.0..=1000.0, None); + slider.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(percent), tl!("Scatter"))); + changed |= slider.labelled_by(label).changed(); if changed { *amount = (percent.round() / 100.0).clamp(0.0, 10.0); } diff --git a/crates/ui-egui/src/panels/brush_sections/tests.rs b/crates/ui-egui/src/panels/brush_sections/tests.rs index aed7d0657a..830708a6db 100644 --- a/crates/ui-egui/src/panels/brush_sections/tests.rs +++ b/crates/ui-egui/src/panels/brush_sections/tests.rs @@ -347,12 +347,17 @@ fn check_scatter_header(section: usize) { let mut h = section_harness(section, b.clone()); crate::PhotocraftApp::setup_context(&h.ctx, kind); h.run_steps(3); - let label = h.get_by_label("Scatter").rect(); + let label = caption_rect(&h, "Scatter"); let axes = h.get_by_label("Both Axes").rect(); let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap().rect(); assert!((label.center().y - axes.center().y).abs() < 2.0, "{kind:?}, section {section}: axes belongs on the Scatter header"); assert!((axes.center().y - field.center().y).abs() < 2.0, "{kind:?}, section {section}: axes and percentage share a row"); assert!(label.right() < axes.left() && axes.right() < field.left(), "{kind:?}, section {section}: label, checkbox, percentage order"); + assert_eq!( + h.query_all_by_role_and_label(Role::Slider, "Scatter").count(), + 1, + "{kind:?}, section {section}: the slider is named by its caption, like other slider rows" + ); assert_eq!(h.state(), &b, "rendering retains fractional scatter and other settings"); } } @@ -396,7 +401,7 @@ fn scatter_header_preserves_values_percentage_limits_and_label_scrubbing() { b.dual_brush.scatter = 2.15; } assert_eq!(h.state(), &b, "percentage edits preserve the other brush block"); - let label = h.get_by_label("Scatter").rect().center(); + let label = caption_rect(&h, "Scatter").center(); drag(&mut h, label, label + vec2(18.0, 0.0)); let amount = if section == 2 { h.state().scattering.scatter.jitter } else { h.state().dual_brush.scatter }; assert!(amount > 2.15, "the label still scrubs the percentage across the checkbox"); From 3d2d1870c9d5441b7f348ebc9b121d78519c0b80 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 7 Nov 2026 09:34:55 -0800 Subject: [PATCH 088/113] Correct Free Transform interior cursor test diagnostic --- crates/ui-egui/src/canvas/transform_controls_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/transform_controls_tests.rs b/crates/ui-egui/src/canvas/transform_controls_tests.rs index 229f0b8965..2bb92e0d8b 100644 --- a/crates/ui-egui/src/canvas/transform_controls_tests.rs +++ b/crates/ui-egui/src/canvas/transform_controls_tests.rs @@ -334,7 +334,7 @@ fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interacti assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}"); assert!(transform_controls_hit(r, p), "same region must start a transform"); } - assert_eq!(transform_controls_cursor(r, r.center()), Some(egui::CursorIcon::Default), "interior stays Move"); + assert_eq!(transform_controls_cursor(r, r.center()), Some(egui::CursorIcon::Default), "interior uses the default arrow"); assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), Some(egui::CursorIcon::None)); // The rotate arrow points into the nearest edge or corner. Handles and the interior have none. let into = |p: Pos2| transform_controls_turn(r, p); From 024c7c0310fd40e71add799e0f5ffd3b6c7e1567 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 18:50:40 +0100 Subject: [PATCH 089/113] Regenerate docs/scorecard.md for #10448's export.lastFolder setting #10448 adds the export.lastFolder preference, so the prefs audit now counts 195 settings instead of 194 and the gate failed on a stale scorecard. Co-Authored-By: qvest-ssels Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 7e92243bf8..4a60cdc4ac 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 195 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 194** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 195** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From ca92d936c00d4724916f4e57ae8937f78aa691d5 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:41:22 +0100 Subject: [PATCH 090/113] PDF: import raster pages through craft-pdf instead of PDFium - craft-pdf (the shared Rust/Hayro reader in craft-libs, rev c5a1cbf) renders each page; no shared library is loaded or shipped, and every desktop platform works. - Raster pages only: editable text/vector import and the pdf_text/pdf_vectors options are removed (they can return later through craft-pdf's interpret device). Page geometry, artboards, page range, budgets, cancellation and warnings are kept; the effective DPI now respects craft-pdf's 8192 px side and 64M px page limits. - Drops pdfium-render, the PDFium download in CI, the build-script copy and the packaging/licence staging; records the Hayro/fonts/CMaps/ICC assets in ATTRIBUTION.md and NOTICE. - \.ai\ files starting with %PDF- now take the PDF importer, matching the comment. - Attribution, architecture and file-format-parity docs updated. --- .github/workflows/ci.yml | 18 - ATTRIBUTION.md | 13 + Cargo.lock | 385 +++++++++---- Cargo.toml | 6 + NOTICE | 11 + apps/photocraft/build.rs | 13 - crates/io/Cargo.toml | 7 +- crates/io/src/lib.rs | 52 +- crates/io/src/pdf_import.rs | 764 ++++++-------------------- crates/io/tests/it/pdf_import.rs | 393 ++++--------- docs/architecture.md | 2 +- docs/file-format-parity.md | 3 +- packaging/windows/install-policy.json | 3 +- packaging/windows/package.ps1 | 75 --- packaging/windows/photocraft.wxs | 7 - 15 files changed, 640 insertions(+), 1112 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4422f41a22..2c3597f5ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -251,24 +251,6 @@ jobs: with: tool: cargo-nextest@0.9.150 - # The PDF import integration test loads PDFium at run time. Provision the pinned build for - # the integration leg and make an unavailable library fail there; local runs still skip. - - name: PDFium for the PDF import test - if: matrix.part == 'integration' - shell: pwsh - run: | - $dir = Join-Path $env:RUNNER_TEMP 'pdfium' - New-Item -ItemType Directory -Force $dir | Out-Null - $tgz = Join-Path $env:RUNNER_TEMP 'pdfium-win-x64.tgz' - Invoke-WebRequest -Uri 'https://github.com/bblanchon/pdfium-binaries/releases/download/chromium/8138/pdfium-win-x64.tgz' -OutFile $tgz - $hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $tgz).Hash.ToLowerInvariant() - if ($hash -ne '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5') { - throw "PDFium archive checksum $hash does not match the pinned chromium/8138 build" - } - tar -xzf $tgz -C $dir - "PDFIUM_DIR=$dir\bin" >> $env:GITHUB_ENV - "PHOTOCRAFT_REQUIRE_PDFIUM=1" >> $env:GITHUB_ENV - # The unit leg runs `--lib --bins` and the integration leg `--test '*'` (every # integration-test target); the feature selection stays the same, so both legs share the # dependency cache. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f11c7f30e0..bac9633320 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -166,3 +166,16 @@ are adapted from Skyfuller1303’s MIT OR Apache-2.0 implementation in `897f20072762fdf0eb688adcdb8d8cda7b38ce66`. Don Omondi’s embedded AI/PDF/EPS extension and current-main integration build on that source. Clipboard and unrelated Shape Tools changes from that branch are not included. + +## Assets bundled by the PDF reader dependency (craft-pdf) + +PhotoCraft imports PDF pages through `craft-pdf`, pinned to the craft-libs revision +`c5a1cbfb5f9049f9270955caffb5bee5997aebf7`. The renderer vendors Hayro and the assets below; +they ship inside the dependency rather than being copied into this repository. PDFium is no +longer used or shipped. + +| Crate / file | Author | Source | Licence | Use | +| --- | --- | --- | --- | --- | +| `hayro-interpret 0.7.0 / assets/Foxit*.pfb` (13 standard-14 font files) | Foxit Software Inc. / PDFium Authors | | BSD-3-Clause | Renders non-embedded standard-14 PDF fonts | +| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | | CC0-1.0 | Default CMYK colour conversion | +| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | | BSD-3-Clause | Character-code mapping for CJK PDFs | diff --git a/Cargo.lock b/Cargo.lock index 049da1acef..5e2a1dfca1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -22,7 +22,7 @@ dependencies = [ "accesskit", "accesskit_consumer", "atspi-common", - "phf", + "phf 0.14.0", "serde", "zvariant", ] @@ -826,6 +826,17 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -874,12 +885,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "byteorder-lite" version = "0.1.0" @@ -1284,26 +1289,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "console_error_panic_hook" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" -dependencies = [ - "cfg-if", - "wasm-bindgen", -] - -[[package]] -name = "console_log" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" -dependencies = [ - "log", - "web-sys", -] - [[package]] name = "const-oid" version = "0.9.6" @@ -1469,6 +1454,18 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pdf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bytemuck", + "hayro", + "hayro-interpret", + "hayro-syntax", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -1498,7 +1495,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -2133,7 +2130,7 @@ dependencies = [ "ecolor", "emath", "epaint_default_fonts", - "font-types", + "font-types 0.12.5", "harfrust", "log", "nohash-hasher", @@ -2141,13 +2138,13 @@ dependencies = [ "profiling", "self_cell", "serde", - "skrifa", + "skrifa 0.44.0", "smallvec", "unicode-bidi", "unicode-general-category", "unicode-properties", "unicode-segmentation", - "vello_cpu", + "vello_cpu 0.2.0", ] [[package]] @@ -2403,6 +2400,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "font-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +dependencies = [ + "bytemuck", +] + [[package]] name = "font-types" version = "0.12.5" @@ -2449,7 +2455,7 @@ dependencies = [ "objc2-core-text", "objc2-foundation 0.3.2", "parlance", - "read-fonts", + "read-fonts 0.41.0", "roxmltree 0.21.1", "smallvec", "windows", @@ -2743,6 +2749,23 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glifo" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "skrifa 0.42.1", + "smallvec", + "vello_common 0.0.9", +] + [[package]] name = "glifo" version = "0.3.0" @@ -2754,9 +2777,9 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "skrifa", + "skrifa 0.44.0", "smallvec", - "vello_common", + "vello_common 0.2.0", ] [[package]] @@ -2905,7 +2928,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] @@ -2938,6 +2961,94 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro" +version = "0.7.1" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bytemuck", + "hayro-interpret", + "image", + "kurbo 0.13.1", + "log", + "pic-scale", + "vello_cpu 0.0.8", +] + +[[package]] +name = "hayro-ccitt" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" + +[[package]] +name = "hayro-cmap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-interpret" +version = "0.7.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-syntax", + "kurbo 0.13.1", + "moxcms", + "phf 0.13.1", + "rustc-hash 2.1.3", + "siphasher", + "skrifa 0.47.0", + "smallvec", + "yoke", +] + +[[package]] +name = "hayro-jbig2" +version = "0.3.0" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "fearless_simd", + "hayro-ccitt", +] + +[[package]] +name = "hayro-jpeg2000" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + +[[package]] +name = "hayro-postscript" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" + +[[package]] +name = "hayro-syntax" +version = "0.7.2" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +dependencies = [ + "flate2", + "hayro-ccitt", + "hayro-jbig2", + "hayro-jpeg2000", + "memchr", + "rustc-hash 2.1.3", + "smallvec", + "stringprep", + "zune-jpeg 0.5.15", +] + [[package]] name = "heck" version = "0.5.0" @@ -5027,7 +5138,7 @@ dependencies = [ "linebender_resource_handle", "parlance", "parley_data", - "skrifa", + "skrifa 0.44.0", ] [[package]] @@ -5057,32 +5168,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" -[[package]] -name = "pdfium-render" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "bytes", - "chrono", - "console_error_panic_hook", - "console_log", - "image", - "itertools 0.15.0", - "js-sys", - "libloading", - "log", - "maybe-owned", - "once_cell", - "utf16string", - "vecmath", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "pem" version = "3.0.6" @@ -5132,17 +5217,37 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", +] + [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", - "phf_shared", + "phf_macros 0.14.0", + "phf_shared 0.14.0", "serde", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_generator" version = "0.14.0" @@ -5150,7 +5255,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -5159,13 +5277,22 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.14.0", + "phf_shared 0.14.0", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.14.0" @@ -5486,12 +5613,12 @@ version = "0.20.1" dependencies = [ "blake3", "craft-docpath", + "craft-pdf", "crc32fast", "flate2", "imagesize", "lopdf", "miniz_oxide 0.9.1", - "pdfium-render", "photocraft-affinity", "photocraft-algo", "photocraft-cms", @@ -5638,7 +5765,7 @@ dependencies = [ "photocraft-psd", "photocraft-raster", "rayon", - "skrifa", + "skrifa 0.44.0", ] [[package]] @@ -5734,6 +5861,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "pic-scale" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -5802,12 +5939,6 @@ dependencies = [ "system-deps", ] -[[package]] -name = "piston-float" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" - [[package]] name = "pkg-config" version = "0.3.34" @@ -6365,6 +6496,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "read-fonts" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +dependencies = [ + "bytemuck", + "font-types 0.11.3", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -6372,7 +6513,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ "bytemuck", - "font-types", + "font-types 0.12.5", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types 0.12.5", "once_cell", ] @@ -7319,6 +7471,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "skrifa" +version = "0.42.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +dependencies = [ + "bytemuck", + "read-fonts 0.39.2", +] + [[package]] name = "skrifa" version = "0.44.0" @@ -7326,7 +7488,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", ] [[package]] @@ -8290,15 +8462,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" -[[package]] -name = "utf16string" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" -dependencies = [ - "byteorder", -] - [[package]] name = "utf8-zero" version = "0.8.1" @@ -8341,12 +8504,37 @@ dependencies = [ ] [[package]] -name = "vecmath" -version = "1.0.0" +name = "vello_common" +version = "0.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee" dependencies = [ - "piston-float", + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_common" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png 0.18.1", + "smallvec", + "thiserror 2.0.21", ] [[package]] @@ -8364,6 +8552,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "vello_cpu" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" +dependencies = [ + "bytemuck", + "glifo 0.1.1", + "hashbrown 0.17.1", + "png 0.18.1", + "vello_common 0.0.8", +] + [[package]] name = "vello_cpu" version = "0.2.0" @@ -8371,9 +8572,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" dependencies = [ "bytemuck", - "glifo", + "glifo 0.3.0", "hashbrown 0.17.1", - "vello_common", + "vello_common 0.2.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e01bcf175a..f5fafa868d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ photocraft-ipp = { path = "crates/ipp" } # external craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" } @@ -203,3 +204,8 @@ eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968157 egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). +hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } diff --git a/NOTICE b/NOTICE index 9ab6b0a1cf..826dea7490 100644 --- a/NOTICE +++ b/NOTICE @@ -70,3 +70,14 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Optional PDF reader (craft-pdf) + +PhotoCraft imports PDF pages through craft-pdf (https://github.com/storytold/craft-libs, +MIT OR Apache-2.0), pinned to revision c5a1cbfb5f9049f9270955caffb5bee5997aebf7. It vendors +Hayro 0.7.1, hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0 and +hayro-cmap 0.1.0 (https://github.com/LaurenzV/hayro, MIT OR Apache-2.0). The reader bundles +the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Compact ICC +profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs +ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or +shipped. diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index e750904018..48abc9f1a5 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -11,19 +11,6 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - // PDF import loads PDFium at runtime. When the build provides the shared library - // (`PDFIUM_DLL`, set by the release packaging step), copy it beside the executable so the - // installer's pdfium.dll and the running app agree. - println!("cargo:rerun-if-env-changed=PDFIUM_DLL"); - if let (Some(dll), Ok(out)) = (std::env::var_os("PDFIUM_DLL"), std::env::var("OUT_DIR")) { - let dll = std::path::PathBuf::from(dll); - if let Some(profile_dir) = std::path::Path::new(&out).ancestors().nth(3) { - let dest = profile_dir.join(dll.file_name().unwrap_or_default()); - if let Err(e) = std::fs::copy(&dll, &dest) { - println!("cargo:warning=could not copy PDFium to {}: {e}", dest.display()); - } - } - } // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index dd5a232f32..36975e57eb 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -51,11 +51,8 @@ imagesize = "0.13" resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] } # The SVG fallback font search keeps each font file's character map (already in the tree through usvg). ttf-parser = { version = "0.25", default-features = false } -# PDF import (pdf_import.rs): PDFium renders the pages; the direct surfaces build the document. -# Pinned exactly, like the WinTab wrappers in photocraft-tablet: PDFium is FFI-loaded at run time -# and the DLL release is pinned separately in packaging/windows/package.ps1, so a lockfile refresh -# must not move the wrapper under it. Bump deliberately and re-check both. -pdfium-render = "=0.9.5" +# PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships. +craft-pdf = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 54a4d1577e..7519449224 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -556,9 +556,9 @@ pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { if is_psd_input(name, bytes) { return ImportPreflight::Psd; } - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + // PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this + // importer too; a recognized raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) { return ImportPreflight::Unbounded; } if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } @@ -612,10 +612,6 @@ pub struct ImportOptions { pub pdf_dpi: f32, /// The 1-based, inclusive page range to import; `None` imports every page (up to the cap). pub pdf_pages: Option<(u32, u32)>, - /// Import PDF text objects as editable text layers (default on). - pub pdf_text: bool, - /// Import PDF vector paths as editable shape layers (default on). - pub pdf_vectors: bool, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -632,8 +628,6 @@ impl Default for ImportOptions { flat_max_pixel_bytes: 0, pdf_dpi: 300.0, pdf_pages: None, - pdf_text: true, - pdf_vectors: true, psd_high_memory_approved: false, psd_approved_estimate: None, } @@ -999,9 +993,9 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o if is_svg_input(name, bytes) { return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth); } - // PDF (PDFium, native only). `.ai` files are PDFs but keep their existing path; a recognized - // raster signature wins over a misleading `.pdf` suffix. - if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && !has_extension(name, "ai") && photocraft_codecs::detect(bytes).is_none()) { + // PDF (craft-pdf, pure Rust). `.ai` files that start with `%PDF-` are PDFs and take this + // importer too; a recognized raster signature wins over a misleading `.pdf` suffix. + if pdf_import::is_pdf(bytes) || (has_extension(name, "pdf") && photocraft_codecs::detect(bytes).is_none()) { return pdf_import::import(name, bytes, opts, ctl); } match route(name, bytes) { @@ -1628,4 +1622,38 @@ mod tests { assert!(is_svg_input("drawing.svg", b"")); assert_eq!(crate::route("drawing.svg", pdf), crate::Route::Flat); } + + /// `.ai` files that start with `%PDF-` are PDFs: both preflight and dispatch send them to the + /// PDF importer rather than the flat decoder. + #[test] + fn an_ai_with_pdf_content_takes_the_pdf_importer() { + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let content = b"0 0 1 rg 10 10 20 20 re f"; + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(100.0), Object::Real(100.0)]), + "Contents" => content_id, + "Resources" => dictionary! {}, + }); + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(vec![Object::Reference(page_id)]), + "Count" => 1, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the .ai fixture"); + assert!(pdf_import::is_pdf(&bytes)); + assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded); + let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer"); + assert_eq!(result.document.artboards().len(), 1); + } } diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 7cb1da50c2..0fcc540749 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -1,33 +1,28 @@ -//! PDF import: PDFium renders the selected pages and each page becomes an artboard. +//! PDF import: craft-pdf (a Rust PDF reader and renderer built on Hayro) rasterizes the +//! selected pages, and each page becomes one artboard. //! -//! The document resolution is chosen so the page's physical size is preserved even when the -//! raster is capped: pixels ÷ resolution × 72 pt is the PDF page's size. Pages are laid out side -//! by side; page count, per-page pixels, union pixels and the aggregate pixel budget are bounded. +//! Raster pages only: editable text and vector import would need craft-pdf's `interpret` +//! device and is not part of this importer. The renderer's hard output bounds (8192 px per +//! side and 64M px per page) and a document-wide strip budget are respected by lowering the +//! effective DPI, so each page keeps its physical size: pixels / resolution * 72 pt. //! -//! Text and vector page objects can be imported as editable layers (`ImportOptions::pdf_text` / -//! `pdf_vectors`); their page-space points are mapped to document pixels through the effective DPI. -//! -//! # Known limits -//! -//! - pdfium-render 0.9.5 exposes a path's fill/stroke *presence* but not its paint colour, stroke -//! width or dash pattern, so imported paths are painted black (1 pt centre stroke when stroked). -//! - A text object exposes no fill colour: the colour is sampled from the rendered page's glyph -//! ink, and the font is matched by family/name rather than embedded or loaded from the PDF. -//! - PDFium is provisioned by `packaging/windows/package.ps1` (pinned release, verified DLL); the -//! shared craft-common-actions release workflow does not stage it. +//! The renderer is pure Rust and runs on every desktop platform: no shared library is loaded +//! or shipped, and a malformed file is reported as an error rather than taking the process down. use crate::{ImportOptions, ImportResult, IoError}; +use craft_pdf::interpret::InterpreterSettings; +use craft_pdf::raster::{self, RenderCache}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{Artboard, Color, Document, Fill, Group, Knot, Layer, LayerContent, Path, PathOp, ShapeLayer, ShapeStroke, Subpath, TextLayer}; -use photocraft_geom::{Affine, Point, Rect, Size}; +use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +use photocraft_geom::{Rect, Size}; use photocraft_raster::{Interrupt, Surface}; -/// `%PDF-` magic. `.ai` files are PDFs too, but the dispatch keeps them out of this importer. +/// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer. pub fn is_pdf(bytes: &[u8]) -> bool { bytes.starts_with(b"%PDF-") } -/// Native PDF import is not available in the web build. +/// PDF import is not available in the web build. #[cfg(target_arch = "wasm32")] pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrupt) -> Result { Err(IoError::Unsupported("PDF import needs the desktop build".into())) @@ -36,23 +31,23 @@ pub fn import(_name: &str, _bytes: &[u8], _opts: &ImportOptions, _ctl: &Interrup /// Renders the selected PDF pages and opens each as one artboard. #[cfg(not(target_arch = "wasm32"))] pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) -> Result { - use pdfium_render::prelude::*; - /// The most pages one import renders. const MAX_PAGES: usize = 16; /// Gap between the artboards, in document pixels. const GAP: u32 = 80; - /// Per-page and per-artboard-strip pixel budgets; a poster at 300 dpi is far below these. - const MAX_PAGE_PIXELS: f64 = 100_000_000.0; + /// The document-wide raster budget across every imported page, in pixels. const MAX_UNION_PIXELS: u64 = 200_000_000; /// The default pixel-memory budget when the caller sets none: a zero /// [`ImportOptions::flat_max_pixel_bytes`] still bounds the import. const DEFAULT_MAX_PIXEL_BYTES: u64 = 2 << 30; + ctl.check().map_err(|_| IoError::Cancelled)?; let requested = if opts.pdf_dpi.is_finite() && opts.pdf_dpi > 0.0 { f64::from(opts.pdf_dpi) } else { 300.0 }; - let pdfium = bind()?; - let document = pdfium.load_pdf_from_byte_slice(bytes, None).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let total = document.pages().len().max(0) as usize; + let pdf = craft_pdf::open_slice_with_options(bytes, None, &craft_pdf::OpenOptions::default()).map_err(open_error)?; + let total = pdf.pages().len(); + if total == 0 { + return Err(IoError::Unsupported("PDF has no pages".into())); + } let (first, last) = match opts.pdf_pages { Some((a, b)) => { let a = a.max(1); @@ -64,46 +59,45 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - } None => (1, total), }; - if total == 0 || first > total { - return Err(IoError::Unsupported("PDF has no pages in the requested range".into())); - } let page_count = last - first + 1; let count = page_count.min(MAX_PAGES); - // The page geometry first: the effective DPI must fit the budgets, capping the raster must - // not change the page's physical size, and editable objects are mapped through the same page - // box and rotation the raster uses. - let mut geoms = Vec::with_capacity(count); + + // Page sizes in points first: the effective DPI must fit the renderer's bounds without + // changing any page's physical size. + let mut sizes = Vec::with_capacity(count); for index in 0..count { + let page = &pdf.pages()[first - 1 + index]; + let (width, height) = page.render_dimensions(); + if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 { + return Err(IoError::Unsupported(format!("PDF page {} has no area", first + index))); + } + sizes.push((f64::from(width), f64::from(height))); ctl.check().map_err(|_| IoError::Cancelled)?; - let page_index = first - 1 + index; - let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - geoms.push(page_geometry(&page, page_index + 1)?); } - let sizes: Vec<(f64, f64)> = geoms.iter().map(|g| (g.width_pt, g.height_pt)).collect(); - let dpi = effective_dpi(requested, &sizes, GAP, MAX_PAGE_PIXELS, MAX_UNION_PIXELS); - let doc_width = sizes.iter().map(|(w, _)| (w * dpi / 72.0).round() as u64).sum::() + u64::from(GAP) * (count as u64 - 1); - let doc_height = sizes.iter().map(|(_, h)| (h * dpi / 72.0).round() as u64).max().unwrap_or(1); + let dpi = effective_dpi(requested, &sizes, u64::from(raster::MAX_SIDE), raster::MAX_PIXELS, MAX_UNION_PIXELS); + + let mut doc_width: u64 = 0; + let mut doc_height: u64 = 0; + let mut retained: u64 = 0; + for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() { + let width = page_pixels(width_pt, dpi); + let height = page_pixels(height_pt, dpi); + doc_width = doc_width.saturating_add(u64::from(width)).saturating_add(if index + 1 < count { u64::from(GAP) } else { 0 }); + doc_height = doc_height.max(u64::from(height)); + let tiles_x = (u64::from(width)).div_ceil(256); + let tiles_y = (u64::from(height)).div_ceil(256); + retained = retained.saturating_add(tiles_x.saturating_mul(tiles_y).saturating_mul(256 * 256 * 4)); + } if doc_width == 0 || doc_height == 0 { return Err(IoError::Unsupported("PDF pages have no area".into())); } - // The aggregate budget: the document keeps every page's raster tiles, while one page at a - // time is converted through the PDFium bitmap, its RGBA copy and the f32 buffer. - let page_px = |w: f64, h: f64| (w * dpi / 72.0).round().max(1.0) * (h * dpi / 72.0).round().max(1.0); - let max_page_pixels = sizes.iter().map(|&(w, h)| page_px(w, h)).fold(0.0_f64, f64::max); - // Retained backing: a page occupies whole 256 px tiles, including the ones its document X - // offset steps into. A 1 x 10,000 px page is 40 tiles (10 MiB), not 10,000 pixels. - const TILE: u64 = 256; - let mut retained: u64 = 0; - let mut page_x: u64 = 0; - for &(w, h) in &sizes { - let px = (w * dpi / 72.0).round().max(1.0) as u64; - let py = (h * dpi / 72.0).round().max(1.0) as u64; - let tiles_x = (page_x + px).div_ceil(TILE) - page_x / TILE; - retained = retained.saturating_add(tiles_x.saturating_mul(py.div_ceil(TILE)).saturating_mul(TILE * TILE * 4)); - page_x += px + u64::from(GAP); + if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) { + return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into())); } - // Plus 24 bytes/px (bitmap, RGBA copy, f32 conversion buffer) for the page being converted. - let estimate = retained.saturating_add((max_page_pixels * 24.0) as u64); + // Retained tiles plus the converting page's peak: craft-pdf's RGBA8 raster (4 B/px) and the + // f32 document buffer (16 B/px). + let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0); + let estimate = retained.saturating_add(max_page.saturating_mul(20)); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -112,576 +106,134 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - budget >> 20 ))); } - let mut object_budget = ObjectBudget::default(); - let mut object_warnings: Vec = Vec::new(); - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); - doc.resolution_dpi = dpi as f32; - let mut x = 0u32; - for (index, geometry) in geoms.iter().enumerate() { - let (w_pt, h_pt) = (geometry.width_pt, geometry.height_pt); - ctl.check().map_err(|_| IoError::Cancelled)?; - let page_index = first - 1 + index; - let target_width = (w_pt * dpi / 72.0).round().max(1.0) as i32; - let target_height = (h_pt * dpi / 72.0).round().max(1.0) as i32; - // A one-pixel-wide page would otherwise produce an arbitrarily tall bitmap before the - // union check runs; reject the final dimensions up front. - if f64::from(target_width) * f64::from(target_height) > MAX_PAGE_PIXELS { - return Err(IoError::Unsupported(format!( - "PDF page {} is too large at {dpi} dpi ({} x {} px); lower the import DPI", - page_index + 1, - target_width, - target_height - ))); - } - let page = document.pages().get(page_index as i32).map_err(|e| IoError::Unsupported(format!("PDF: {e}")))?; - let bitmap = - page.render_with_config(&PdfRenderConfig::new().set_target_width(target_width)).map_err(|e| IoError::Unsupported(format!("PDF render: {e}")))?; - let (width, height) = (bitmap.width().max(0) as u32, bitmap.height().max(0) as u32); - // The rounded target width can render a taller bitmap than the pre-check predicted. - if f64::from(width) * f64::from(height) > MAX_PAGE_PIXELS { - return Err(IoError::Unsupported(format!( - "PDF page {} rendered larger than the {MAX_PAGE_PIXELS} px budget ({} x {}); lower the import DPI", - page_index + 1, - width, - height - ))); - } - // The page's pixels go straight into the document-wide layer surface: no full-strip - // canvas and no PNG round-trip, so the peak is the page bitmap plus its tiles. - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); - let rgba = bitmap.as_rgba_bytes(); - let mut data = Vec::new(); - if data.try_reserve_exact(rgba.len()).is_err() { - return Err(IoError::Unsupported(format!("PDF page {} needs more memory than is available", page_index + 1))); - } - for chunk in rgba.as_chunks::<4>().0 { - for &v in &chunk[..3] { - data.push(f32::from(v) / 255.0); - } - data.push(f32::from(chunk[3]) / 255.0); - } - surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); - let layer = Layer::new(format!("Page {}", page_index + 1), LayerContent::Raster(surface)); - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); - let mut children = vec![layer]; - if opts.pdf_text || opts.pdf_vectors { - let frame = PageFrame { geometry: *geometry, dpi, x, rgba: &rgba, width, height }; - let (layers, truncated) = object_layers(&page, opts, &frame, ctl, &mut object_budget)?; - children.extend(layers); - if truncated { - object_warnings.push(format!("PDF page {}: editable text/vector layers omitted at the import limit (the raster page is kept)", page_index + 1)); - } - } - let group = Group { children, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; - doc.layers.push(Layer::new(format!("Page {}", page_index + 1), LayerContent::Group(group))); - x += width + GAP; - ctl.progress((index + 1) as f32 / count as f32); - } - let mut warnings = object_warnings; + + let mut warnings = Vec::new(); if first > 1 || last < total || count < page_count { let shown_last = first + count - 1; let reason = if count < page_count { " (the page limit is 16)" } else { "" }; warnings.push(format!("PDF has {total} pages; imported pages {first}-{shown_last}{reason}")); } + if dpi + 0.5 < requested { + warnings.push(format!("PDF was rendered at {:.0} dpi to fit the import limits", dpi.max(1.0))); + } + + let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); + doc.resolution_dpi = dpi as f32; + let mut x: u32 = 0; + for index in 0..count { + ctl.check().map_err(|_| IoError::Cancelled)?; + let page_number = first + index; + let page = &pdf.pages()[page_number - 1]; + let (width_pt, height_pt) = sizes[index]; + let width = page_pixels(width_pt, dpi); + let height = page_pixels(height_pt, dpi); + // The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if + // rounding on an edge moves one pixel past them. + if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS { + return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI"))); + } + let cache = RenderCache::new(); + let settings = InterpreterSettings::default(); + let options = raster::Options { + scale: [(dpi / 72.0) as f32; 2], + size: Some([width, height]), + offset: [0.0, 0.0], + // PDF pages composite onto white, as every PDF viewer and the previous importer did. + background: [255, 255, 255, 255], + color_replacement: None, + }; + let rendered = raster::render(page, &cache, &settings, &options).map_err(|error| render_error(page_number, dpi, error))?; + if rendered.diagnostics.image_decode_failed { + warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing")); + } + if rendered.diagnostics.content_truncated { + warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)")); + } + ctl.check().map_err(|_| IoError::Cancelled)?; + + let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + let bytes = rendered.bytes(); + let mut data = Vec::new(); + if data.try_reserve_exact(bytes.len()).is_err() { + return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available"))); + } + for chunk in bytes.as_chunks::<4>().0 { + for &value in &chunk[..3] { + data.push(f32::from(value) / 255.0); + } + data.push(f32::from(chunk[3]) / 255.0); + } + surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); + let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); + let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface)); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group))); + x = x.saturating_add(width).saturating_add(GAP); + ctl.progress((index + 1) as f32 / count as f32); + } + Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } -/// Document-wide bound on editable objects. Text layers and path knots are allocated outside the -/// pixel-memory estimate, so a pathological PDF could otherwise exhaust memory. -const MAX_OBJECT_LAYERS: usize = 20_000; -const MAX_PATH_KNOTS: usize = 1_000_000; - -/// Tracks the editable objects created so far, document-wide. -#[derive(Default)] -struct ObjectBudget { - layers: usize, - knots: usize, -} - -impl ObjectBudget { - /// Claims one editable layer; false once the document-wide limit is reached. - fn claim_layer(&mut self) -> bool { - if self.layers >= MAX_OBJECT_LAYERS { - false - } else { - self.layers += 1; - true - } - } - - /// Claims `count` path knots; false if that would pass the document-wide limit. - fn claim_knots(&mut self, count: usize) -> bool { - if self.knots.saturating_add(count) > MAX_PATH_KNOTS { - false - } else { - self.knots += count; - true - } - } -} -/// A page's visible area and rotation, in PDF points. -#[derive(Clone, Copy)] -struct PageGeometry { - /// Displayed size (rotation applied): the size the raster is rendered into. - width_pt: f64, - height_pt: f64, - /// The crop box origin in unrotated PDF user space. - origin_x: f64, - origin_y: f64, - /// The crop box size in unrotated PDF user space. - crop_w: f64, - crop_h: f64, - /// Clockwise rotation the renderer applies: 0, 90, 180 or 270. - rotation: u16, -} - -/// The page's visible box and rotation. PDF page objects stay in unrotated user space, while the -/// raster is rendered through the crop box and the page's `/Rotate`, so editable layers must use -/// the same transform. +/// One page's raster width or height in pixels at `dpi`, at least one. #[cfg(not(target_arch = "wasm32"))] -fn page_geometry(page: &pdfium_render::prelude::PdfPage, page_number: usize) -> Result { - let width_pt = f64::from(page.width().value); - let height_pt = f64::from(page.height().value); - if width_pt <= 0.0 || height_pt <= 0.0 { - return Err(IoError::Unsupported(format!("PDF page {page_number} has no area"))); - } - let rotation = page.rotation().map(|r| r.as_degrees() as u16).unwrap_or(0); - // The page's effective box, as PDFium renders it: the bounding box (media box clipped to the - // crop box), not the raw crop box, which may extend past the media box. - let (origin_x, origin_y, crop_w, crop_h) = match page.boundaries().bounding().or_else(|_| page.boundaries().crop()).or_else(|_| page.boundaries().media()) { - Ok(boundary) => { - let r = boundary.bounds; - (f64::from(r.left().value), f64::from(r.bottom().value), f64::from(r.right().value - r.left().value), f64::from(r.top().value - r.bottom().value)) - } - Err(_) => (0.0, 0.0, width_pt, height_pt), - }; - // A malformed box falls back to the displayed size; 90 and 270 swap the axes. - let (crop_w, crop_h) = if crop_w > 0.0 && crop_h > 0.0 { - (crop_w, crop_h) - } else if rotation == 90 || rotation == 270 { - (height_pt, width_pt) - } else { - (width_pt, height_pt) - }; - Ok(PageGeometry { width_pt, height_pt, origin_x, origin_y, crop_w, crop_h, rotation }) +fn page_pixels(points: f64, dpi: f64) -> u32 { + (points * dpi / 72.0).round().max(1.0) as u32 } -/// One rendered page's frame: its geometry, DPI, document x, and the RGBA pixels. -struct PageFrame<'a> { - geometry: PageGeometry, - dpi: f64, - x: u32, - rgba: &'a [u8], - width: u32, - height: u32, -} - -impl PageFrame<'_> { - /// Maps a point in PDF page space to the page's own pixels: crop box, rotation and scale. - fn to_page_px(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let g = &self.geometry; - let u = f64::from(x_pt) - g.origin_x; - let v = f64::from(y_pt) - g.origin_y; - let (dx, dy) = match g.rotation { - 90 => (v, u), - 180 => (g.crop_w - u, v), - 270 => (g.crop_h - v, g.crop_w - u), - _ => (u, g.crop_h - v), - }; - let scale = self.dpi / 72.0; - (dx * scale, dy * scale) - } - - /// Maps a point in PDF page space to document pixels: the page's own pixels plus its X offset. - fn to_doc(&self, x_pt: f32, y_pt: f32) -> (f64, f64) { - let (px, py) = self.to_page_px(x_pt, y_pt); - ((px + f64::from(self.x)).round(), py.round()) - } - - /// The text layer's transform at document pixel (`x`, `y`): the page rotation turns the text - /// layout too, so rotated pages get rotated editable text rather than upright text at a - /// rotated position. - fn text_transform(&self, x: f64, y: f64) -> Affine { - let (a, b, c, d) = match self.geometry.rotation { - 90 => (0.0, 1.0, -1.0, 0.0), - 180 => (-1.0, 0.0, 0.0, -1.0), - 270 => (0.0, -1.0, 1.0, 0.0), - _ => (1.0, 0.0, 0.0, 1.0), - }; - Affine { m: [a, b, c, d, x, y] } - } - - /// The rendered page's colour at local pixel (`x`, `y`), or black outside it. - fn color_at(&self, x: u32, y: u32) -> Color { - let i = (y as usize * self.width as usize + x as usize) * 4; - if i + 3 < self.rgba.len() && self.rgba[i + 3] > 0 { - Color::rgb(f32::from(self.rgba[i]) / 255.0, f32::from(self.rgba[i + 1]) / 255.0, f32::from(self.rgba[i + 2]) / 255.0) - } else { - Color::BLACK - } - } - - /// The ink colour of the text in `bounds` (page points). - /// - /// The box holds both glyphs and the page behind them, so sampling one corner usually finds - /// background or an antialiased edge. Take the pixel farthest from the box's most common - /// colour instead: for dark text on a light page that is a glyph core, and for light text on a - /// dark page it is the glyph rather than the background. - fn text_color(&self, left: f32, top: f32, right: f32, bottom: f32) -> Color { - // The box's four corners through the same rotation-aware mapping as the glyphs. - let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for (x, y) in [(left, bottom), (left, top), (right, top), (right, bottom)] { - let (px, py) = self.to_page_px(x, y); - x0 = x0.min(px); - x1 = x1.max(px); - y0 = y0.min(py); - y1 = y1.max(py); - } - let x0 = x0.floor().max(0.0) as u32; - let x1 = x1.ceil().clamp(0.0, f64::from(self.width)) as u32; - let y0 = y0.floor().max(0.0) as u32; - let y1 = y1.ceil().clamp(0.0, f64::from(self.height)) as u32; - if x1 <= x0 || y1 <= y0 { - return Color::BLACK; - } - // At most 4096 samples, so a page-sized text box stays cheap. - let step = ((f64::from(x1 - x0) * f64::from(y1 - y0) / 4096.0).sqrt().ceil() as u32).max(1); - let mut samples: Vec<[f32; 3]> = Vec::new(); - let mut buckets: std::collections::HashMap = std::collections::HashMap::new(); - let mut y = y0; - 'rows: while y < y1 { - let mut x = x0; - while x < x1 { - if samples.len() >= 4096 { - break 'rows; - } - let c = self.color_at(x, y); - let rgb = [c.c[0], c.c[1], c.c[2]]; - let key = (rgb[0] * 31.0) as u32 * 1024 + (rgb[1] * 31.0) as u32 * 32 + (rgb[2] * 31.0) as u32; - let entry = buckets.entry(key).or_insert((0, [0.0; 3])); - entry.0 += 1; - for (sum, v) in entry.1.iter_mut().zip(rgb) { - *sum += v; - } - samples.push(rgb); - x += step; - } - y += step; - } - let Some((_, (count, sum))) = buckets.iter().max_by_key(|(_, (count, _))| *count) else { return Color::BLACK }; - let mode = [sum[0] / *count as f32, sum[1] / *count as f32, sum[2] / *count as f32]; - let mut best = mode; - let mut best_distance = -1.0f32; - for rgb in samples { - let distance = (rgb[0] - mode[0]).powi(2) + (rgb[1] - mode[1]).powi(2) + (rgb[2] - mode[2]).powi(2); - if distance > best_distance { - best_distance = distance; - best = rgb; - } - } - Color::rgb(best[0], best[1], best[2]) - } -} - -/// Editable text and shape layers for one rendered page, in document pixels. +/// The highest DPI not above `requested` that keeps every page inside the renderer's side and +/// pixel bounds and the whole strip inside `max_union_pixels`. Rendering at that DPI keeps each +/// page's physical size unchanged; unreachable bounds report 1 DPI and the render call then fails +/// with a clear message. #[cfg(not(target_arch = "wasm32"))] -fn object_layers( - page: &pdfium_render::prelude::PdfPage, - opts: &ImportOptions, - frame: &PageFrame, - ctl: &Interrupt, - budget: &mut ObjectBudget, -) -> Result<(Vec, bool), IoError> { - use pdfium_render::prelude::*; - - let objects = page.objects(); - let mut layers = Vec::new(); - let mut truncated = false; - 'objects: for object in objects.iter() { - if budget.layers >= MAX_OBJECT_LAYERS { - truncated = true; - break; - } - if ctl.check().is_err() { - return Err(IoError::Cancelled); - } - match object { - PdfPageObject::Text(text) if opts.pdf_text => { - let content = text.text(); - if content.trim().is_empty() { - continue; - } - let Ok(bounds) = text.bounds() else { continue }; - let (x_px, y_px) = frame.to_doc(bounds.left().value, bounds.top().value); - // The text layer's size is in points; the transform is in document pixels. - // The text object does not expose its fill colour; sample the glyph ink from the - // page. The font is matched by family/name, not embedded: a document font that is - // not installed renders with the closest family the text engine has. - let color = frame.text_color(bounds.left().value, bounds.top().value, bounds.right().value, bounds.bottom().value); - let size_pt = f64::from(text.scaled_font_size().value).max(1.0); - let font = text.font(); - let family = if font.family().is_empty() { font.name() } else { font.family() }; - let mut layer = Layer::new( - "Text", - LayerContent::Text(TextLayer { - text: content, - font_family: family, - size_pt: size_pt as f32, - color, - transform: frame.text_transform(x_px, y_px), - ..Default::default() - }), - ); - if !text.is_visible() { - layer.visible = false; - } - if !budget.claim_layer() { - truncated = true; - break 'objects; - } - layers.push(layer); +fn effective_dpi(requested: f64, sizes: &[(f64, f64)], max_side: u64, max_page_pixels: u64, max_union_pixels: u64) -> f64 { + let mut dpi = requested.clamp(1.0, 2400.0); + loop { + let mut union = 0u64; + let mut fits = true; + for &(width_pt, height_pt) in sizes { + let width = u64::from(page_pixels(width_pt, dpi)); + let height = u64::from(page_pixels(height_pt, dpi)); + if width > max_side || height > max_side || width.saturating_mul(height) > max_page_pixels { + fits = false; + break; } - PdfPageObject::Path(path) if opts.pdf_vectors => { - // PDFium reports the segments in object space; the object's matrix places them on - // the page. Without it, scaled or rotated paths land in the wrong place. - let matrix = path.matrix().unwrap_or(PdfMatrix::IDENTITY); - // The fill and stroke modes are exposed; the colours, stroke width and dash - // pattern are not, so both paints are black and a stroke is 1 pt wide. - let filled = !matches!(path.fill_mode(), Ok(PdfPathFillMode::None)); - let stroked = path.is_stroked().unwrap_or(false); - if !filled && !stroked { - continue; - } - let mut subpaths: Vec = Vec::new(); - let mut knots: Vec = Vec::new(); - let mut closed = false; - let mut bezier: Vec<(f64, f64)> = Vec::new(); - for segment in path.segments().transform(matrix).iter() { - let point = || frame.to_doc(segment.x().value, segment.y().value); - match segment.segment_type() { - PdfPathSegmentType::MoveTo => { - if !knots.is_empty() { - subpaths.push(Subpath { closed, knots: std::mem::take(&mut knots), op: PathOp::Combine }); - closed = false; - } - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - let (px, py) = point(); - knots.push(Knot::corner(px, py)); - } - PdfPathSegmentType::LineTo => { - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - let (px, py) = point(); - knots.push(Knot::corner(px, py)); - } - PdfPathSegmentType::BezierTo => { - // PDF draws a cubic Bézier as three consecutive BezierTo points: the - // two control points, then the end point. - bezier.push(point()); - if bezier.len() == 3 { - let ((c1x, c1y), (c2x, c2y), (ex, ey)) = (bezier[0], bezier[1], bezier[2]); - if let Some(prev) = knots.last_mut() { - prev.out_ctrl = Point::new(c1x, c1y); - } - if !budget.claim_knots(1) { - truncated = true; - break 'objects; - } - knots.push(Knot::smooth(Point::new(ex, ey), Point::new(c2x, c2y), Point::new(ex, ey))); - bezier.clear(); - } - } - PdfPathSegmentType::Unknown => {} - } - // A closing segment can also be the endpoint that closes a Bézier; process it - // above before marking the subpath closed so its control points are consumed. - if segment.is_close() { - closed = true; - } - } - if !knots.is_empty() { - subpaths.push(Subpath { closed, knots, op: PathOp::Combine }); - } - if subpaths.is_empty() { - continue; - } - let stroke = stroked.then(|| ShapeStroke { paint: Fill::Solid(Color::BLACK), width: 1.0, ..Default::default() }); - if !budget.claim_layer() { - truncated = true; - break 'objects; - } - layers.push(Layer::new( - "Path", - LayerContent::Shape(ShapeLayer { - path: Path::new(subpaths), - fill: filled.then_some(Fill::Solid(Color::BLACK)), - stroke, - ..Default::default() - }), - )); - } - _ => {} + union = union.saturating_add(width.saturating_mul(height)); } + if fits && union <= max_union_pixels { + return dpi; + } + if dpi <= 1.0 { + return 1.0; + } + // The strip's gaps contribute a constant width, so a geometric step converges without + // needing a closed form per page. + dpi = (dpi * 0.9).max(1.0); } - Ok((layers, truncated)) } -/// The highest DPI not above `requested` that keeps every page and the artboard strip within -/// their pixel budgets. Rendering at that DPI keeps each page's physical size unchanged. +/// Maps a craft-pdf open failure to the importer's error. #[cfg(not(target_arch = "wasm32"))] -fn effective_dpi(requested: f64, sizes: &[(f64, f64)], gap: u32, max_page: f64, max_union: u64) -> f64 { - let mut dpi = requested; - for (w, h) in sizes { - dpi = dpi.min(72.0 * (max_page / (w * h)).sqrt()); +fn open_error(error: craft_pdf::OpenError) -> IoError { + use craft_pdf::OpenError; + match error { + OpenError::InputLimit { limit } => IoError::Unsupported(format!("PDF is larger than the {limit}-byte input limit")), + OpenError::Allocation => IoError::Unsupported("PDF needs more memory than is available".into()), + OpenError::BackendPanic => IoError::Unsupported("PDF reader failed on this file; it may be damaged".into()), + OpenError::Load(error) => IoError::Unsupported(format!("PDF: {error:?}")), } - let n = sizes.len() as f64; - let sum_w: f64 = sizes.iter().map(|(w, _)| w).sum(); - let max_h = sizes.iter().map(|(_, h)| h).fold(0.0_f64, |a, &h| a.max(h)); - // (sum_w * k + gaps) * (max_h * k) <= max_union, where k = dpi / 72: solve a k² + b k - c = 0. - let gaps = f64::from(gap) * (n - 1.0); - let a = sum_w * max_h; - let b = gaps * max_h; - let k = if a > 0.0 { (-b + (b * b + 4.0 * a * max_union as f64).sqrt()) / (2.0 * a) } else { f64::INFINITY }; - dpi.min(72.0 * k).max(1.0) } -/// Loads the PDFium shared library from the executable's folder (`PDFIUM_DIR` overrides it). -/// -/// pdfium-render keeps the bindings in a process-wide static: the first import initializes them -/// and later `bind_to_library` calls fail with `PdfiumLibraryBindingsAlreadyInitialized`. Remember -/// the outcome and reuse the initialized bindings, so opening a second PDF in one session works. +/// Maps a craft-pdf render failure to the importer's error. #[cfg(not(target_arch = "wasm32"))] -fn bind() -> Result { - use pdfium_render::prelude::Pdfium; - - static INIT: std::sync::OnceLock> = std::sync::OnceLock::new(); - let init = INIT.get_or_init(|| { - let dir = std::env::var_os("PDFIUM_DIR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| std::env::current_exe().ok().and_then(|exe| exe.parent().map(std::path::Path::to_path_buf)).unwrap_or_default()); - let library = Pdfium::pdfium_platform_library_name_at_path(&dir); - let platform = Pdfium::pdfium_platform_library_name().to_string_lossy().into_owned(); - match Pdfium::bind_to_library(&library) { - Ok(bindings) => { - // Initializes the library inside pdfium-render's process-wide bindings. - drop(Pdfium::new(bindings)); - Ok(()) - } - Err(e) => Err(format!( - "PDF import: cannot load PDFium from {} ({e}); put {platform} next to the executable or set PDFIUM_DIR, then restart the application", - library.display() - )), - } - }); - match init { - // The bindings are already initialized; `default()` re-uses them. - Ok(()) => Ok(Pdfium::default()), - Err(message) => Err(IoError::Unsupported(message.clone())), - } -} - -#[cfg(test)] -mod tests { - use super::{MAX_OBJECT_LAYERS, MAX_PATH_KNOTS, ObjectBudget, PageFrame, PageGeometry}; - - /// A 595 x 842 pt page with no offset, rotated by `rotation` degrees. - fn geometry(rotation: u16) -> PageGeometry { - PageGeometry { width_pt: 595.0, height_pt: 842.0, origin_x: 0.0, origin_y: 0.0, crop_w: 595.0, crop_h: 842.0, rotation } - } - - /// A full-page frame at `dpi`, starting at document x `x`. - fn frame(dpi: f64, x: u32) -> PageFrame<'static> { - PageFrame { geometry: geometry(0), dpi, x, rgba: &[], width: 595, height: 842 } - } - - #[test] - /// Page points map through the DPI scale, the Y flip and the page's document X offset. - fn page_points_map_to_document_pixels() { - assert_eq!(frame(72.0, 0).to_doc(60.0, 420.0), (60.0, 422.0)); - // The same point at four times the resolution. - assert_eq!(frame(300.0, 0).to_doc(60.0, 420.0), (250.0, 1758.0)); - // Page 2 starts after page 1's width: the document X offset is part of the mapping. - assert_eq!(frame(300.0, 2480).to_doc(60.0, 420.0), (2730.0, 1758.0)); - } - - #[test] - /// The document-wide budget refuses layers and knots once its limits are reached. - fn object_budget_stops_at_its_limits() { - let mut budget = ObjectBudget::default(); - for _ in 0..MAX_OBJECT_LAYERS { - assert!(budget.claim_layer()); - } - assert!(!budget.claim_layer()); - let mut knots = ObjectBudget::default(); - assert!(knots.claim_knots(MAX_PATH_KNOTS)); - assert!(!knots.claim_knots(1)); - assert!(!knots.claim_knots(usize::MAX)); - } - #[test] - /// Crop-box offsets and 90/180/270 rotations land where the raster renders them. - fn crop_box_offsets_and_rotations_map_like_the_raster() { - // A 200 x 100 pt crop box at (10, 20), displayed rotated 90 degrees clockwise: 100 x 200. - let rotated = |rotation| PageFrame { - geometry: PageGeometry { width_pt: 100.0, height_pt: 200.0, origin_x: 10.0, origin_y: 20.0, crop_w: 200.0, crop_h: 100.0, rotation }, - dpi: 72.0, - x: 0, - rgba: &[], - width: 100, - height: 200, - }; - // At 72 dpi the rectangle (20, 30)..(60, 70) lands at (10, 10)..(50, 50). - assert_eq!(rotated(90).to_doc(20.0, 30.0), (10.0, 10.0)); - assert_eq!(rotated(90).to_doc(60.0, 70.0), (50.0, 50.0)); - // 180 mirrors X; 270 swaps the axes back. - assert_eq!(rotated(180).to_doc(20.0, 30.0), (190.0, 10.0)); - assert_eq!(rotated(270).to_doc(20.0, 30.0), (90.0, 190.0)); - // The page's document X offset is added after the page-space mapping. - let mut offset = rotated(90); - offset.x = 500; - assert_eq!(offset.to_doc(20.0, 30.0), (510.0, 10.0)); - } - - #[test] - /// The page sampler reads the requested pixel and reports black outside the page. - fn samples_the_rendered_page() { - // Two pixels: white then black. - let rgba = [255u8, 255, 255, 255, 0, 0, 0, 255]; - let page = PageFrame { - geometry: PageGeometry { width_pt: 2.0, height_pt: 1.0, origin_x: 0.0, origin_y: 0.0, crop_w: 2.0, crop_h: 1.0, rotation: 0 }, - dpi: 72.0, - x: 0, - rgba: &rgba, - width: 2, - height: 1, - }; - assert_eq!(page.color_at(0, 0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); - assert_eq!(page.color_at(1, 0), photocraft_doc::Color::BLACK); - assert_eq!(page.color_at(2, 0), photocraft_doc::Color::BLACK); - } - - #[test] - /// Glyph ink wins over the background inside a text box, while an empty box keeps background. - fn text_colour_samples_the_glyph_ink() { - // An 8 x 4 white page with one black glyph pixel at (2, 1). - let mut rgba = vec![255u8; 8 * 4 * 4]; - let glyph = (8 + 2) * 4; - rgba[glyph..glyph + 3].fill(0); - let page = PageFrame { - geometry: PageGeometry { width_pt: 8.0, height_pt: 4.0, origin_x: 0.0, origin_y: 0.0, crop_w: 8.0, crop_h: 4.0, rotation: 0 }, - dpi: 72.0, - x: 0, - rgba: &rgba, - width: 8, - height: 4, - }; - // The whole page box contains the glyph: the ink wins over the white background. - assert_eq!(page.text_color(0.0, 4.0, 8.0, 0.0), photocraft_doc::Color::BLACK); - // A box that contains only background keeps the background colour. - assert_eq!(page.text_color(4.0, 4.0, 8.0, 2.0), photocraft_doc::Color::rgb(1.0, 1.0, 1.0)); +fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError { + use raster::Error; + match error { + Error::Cancelled => IoError::Cancelled, + Error::OutputLimit => IoError::Unsupported(format!("PDF page {page} is too large at {dpi:.0} dpi; lower the import DPI")), + Error::InvalidPage => IoError::Unsupported(format!("PDF page {page} has an empty or invalid page box")), + Error::Allocation => IoError::Unsupported(format!("PDF page {page} needs more memory than is available")), + Error::BackendPanic => IoError::Unsupported(format!("PDF renderer failed on page {page}; it may be damaged")), + Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")), } } diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index ef02111309..f63ff19482 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -1,239 +1,26 @@ -//! PDF import end-to-end through PDFium. +//! PDF import end-to-end through craft-pdf (pure Rust, no shared library). //! -//! A synthetic two-page PDF with non-origin red text, a transformed blue rectangle and green text -//! is imported at 72 and 300 DPI, and the resulting editable layers are checked against the -//! fixture's geometry and pixels. PDFium is loaded at run time: when it is unavailable (no -//! `PDFIUM_DIR`, no DLL beside the test binary) the test prints an explicit SKIPPED line and -//! returns instead of pretending the end-to-end wiring passed. +//! A six-page synthetic PDF (plain, CropBox offset, rotations 90/180/270 and an oversized +//! CropBox) imports at 72 and 300 DPI as one artboard per page, with the page's print size kept, +//! a blue rectangle sampled from the raster, and the renderer's side/pixel limits respected by +//! lowering the effective DPI on a huge page. use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; -use pdfium_render::prelude::{PdfRenderConfig, Pdfium}; -use photocraft_doc::{Color, Document, Layer, LayerContent, ShapeLayer, TextLayer}; +use photocraft_doc::LayerContent; use photocraft_geom::Rect; -use photocraft_io::{ImportOptions, ImportResult, IoError, import_with_options_and_interrupt}; +use photocraft_io::{ImportOptions, IoError, import_with_options_and_interrupt}; use photocraft_raster::Interrupt; const PAGE_W: f64 = 200.0; const PAGE_H: f64 = 100.0; -const GAP: f64 = 80.0; -/// Imports the four-page fixture at 72 and 300 DPI and checks every layer it produces. -#[test] -fn imports_text_and_a_transformed_path_on_two_pages() { - let pdf = three_page_pdf(); - for dpi in [72.0f32, 300.0] { - let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; - let result = match import_with_options_and_interrupt("fixture.pdf", &pdf, &options, &photocraft_raster::Interrupt::NONE) { - Ok(result) => result, - Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { - eprintln!("SKIPPED the PDF import end-to-end test: PDFium is unavailable ({message})"); - // The Windows integration leg provisions PDFium and sets this: there a missing - // library must fail rather than let the runner report an unreached pass. - assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for this test but could not load: {message}"); - return; - } - Err(error) => panic!("PDF import failed at {dpi} dpi: {error}"), - }; - check(&result.document, dpi); - eprintln!("PDF import executed at {dpi} dpi: {} page groups, layer checks passed", result.document.layers.len()); - } -} - -/// Page 1: red 48 pt text at (20, 50). Page 2: a 20 x 10 pt rectangle scaled 2x and moved by -/// (10, 5) - corners (30, 25)..(70, 45) - plus green 48 pt text at (20, 20). Page 3: a crop box -/// offset to (10, 20, 210, 120) and rotated 90 degrees clockwise, with a 40 x 40 pt rectangle at -/// (20, 30)..(60, 70) that renders at (10, 10)..(50, 50) on a 100 x 200 page. -fn three_page_pdf() -> Vec { - let mut pdf = PdfDocument::with_version("1.5"); - let pages_id = pdf.new_object_id(); - let font_id = pdf.add_object(dictionary! { - "Type" => "Font", - "Subtype" => "Type1", - "BaseFont" => "Helvetica", - }); - let resources = pdf.add_object(dictionary! { - "Font" => dictionary! { "F1" => font_id }, - }); - let pages = [ - ("1 0 0 rg BT /F1 48 Tf 20 50 Td (Red) Tj ET", [0.0f32, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), - ("0 0 1 rg q 2 0 0 2 10 5 cm 10 10 20 10 re f Q 0 1 0 rg BT /F1 48 Tf 20 20 Td (Green) Tj ET", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, None), - ("0 0 1 rg 20 30 40 40 re f 0 0.5 0 rg BT /F1 24 Tf 40 60 Td (Rot) Tj ET", [10.0, 20.0, 210.0, 120.0], Some(90i64), None), - // A CropBox larger than the MediaBox: the rendered page and the mapping use the - // intersection, so the rectangle must not be offset by the crop box's negative origin. - ("0 0.5 0 rg 20 30 40 40 re f", [0.0, 0.0, PAGE_W as f32, PAGE_H as f32], None, Some([-50.0f32, -50.0, 250.0, 150.0])), - ]; - let mut kids = Vec::new(); - for (content, [left, bottom, right, top], rotate, crop) in pages { - let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); - let mut page = dictionary! { - "Type" => "Page", - "Parent" => pages_id, - "MediaBox" => Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)]), - "Contents" => content_id, - "Resources" => resources, - }; - if let Some(rotate) = rotate { - page.set("Rotate", rotate); - } - if let Some([left, bottom, right, top]) = crop { - page.set("CropBox", Object::Array(vec![Object::Real(left), Object::Real(bottom), Object::Real(right), Object::Real(top)])); - } - let page_id = pdf.add_object(page); - kids.push(Object::Reference(page_id)); - } - let count = kids.len() as i64; - pdf.objects.insert( - pages_id, - Object::Dictionary(dictionary! { - "Type" => "Pages", - "Kids" => Object::Array(kids), - "Count" => count, - }), - ); - let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); - pdf.trailer.set("Root", catalog); - let mut bytes = Vec::new(); - pdf.save_to(&mut bytes).expect("writing the PDF fixture"); - bytes -} - -/// Asserts the imported text and path layers at one DPI against the fixture geometry. -fn check(document: &Document, dpi: f32) { - let scale = f64::from(dpi) / 72.0; - let page_two_x = (PAGE_W * scale).round() + GAP; - - // Page 1: the editable text keeps its position and takes the red ink from the page. - let text = text_layer(page_children(document, 1)); - assert_red(&text.color, "page 1 text"); - let x = text.transform.m[4]; - let y = text.transform.m[5]; - assert!((x - 20.0 * scale).abs() < 8.0 * scale, "page 1 text x is {x} at {dpi} dpi"); - // 48 pt Helvetica's bounds top is about 35 pt above the baseline at y = 50. - assert!((y - 15.0 * scale).abs() < 20.0 * scale, "page 1 text y is {y} at {dpi} dpi"); - - // Page 2: the transformed rectangle lands at (30, 25)..(70, 45) plus the page's document X. - let shape = shape_layer(page_children(document, 2)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - assert!((min_x - (page_two_x + 30.0 * scale)).abs() < 4.0, "path min x is {min_x}, page 2 starts at {page_two_x} ({dpi} dpi)"); - assert!((max_x - (page_two_x + 70.0 * scale)).abs() < 4.0, "path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - (PAGE_H - 45.0) * scale).abs() < 4.0, "path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - (PAGE_H - 25.0) * scale).abs() < 4.0, "path max y is {max_y} ({dpi} dpi)"); - - let text = text_layer(page_children(document, 2)); - assert_green(&text.color, "page 2 text"); - assert!(text.transform.m[4] > page_two_x + 10.0 * scale, "page 2 text x misses the page offset: {} <= {page_two_x}", text.transform.m[4]); - - // Page 3: the crop box (10, 20, 210, 120) and /Rotate 90 put the rectangle at (10..50, 10..50). - let shape = shape_layer(page_children(document, 3)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - let page_three_x = 2.0 * (PAGE_W * scale).round() + 2.0 * GAP; - assert!((min_x - (page_three_x + 10.0 * scale)).abs() < 3.0, "rotated path min x is {min_x}, page 3 starts at {page_three_x} ({dpi} dpi)"); - assert!((max_x - (page_three_x + 50.0 * scale)).abs() < 3.0, "rotated path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - 10.0 * scale).abs() < 3.0, "rotated path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - 50.0 * scale).abs() < 3.0, "rotated path max y is {max_y} ({dpi} dpi)"); - - // Rotated text: the layer's transform carries the 90 degree turn, not just its position. - let text = text_layer(page_children(document, 3)); - let m = text.transform.m; - assert!(m[0].abs() < 0.01 && (m[1] - 1.0).abs() < 0.01 && (m[2] + 1.0).abs() < 0.01 && m[3].abs() < 0.01, "page 3 text rotation is {m:?}"); - assert!(m[4] > page_three_x, "page 3 text x misses the page offset: {} <= {page_three_x}", m[4]); - assert!(text.color.c[1] > 0.3 && text.color.c[0] < 0.2 && text.color.c[2] < 0.2, "page 3 text should be green, got {:?}", text.color.c); - - // Page 4: a CropBox (-50, -50, 250, 150) around a 200 x 100 MediaBox must not offset the rect. - let shape = shape_layer(page_children(document, 4)); - let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for knot in shape.path.subpaths.iter().flat_map(|subpath| &subpath.knots) { - min_x = min_x.min(knot.anchor.x); - max_x = max_x.max(knot.anchor.x); - min_y = min_y.min(knot.anchor.y); - max_y = max_y.max(knot.anchor.y); - } - // Page 3 is rotated 90 degrees, so it is 100 pt wide on the strip, not 200. - let page_four_x = 2.0 * (PAGE_W * scale).round() + (100.0 * scale).round() + 3.0 * GAP; - assert!((min_x - (page_four_x + 20.0 * scale)).abs() < 3.0, "oversized-crop path min x is {min_x}, page 4 starts at {page_four_x} ({dpi} dpi)"); - assert!((max_x - (page_four_x + 60.0 * scale)).abs() < 3.0, "oversized-crop path max x is {max_x} ({dpi} dpi)"); - assert!((min_y - 30.0 * scale).abs() < 3.0, "oversized-crop path min y is {min_y} ({dpi} dpi)"); - assert!((max_y - 70.0 * scale).abs() < 3.0, "oversized-crop path max y is {max_y} ({dpi} dpi)"); -} - -/// The layer children of the imported `Page N` group. -fn page_children(document: &Document, page: usize) -> &[Layer] { - let name = format!("Page {page}"); - let layer = document.layers.iter().find(|layer| layer.name == name).unwrap_or_else(|| panic!("no {name} layer")); - match &layer.content { - LayerContent::Group(group) => &group.children, - _ => panic!("{name} is not a group"), - } -} - -/// The first text layer among `children`. -fn text_layer(children: &[Layer]) -> &TextLayer { - children - .iter() - .find_map(|layer| match &layer.content { - LayerContent::Text(text) => Some(text), - _ => None, - }) - .expect("a text layer") -} - -/// The first shape layer among `children`. -fn shape_layer(children: &[Layer]) -> &ShapeLayer { - children - .iter() - .find_map(|layer| match &layer.content { - LayerContent::Shape(shape) => Some(shape), - _ => None, - }) - .expect("a shape layer") -} - -/// Asserts `color` is the fixture's red ink. -fn assert_red(color: &Color, what: &str) { - assert!(color.c[0] > 0.8 && color.c[1] < 0.2 && color.c[2] < 0.2, "{what} should be red, got {:?}", color.c); -} - -/// Asserts `color` is the fixture's green ink. -fn assert_green(color: &Color, what: &str) { - assert!(color.c[1] > 0.8 && color.c[0] < 0.2 && color.c[2] < 0.2, "{what} should be green, got {:?}", color.c); -} - -/// Imports `bytes`, or prints SKIPPED and returns `None` when PDFium cannot load. The Windows -/// integration leg sets `PHOTOCRAFT_REQUIRE_PDFIUM`, where a missing library must fail. -fn imported_or_skipped(bytes: &[u8], options: &ImportOptions, ctl: &Interrupt<'_>, what: &str) -> Option { - match import_with_options_and_interrupt("probe.pdf", bytes, options, ctl) { - Ok(result) => Some(result), - Err(IoError::Unsupported(message)) if message.contains("cannot load PDFium") => { - eprintln!("SKIPPED {what}: PDFium is unavailable ({message})"); - assert!(std::env::var_os("PHOTOCRAFT_REQUIRE_PDFIUM").is_none(), "PDFium is required for {what} but could not load: {message}"); - None - } - Err(error) => panic!("{what} failed: {error}"), - } -} - -/// Six one-page variants for the cancellation and fidelity probes: plain, a CropBox offset to -/// (10, 20, 210, 120), rotations of 90, 180 and 270 degrees, and an oversized CropBox -/// (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page draws a 40 x 40 blue rectangle -/// and a 10 x 10 red one at (20, 30). +/// Six one-page variants: plain, CropBox offset to (10, 20, 210, 120), rotations of 90/180/270 +/// degrees and an oversized CropBox (-50, -50, 250, 150) around the 200 x 100 MediaBox. Each page +/// draws a 40 x 40 blue rectangle at (20, 30) in PDF space. fn variant_pdf() -> Vec { - let mut pdf = PdfDocument::with_version("1.5"); - let pages_id = pdf.new_object_id(); let pages: [(Option, Option<[f32; 4]>); 6] = [ (None, None), (None, Some([10.0, 20.0, 210.0, 120.0])), @@ -242,9 +29,11 @@ fn variant_pdf() -> Vec { (Some(270), None), (None, Some([-50.0, -50.0, 250.0, 150.0])), ]; + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); let mut kids = Vec::new(); for (rotate, crop) in pages { - let content = b"0 0 1 rg 20 30 40 40 re f 1 0 0 rg 20 30 10 10 re f"; + let content = b"0 0 1 rg 20 30 40 40 re f"; let content_id = pdf.add_object(Stream::new(dictionary! {}, content.to_vec())); let mut page = dictionary! { "Type" => "Page", @@ -277,8 +66,102 @@ fn variant_pdf() -> Vec { bytes } -/// A cancel that lands on the last object's check, or on the public boundary after -/// `import_stages`, must be reported as `Cancelled` rather than returning a document. +/// One page of `width` x `height` points with the same blue rectangle. +fn one_page_pdf(width: f32, height: f32) -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let content_id = pdf.add_object(Stream::new(dictionary! {}, b"0 0 1 rg 20 30 40 40 re f".to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(width), Object::Real(height)]), + "Contents" => content_id, + "Resources" => dictionary! {}, + }); + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(vec![Object::Reference(page_id)]), + "Count" => 1, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the page PDF"); + bytes +} + +/// The first artboard rectangle of `document`. +fn first_artboard(document: &photocraft_doc::Document) -> Rect { + let layer = document.layers.first().expect("an imported page group"); + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("{} is not a group", layer.name), + }; + group.artboard.as_ref().expect("page artboard").rect +} + +#[test] +fn imports_every_page_as_an_artboard_with_its_print_size() { + let pdf = variant_pdf(); + for dpi in [72.0f32, 300.0] { + let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; + let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import"); + assert_eq!(result.document.layers.len(), 6, "one artboard per page at {dpi} dpi"); + let mut top_left = 0i32; + for (index, layer) in result.document.layers.iter().enumerate() { + let group = match &layer.content { + LayerContent::Group(group) => group, + _ => panic!("{} is not a page group", layer.name), + }; + let artboard = group.artboard.as_ref().expect("page artboard").rect; + let expected = match index { + // CropBox [10, 20, 210, 120] intersected with the MediaBox is 190 x 80 points. + 1 => (190.0, 80.0), + // Rotations 90 and 270 swap the axes. + 2 | 4 => (100.0, 200.0), + _ => (200.0, 100.0), + }; + let print_width = f64::from(artboard.width()) * 72.0 / f64::from(dpi); + let print_height = f64::from(artboard.height()) * 72.0 / f64::from(dpi); + assert!((print_width - expected.0).abs() < 1.0, "page {} width is {print_width:.1} pt, expected {} at {dpi} dpi", index + 1, expected.0); + assert!((print_height - expected.1).abs() < 1.0, "page {} height is {print_height:.1} pt, expected {} at {dpi} dpi", index + 1, expected.1); + assert_eq!(artboard.x0, top_left, "pages lay out side by side from x=0"); + top_left = artboard.x1 + 80; + let surface = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); + if index == 0 { + // The rectangle's centre in PDF space is (40, 50); at the document's top-left + // origin that is y = PAGE_H - 50. + let scale = f64::from(dpi) / 72.0; + let x = artboard.x0 + (40.0 * scale).round() as i32; + let y = ((PAGE_H - 50.0) * scale).round() as i32; + let mut pixel = [[0u8; 4]; 1]; + surface.read_rgba8_into(Rect::from_xywh(x, y, 1, 1), &mut pixel); + assert!(pixel[0][2] > 120 && pixel[0][0] < 120, "page 1 should be blue inside the rectangle, got {:?}", pixel[0]); + let mut background = [[0u8; 4]; 1]; + surface.read_rgba8_into(Rect::from_xywh(artboard.x0 + 2, 2, 1, 1), &mut background); + assert!(background[0][0] > 240 && background[0][1] > 240 && background[0][2] > 240, "page background should be white, got {:?}", background[0]); + } + } + } +} + +#[test] +fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { + // 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit. + let pdf = one_page_pdf(3000.0, 100.0); + let options = ImportOptions { pdf_dpi: 300.0, ..Default::default() }; + let result = import_with_options_and_interrupt("wide.pdf", &pdf, &options, &Interrupt::NONE).expect("PDF import"); + assert!(result.warnings.iter().any(|warning| warning.contains("rendered at")), "warnings: {:?}", result.warnings); + let artboard = first_artboard(&result.document); + assert!(artboard.width() <= 8192, "width {} is over the renderer's side limit", artboard.width()); + assert!(result.document.resolution_dpi < 300.0, "the effective DPI should be lowered"); + let print_width = f64::from(artboard.width()) * 72.0 / f64::from(result.document.resolution_dpi); + assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt"); +} + #[test] fn cancelling_on_the_last_checks_is_reported() { let pdf = variant_pdf(); @@ -289,17 +172,16 @@ fn cancelling_on_the_last_checks_is_reported() { false }; let ctl = Interrupt::cancel_only(&cancel); - if imported_or_skipped(&pdf, &options, &ctl, "the last-check cancellation test").is_none() { - return; - } + let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl); + assert!(result.is_ok(), "uncancelled import failed: {:?}", result.err()); let total = count.load(Ordering::SeqCst); assert!(total >= 3, "a complete import should check cancellation at least three times, got {total}"); - for (label, threshold) in [("the last per-object check", total - 1), ("the public boundary check", total)] { + for (label, threshold) in [("the last page check", total - 1), ("the public boundary check", total)] { let seen = AtomicUsize::new(0); let cancel = || seen.fetch_add(1, Ordering::SeqCst) + 1 >= threshold; let ctl = Interrupt::cancel_only(&cancel); let started = Instant::now(); - let result = import_with_options_and_interrupt("probe.pdf", &pdf, &options, &ctl); + let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl); let elapsed = started.elapsed(); assert_eq!(seen.load(Ordering::SeqCst), threshold, "cancelling on {label} should stop at check {threshold} of {total}"); match result { @@ -310,52 +192,3 @@ fn cancelling_on_the_last_checks_is_reported() { assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}"); } } - -/// Every imported page's stored raster must equal a direct PDFium render of the same page at the -/// same target width: crop intersection, rotation and the strip placement may not move or resample -/// a pixel. At 72, 150 and 300 DPI over the six variants that is 18 page renders. -#[test] -fn raster_matches_a_direct_pdfium_render() { - let pdf = variant_pdf(); - let mut compared = 0; - for dpi in [72.0f32, 150.0, 300.0] { - let options = ImportOptions { pdf_dpi: dpi, ..Default::default() }; - let Some(result) = imported_or_skipped(&pdf, &options, &Interrupt::NONE, "the raster fidelity matrix") else { - return; - }; - let pdfium = Pdfium::default(); - let reference = pdfium.load_pdf_from_byte_slice(&pdf, None).expect("reference PDF"); - assert_eq!(reference.pages().len() as usize, result.document.layers.len(), "page count at {dpi} dpi"); - for (index, layer) in result.document.layers.iter().enumerate() { - let group = match &layer.content { - LayerContent::Group(group) => group, - _ => panic!("page layer {} is not a group", layer.name), - }; - let artboard = group.artboard.as_ref().expect("page artboard").rect; - let raster = group.children.first().and_then(|layer| layer.surface()).expect("page raster layer"); - let (width, height) = (artboard.width(), artboard.height()); - let mut got = vec![[0u8; 4]; (width as usize) * (height as usize)]; - raster.read_rgba8_into(Rect::from_xywh(artboard.x0, artboard.y0, width, height), &mut got); - - let page = reference.pages().get(index as i32).expect("reference page"); - let bitmap = page.render_with_config(&PdfRenderConfig::new().set_target_width(width as i32)).expect("reference render"); - assert_eq!((bitmap.width() as u32, bitmap.height() as u32), (width, height), "page {} size at {dpi} dpi", index + 1); - let want = bitmap.as_rgba_bytes(); - - let mut max_diff = 0u32; - let mut sum = 0u64; - for (pixel, reference) in got.iter().zip(want.as_chunks::<4>().0.iter()) { - for channel in 0..4 { - let diff = (pixel[channel] as i32 - reference[channel] as i32).unsigned_abs(); - sum += u64::from(diff); - max_diff = max_diff.max(diff); - } - } - let channels = u64::from(width) * u64::from(height) * 4; - let mean = sum as f64 / channels as f64; - assert!(max_diff <= 1, "page {} at {dpi} dpi differs from the direct render: max channel diff {max_diff}, mean {mean:.4}", index + 1); - compared += 1; - } - } - assert_eq!(compared, 18, "six pages at three DPIs should all be compared"); -} diff --git a/docs/architecture.md b/docs/architecture.md index 0125f26693..ee9650cb10 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -183,7 +183,7 @@ photocraft/ 3. **`photocraft-psd` depends on no workspace crate.** The doc ⇄ PSD mapping lives in `io`. This keeps the PSD crate publishable and reusable by other projects. The same holds for every standalone crate, with one documented exception: `codecs` → `heif` (both standalone and publishable; `STANDALONE_EXCEPTIONS` in `xtask/src/layers.rs`). 4. **wasm gate:** every crate in L0–L5 (except feature-gated native backends) must build for `wasm32-unknown-unknown`. CI runs `cargo build -p photocraft-engine --target wasm32-unknown-unknown --no-default-features --features web`. 5. `gpu` is optional for `engine`. Engine features are `gpu` (default on) and `cpu-only`, and `cpu-only` builds are what the headless CLI and CI tests use. -6. **C dependencies** (optional LibRaw, pdfium) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target. +6. **C dependencies** (optional LibRaw) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target. --- diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 468365c6f6..02a2da7f79 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -40,7 +40,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | Portable Bit Map (PBM/PGM/PPM/PNM/PFM/PAM) | R/W | yes | yes | 8/16/32f | | FITS | R/W (FITS Liberator plug-in) | yes | yes | 8/16/32f gray or RGB, header cards kept; no fpack, no debayer | | Targa | R/W | yes | yes | 8-bit | -| Photoshop PDF | R/W | no (#2541) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | No vector/text PDF, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10); read still missing (#2541) | +| Photoshop PDF | R/W | yes, raster pages (craft-pdf; up to 16 pages, 8192 px per side, 64M px per page) | yes, one flattened page (Save As / Save a Copy / CLI, #3401; also print and artboards-to-PDF) | Read renders each page as a raster artboard: no editable text/vector layers yet (craft-pdf `interpret` is the follow-up), no PDF forms or annotations; write is still one flattened page, no multi-page save, no PDF presentation, layers are not preserved (FILE-215-10) | | Photoshop EPS, DCS 1.0/2.0, EPS TIFF/PICT preview | R/W | no | no | | | Generic EPS / AI | R (rasterize) | no | no | | | SVG | R (rasterize) | yes, as editable shape layers or a vector smart object | no | Better than Photoshop for editing; gradients approximated (FILE-215-9) | @@ -145,6 +145,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCraft editor choice, including nested PSB contents. AI/PDF/EPS working copies retain their format on save-back; a separate source-bound SVG display preview does not replace the native payload. Placement, shared instances, masks and Undo/Redo use existing smart-object transactions, with native bytes and previews persisted through .pcraft and PSD/PSB saves. Unsupported editor features may still change; standalone EPS/DCS import and lossless Adobe round-trip compatibility remain unverified. See [workflow, safety and validation limits](embedded-vector-editing.md). No corpus floor or parity percentage is changed. ## Revision history +| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | The original reference row retains its source date and historical totals; current totals are in the status and Actions row above. The original reference entry retains its source date and historical totals; current totals are in the status above. diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json index 8d01fab4ac..fcba1850ae 100644 --- a/packaging/windows/install-policy.json +++ b/packaging/windows/install-policy.json @@ -15,8 +15,7 @@ ], "payloads": [ "photocraft-cli.exe", - "photocraft.exe", - "pdfium.dll" + "photocraft.exe" ], "registry": [ [ diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 8b4e8d0fea..d984e3930a 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -55,77 +55,6 @@ New-Item -ItemType Directory -Force -Path $Dist | Out-Null if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } -# PDF import loads PDFium at runtime. Stage the Windows build's DLL before cargo, so the app's -# build script copies it beside the exe and both the MSI and the portable ZIP ship it. -# -# Pinned to a reviewed pdfium-binaries release: the archive is verified before extraction and a -# cached DLL is verified before reuse, so a moved or compromised "latest" cannot be packaged. -# Bump the release and both hashes together after re-checking the published build. -$PdfiumRelease = 'chromium/8138' -$PdfiumArchiveSha256 = @{ - x64 = '8d48973e3eb472dda0f5f2435e595ac043f9f2219dd71883392f549445afa8a5' - x86 = '5c32d44711a73ed8ae86b85322078da8444fc696b9326527eed2d9fcd620fc84' - arm64 = '5e04abdb36ba9b4b5c8630123eaf042036f8a62abda6e5529708fee3d35fbf4f' -} -$PdfiumDllSha256 = @{ - x64 = '71a3e63e6ab8f5746a0fc9de9bc3d0c0dc07eb60990dfd37d9db7fc891821943' - x86 = 'ee592bd01eaef454aada95ed483ceca1c4f6ce0f0b9568608f40c3861fbda035' - arm64 = '0b1b9a52b3297448cbe461ffbca1455603d85161d5e96090e1a89bd7c4a62a33' -} -$PdfiumDir = Join-Path $Root "target\pdfium\$Arch" -$PdfiumDll = Join-Path $PdfiumDir 'pdfium.dll' -$PdfiumLicense = Join-Path $PdfiumDir 'LICENSE' -$PdfiumLicenses = Join-Path $PdfiumDir 'licenses' -$PdfiumTag = Join-Path $PdfiumDir 'release.txt' - -function Get-Sha256([string] $Path) { (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant() } - -# A cache from another pinned release (or missing its licence set) is discarded whole. -$cachedRelease = if (Test-Path -LiteralPath $PdfiumTag) { (Get-Content -Raw -LiteralPath $PdfiumTag).Trim() } else { '' } -if ($cachedRelease -ne $PdfiumRelease) { - Remove-Item -LiteralPath $PdfiumDir -Recurse -Force -ErrorAction SilentlyContinue -} -if (Test-Path -LiteralPath $PdfiumDll) { - $actualDll = Get-Sha256 $PdfiumDll - if ($actualDll -ne $PdfiumDllSha256[$Arch]) { - Write-Warning "cached PDFium DLL is not the pinned $PdfiumRelease build ($actualDll); re-downloading" - Remove-Item -LiteralPath $PdfiumDll -Force - } -} -if (-not ((Test-Path -LiteralPath $PdfiumDll) -and (Test-Path -LiteralPath $PdfiumLicense) -and (Test-Path -LiteralPath $PdfiumLicenses))) { - $expectedArchive = $PdfiumArchiveSha256[$Arch] - if (-not $expectedArchive) { throw "no pinned PDFium checksum for $Arch" } - $tgz = Join-Path $env:TEMP "pdfium-win-$Arch.tgz" - Invoke-Native "download PDFium ($Arch, $PdfiumRelease)" { - Remove-Item -LiteralPath $tgz -Force -ErrorAction SilentlyContinue - Invoke-WebRequest -Uri "https://github.com/bblanchon/pdfium-binaries/releases/download/$PdfiumRelease/pdfium-win-$Arch.tgz" -OutFile $tgz - $actualArchive = Get-Sha256 $tgz - if ($actualArchive -ne $expectedArchive) { throw "PDFium $Arch archive checksum $actualArchive does not match the pinned $expectedArchive" } - New-Item -ItemType Directory -Force -Path $PdfiumDir | Out-Null - # A DLL left in bin\ by an earlier run must not be mistaken for this archive's extraction. - $extracted = Join-Path $PdfiumDir 'bin\pdfium.dll' - Remove-Item -LiteralPath $extracted -Force -ErrorAction SilentlyContinue - tar -xzf $tgz -C $PdfiumDir - if ($LASTEXITCODE -ne 0) { throw "PDFium $Arch archive extraction failed with exit code $LASTEXITCODE" } - if (-not (Test-Path -LiteralPath $extracted)) { throw 'PDFium archive had no bin/pdfium.dll' } - Move-Item -Force $extracted $PdfiumDll - Set-Content -LiteralPath $PdfiumTag -Value $PdfiumRelease -NoNewline - if ((Get-Sha256 $PdfiumDll) -ne $PdfiumDllSha256[$Arch]) { throw "extracted PDFium $Arch DLL checksum does not match the pinned build" } - Remove-Item -LiteralPath $tgz -Force - } -} -$env:PDFIUM_DLL = $PdfiumDll - -# PDFium's BSD licence and the licences of the libraries bundled into its DLL ship beside it. They -# are staged flat with a `pdfium-` prefix, so both the MSI's INSTALLFOLDER and the portable root -# carry them whether the DLL came from this download or the cache. -function Stage-PdfiumLicences([string] $Dest) { - Copy-Item -LiteralPath $PdfiumLicense -Destination (Join-Path $Dest 'pdfium-LICENSE.txt') -Force - Get-ChildItem -LiteralPath $PdfiumLicenses -File | ForEach-Object { - Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $Dest ("pdfium-license-" + $_.Name)) -Force - } -} - Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" if (-not $SkipBuild) { @@ -160,8 +89,6 @@ $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null Copy-Item (Join-Path $Bin 'photocraft.exe'), (Join-Path $Bin 'photocraft-cli.exe') $Stage -Copy-Item -LiteralPath $PdfiumDll -Destination $Stage -Stage-PdfiumLicences $Stage & (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') (Join-Path $Stage 'photocraft-cli.exe') @@ -244,8 +171,6 @@ $Portable = Join-Path $TargetDir "windows-package\photocraft-$Version-windows-$A Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable -Copy-Item -LiteralPath $PdfiumDll -Destination $Portable -Stage-PdfiumLicences $Portable foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxs index f727880a5a..6ff961fd99 100644 --- a/packaging/windows/photocraft.wxs +++ b/packaging/windows/photocraft.wxs @@ -33,7 +33,6 @@ - - - - - - From 2de7a9c042d2572a9a166971d11c07446d3a9b90 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:41:28 +0100 Subject: [PATCH 091/113] Revert "Export: split nested groups into separate layers/files" This reverts commit c1662d49116d73cf1760d37f7089a232a5159c6e. --- crates/engine/src/cmd/file_cmds/export.rs | 162 +++++----------------- crates/engine/src/cmd/file_cmds/tests.rs | 61 -------- 2 files changed, 38 insertions(+), 185 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 629b7aad82..1f7f9677ff 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -20,7 +20,7 @@ pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) export_layers_report_with(s, p, write).map(|report| report.files) } -/// A layer omitted from a successful Layers to Files export. +/// A top-level layer omitted from a successful Layers to Files export. #[derive(Debug, serde::Serialize)] pub struct SkippedExportLayer { /// Session layer id (names need not be unique). @@ -38,83 +38,14 @@ pub struct LayerExportReport { pub skipped: Vec, } -/// One layer the export will write or explain, in top-to-bottom order. -enum Planned<'a> { - Export(&'a Layer), - Skip(&'a Layer, &'static str), - Hidden(&'a Layer), -} - -/// Flattens a layer (and, with `split_groups`, its group descendants) into export entries. -fn plan_layer<'a>(layer: &'a Layer, split_groups: bool, visible_only: bool, plan: &mut Vec>) { - if !layer.visible && visible_only { - plan.push(Planned::Hidden(layer)); - // A hidden group takes its descendants with it; report each so the omission is complete. - if split_groups && let LayerContent::Group(group) = &layer.content { - for child in group.children.iter().rev() { - plan_hidden(child, plan); - } - } - return; - } - if let LayerContent::Group(group) = &layer.content - && split_groups - { - for child in group.children.iter().rev() { - plan_layer(child, split_groups, visible_only, plan); - } - return; - } - if matches!(layer.content, LayerContent::Adjustment(_)) { - plan.push(Planned::Skip(layer, "adjustment layer has no pixels of its own")); - } else { - plan.push(Planned::Export(layer)); - } -} - -/// Marks `layer` and all of its descendants as hidden, top to bottom. -fn plan_hidden<'a>(layer: &'a Layer, plan: &mut Vec>) { - plan.push(Planned::Hidden(layer)); - if let LayerContent::Group(group) = &layer.content { - for child in group.children.iter().rev() { - plan_hidden(child, plan); - } - } -} - -/// The same export as [`export_layers_with`], with an explanation for every omitted layer. -/// -/// `groups` chooses what a group produces: `"merged"` (the default) exports the group as one -/// file, as before; `"layers"` walks into the group and exports each visible layer inside it as -/// its own file (top to bottom), so no group is a file of its own. Encoding and write failures -/// remain errors, never successful skips. Existing numbering is preserved. +/// The same export as [`export_layers_with`], with an explanation for every omitted top-level +/// layer. Groups export merged, so their children are not separate exports or skips. Encoding +/// and write failures remain errors, never successful skips. Existing numbering is preserved. pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); - let split_groups = match p.get("groups") { - None => false, - Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { - "merged" => false, - "layers" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("groups must be \"merged\" or \"layers\", not {other:?}") }); - } - }, - Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "groups must be a string: \"merged\" or \"layers\"".into() }), - }; - let layer_names = match p.get("naming") { - None => false, - Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() { - "numbered" => false, - "layer" => true, - other => { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("naming must be \"numbered\" or \"layer\", not {other:?}") }); - } - }, - Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "naming must be a string: \"numbered\" or \"layer\"".into() }), - }; // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); @@ -122,65 +53,48 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let d = s.active().ok_or(EngineError::NoDocument)?; let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); - let mut plan = Vec::new(); - for l in doc.layers.iter().rev() { - plan_layer(l, split_groups, visible_only, &mut plan); - } let mut report = LayerExportReport::default(); - let mut used = std::collections::HashSet::new(); // Hidden layers never consumed a filename index; adjustments that pass the visibility // filter did. Keep those filenames stable while reporting both kinds of omission. let mut i = 0usize; - for entry in plan { - match entry { - Planned::Hidden(l) => report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }), - Planned::Skip(l, reason) => { - i += 1; - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason }); - } - Planned::Export(l) => { - let index = i; - i += 1; - let mut one = (*doc).clone(); - let mut only = l.clone(); - only.visible = true; - only.clipped = false; - one.layers = vec![only]; - if trim { - let mut bounds = Rect::EMPTY; - let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { - let width = band.rect.width() as usize; - for (i, rgba) in band.px.iter().enumerate() { - if rgba[3] > 0.0 && width > 0 { - let x = band.rect.x0 + (i % width) as i32; - let y = band.rect.y0 + (i / width) as i32; - bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); - } - } - Ok(()) - }); - if !bounds.is_empty() && bounds != one.bounds() { - crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; + for l in doc.layers.iter().rev() { + if !l.visible && visible_only { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); + continue; + } + let index = i; + i += 1; + if matches!(l.content, LayerContent::Adjustment(_)) { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); + continue; + } + let mut one = (*doc).clone(); + let mut only = l.clone(); + only.visible = true; + only.clipped = false; + one.layers = vec![only]; + if trim { + let mut bounds = Rect::EMPTY; + let _ = photocraft_compose::render_bands(&one, one.bounds(), 0, |band| -> std::result::Result<(), ()> { + let width = band.rect.width() as usize; + for (i, rgba) in band.px.iter().enumerate() { + if rgba[3] > 0.0 && width > 0 { + let x = band.rect.x0 + (i % width) as i32; + let y = band.rect.y0 + (i / width) as i32; + bounds = bounds.union(&Rect::new(x, y, x + 1, y + 1)); } } - - let name = if layer_names { - let base = sanitize(&l.name); - let mut name = format!("{base}.{format}"); - let mut n = 2; - while !used.insert(name.to_ascii_lowercase()) { - name = format!("{base}-{n}.{format}"); - n += 1; - } - name - } else { - format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)) - }; - let (bytes, _warnings) = encode(&one, &name, save)?; - write(&name, &bytes)?; - report.files.push(name); + Ok(()) + }); + if !bounds.is_empty() && bounds != one.bounds() { + crate::image_cmds::crop_doc(&mut one, cmd, bounds, true, [0.0; 4])?; } } + + let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); + let (bytes, _warnings) = encode(&one, &name, save)?; + write(&name, &bytes)?; + report.files.push(name); } Ok(report) } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 0703cf914e..d42d333128 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2573,67 +2573,6 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } } -#[test] -/// `groups: "layers"` walks into a group and writes each visible leaf as its own file. -fn layers_to_files_exports_group_children_as_loose_files() { - let dir = tmp("layers-groups"); - let mut s = session(8, 8, 8); - s.edit("Group", |doc, _| { - let fmt = doc.pixel_format(); - let child = |name: &str| photocraft_doc::Layer::new(name, photocraft_doc::LayerContent::Raster(photocraft_doc::Surface::new(fmt))); - let sub = photocraft_doc::Layer::new( - "sub", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { children: vec![child("c")], expanded: true, artboard: None, frame_stroke: None }), - ); - doc.layers.push(photocraft_doc::Layer::new( - "expanded", - photocraft_doc::LayerContent::Group(photocraft_doc::Group { - children: vec![child("a"), child("b"), sub], - expanded: true, - artboard: None, - frame_stroke: None, - }), - )); - Ok(()) - }) - .unwrap(); - let files = |r: &Value| -> Vec { r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect() }; - - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "loose", "groups": "layers"})).unwrap(); - assert_eq!( - files(&r), - vec![join(&dir, "loose_0000_c.png"), join(&dir, "loose_0001_b.png"), join(&dir, "loose_0002_a.png"), join(&dir, "loose_0003_Background.png")] - ); - assert!(files(&r).iter().all(|f| std::path::Path::new(f).is_file())); - - // The default still merges the group into one file. - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "merged"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "merged_0000_expanded.png"), join(&dir, "merged_0001_Background.png")]); - - // naming: "layer" writes the bare layer names instead of prefix_index_name. - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "layers", "naming": "layer"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "c.png"), join(&dir, "b.png"), join(&dir, "a.png"), join(&dir, "Background.png")]); - - // A hidden child is skipped with visibleOnly and exported without it. - s.edit("Hide b", |doc, _| { - let group = doc.layers.last_mut().ok_or_else(|| EngineError::Other("no group".into()))?; - let LayerContent::Group(g) = &mut group.content else { return Err(EngineError::Other("not a group".into())) }; - g.children[1].visible = false; - Ok(()) - }) - .unwrap(); - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "visible", "groups": "layers"})).unwrap(); - assert_eq!(files(&r), vec![join(&dir, "visible_0000_c.png"), join(&dir, "visible_0001_a.png"), join(&dir, "visible_0002_Background.png")]); - let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "groups": "layers", "visibleOnly": false})).unwrap(); - assert_eq!( - files(&r), - vec![join(&dir, "all_0000_c.png"), join(&dir, "all_0001_b.png"), join(&dir, "all_0002_a.png"), join(&dir, "all_0003_Background.png")] - ); - - // An unknown mode is rejected instead of silently merging. - assert!(s.execute("file.export.layersToFiles", json!({"dir": dir, "groups": "folders"})).is_err()); -} - #[test] fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { let mut s = session(4, 4, 8); From 060d35265a1a65a9f25f555b5f2d924208425209 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:46:18 +0100 Subject: [PATCH 092/113] PDF: keep the raster importer clippy-clean and refresh the scorecard - Iterate the page sizes with their index instead of indexing the vector (clippy::needless_range_loop). - Fix the .ai dispatch test's module path. - Regenerate docs/scorecard.md after the merge (10 of 197 settings). --- crates/io/src/lib.rs | 2 +- crates/io/src/pdf_import.rs | 3 +-- docs/scorecard.md | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 7519449224..195a58b01a 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1651,7 +1651,7 @@ mod tests { pdf.trailer.set("Root", catalog); let mut bytes = Vec::new(); pdf.save_to(&mut bytes).expect("writing the .ai fixture"); - assert!(pdf_import::is_pdf(&bytes)); + assert!(crate::pdf_import::is_pdf(&bytes)); assert_eq!(import_preflight("illustration.ai", &bytes), ImportPreflight::Unbounded); let result = import("illustration.ai", &bytes).expect("an .ai starting with %PDF- takes the PDF importer"); assert_eq!(result.document.artboards().len(), 1); diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 0fcc540749..fc4733908a 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -120,11 +120,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; let mut x: u32 = 0; - for index in 0..count { + for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() { ctl.check().map_err(|_| IoError::Cancelled)?; let page_number = first + index; let page = &pdf.pages()[page_number - 1]; - let (width_pt, height_pt) = sizes[index]; let width = page_pixels(width_pt, dpi); let height = page_pixels(height_pt, dpi); // The DPI solve keeps these inside the renderer's bounds; re-check rather than panic if diff --git a/docs/scorecard.md b/docs/scorecard.md index cb666664b9..4ff5f86cd6 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 197 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 662 of 662 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 194** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 197** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From c5a9288c4b6fe326922e3f3c9bfe32a599c0dfc5 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:52:35 +0100 Subject: [PATCH 093/113] PDF: keep the craft-pdf imports off the wasm build The module compiles for wasm (only its import entry point is stubbed), so the renderer imports and the native document types are gated; the web build no longer sees a dependency it does not have. --- crates/io/src/pdf_import.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index fc4733908a..c78d92018c 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -10,12 +10,19 @@ //! or shipped, and a malformed file is reported as an error rather than taking the process down. use crate::{ImportOptions, ImportResult, IoError}; +#[cfg(not(target_arch = "wasm32"))] use craft_pdf::interpret::InterpreterSettings; +#[cfg(not(target_arch = "wasm32"))] use craft_pdf::raster::{self, RenderCache}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_color::{ColorMode, PixelFormat, SampleType}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_doc::{Artboard, Document, Group, Layer, LayerContent}; +#[cfg(not(target_arch = "wasm32"))] use photocraft_geom::{Rect, Size}; -use photocraft_raster::{Interrupt, Surface}; +use photocraft_raster::Interrupt; +#[cfg(not(target_arch = "wasm32"))] +use photocraft_raster::Surface; /// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer. pub fn is_pdf(bytes: &[u8]) -> bool { From d297dd3a2d068a664fa87dc5e22d56cd7bb323c3 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:12:46 +0100 Subject: [PATCH 094/113] PDF: validate --pdf-dpi, band the raster conversion, complete the notices - --pdf-dpi now rejects zero, negative, NaN and infinite values at parse time (unit-tested) instead of silently falling back to 300 DPI. - The RGBA8 raster is converted and written in 256-row bands with a cancellation check per band, so the f32 buffer no longer duplicates a whole page; the pixel-memory estimate charges the retained raster instead of that buffer. - docs/file-format-parity.md: the 2026-11-07 revision row is inside the revision table. - NOTICE now reproduces the Hayro MIT notice, the Foxit/PDFium BSD-3-Clause text, Adobe's CMaps BSD-3-Clause text and the CC0 statement for the ICC profile; package.ps1 ships NOTICE and ATTRIBUTION.md in both installers. --- NOTICE | 37 ++++++++++++++++++++++++++++++++ apps/photocraft-cli/src/args.rs | 26 +++++++++++++++++++++- crates/io/src/pdf_import.rs | 28 ++++++++++++++---------- crates/io/tests/it/pdf_import.rs | 3 +++ docs/file-format-parity.md | 2 +- 5 files changed, 83 insertions(+), 13 deletions(-) diff --git a/NOTICE b/NOTICE index 826dea7490..d51db72c91 100644 --- a/NOTICE +++ b/NOTICE @@ -81,3 +81,40 @@ the standard-14 Foxit fonts (BSD-3-Clause), Adobe CMaps (BSD-3-Clause) and a Com profile by Clinton Ingram (CC0-1.0); per-file sources and hashes are in craft-libs ATTRIBUTION.md. No PDF assets are copied into this repository, and PDFium is no longer used or shipped. + +Licence texts for the optional PDF reader + +Hayro (MIT): +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Standard-14 Foxit fonts (BSD-3-Clause): +Copyright 2014 PDFium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Adobe CMaps (BSD-3-Clause): +Copyright 1990-2023 Adobe. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Compact ICC profile: CC0 1.0 Universal (public domain dedication), by Clinton Ingram (saucecontrol/Compact-ICC-Profiles). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 84cf7c0a88..a15019e666 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -114,7 +114,7 @@ pub(crate) struct ConvertArgs { #[arg(long)] pub(crate) approve_high_memory: bool, /// PDF import resolution in DPI (default 300) - #[arg(long)] + #[arg(long, value_name = "DPI", value_parser = pdf_dpi)] pub(crate) pdf_dpi: Option, /// PDF pages to import, 1-based: "3" or "2-7" (default all) #[arg(long)] @@ -320,6 +320,8 @@ enum ValueError { JpegFormat, #[error("expected on or off")] OnOff, + #[error("expected a positive number")] + PdfDpi, /// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused. #[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:)")] Bridge, @@ -388,6 +390,12 @@ fn on_off(s: &str) -> Result { } } +/// A PDF import DPI: a finite number greater than zero. The importer's fallback to 300 DPI is +/// for absent preferences, not for a mistyped flag. +fn pdf_dpi(s: &str) -> Result { + s.parse::().ok().filter(|dpi| dpi.is_finite() && *dpi > 0.0).ok_or(ValueError::PdfDpi) +} + fn jpeg_format(s: &str) -> Result { JpegFormat::parse(s).ok_or(ValueError::JpegFormat) } @@ -538,3 +546,19 @@ fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, tr } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `--pdf-dpi` only takes a positive finite number: a mistyped value is refused at parse time + /// instead of silently becoming the importer's 300 DPI fallback. + #[test] + fn pdf_dpi_rejects_non_positive_and_non_finite_values() { + assert!(pdf_dpi("300").is_ok()); + assert!(pdf_dpi("0.5").is_ok()); + for bad in ["0", "-1", "nan", "inf", "-inf", "abc"] { + assert!(pdf_dpi(bad).is_err(), "{bad} should be refused"); + } + } +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index c78d92018c..79db591088 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -101,10 +101,10 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if doc_width > u64::from(u32::MAX) || doc_height > u64::from(u32::MAX) { return Err(IoError::Unsupported("PDF import is too large at this DPI; lower the import DPI".into())); } - // Retained tiles plus the converting page's peak: craft-pdf's RGBA8 raster (4 B/px) and the - // f32 document buffer (16 B/px). + // Retained tiles plus the converting page's raster (4 B/px); the f32 conversion runs in + // 256-row bands, so it adds only a constant-sized buffer rather than a second full page. let max_page = sizes.iter().map(|&(w, h)| u64::from(page_pixels(w, dpi)) * u64::from(page_pixels(h, dpi))).max().unwrap_or(0); - let estimate = retained.saturating_add(max_page.saturating_mul(20)); + let estimate = retained.saturating_add(max_page.saturating_mul(4)); let budget = if opts.flat_max_pixel_bytes > 0 { opts.flat_max_pixel_bytes } else { DEFAULT_MAX_PIXEL_BYTES }; if estimate > budget { return Err(IoError::Unsupported(format!( @@ -159,17 +159,23 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); let bytes = rendered.bytes(); - let mut data = Vec::new(); - if data.try_reserve_exact(bytes.len()).is_err() { + // Convert and write in row bands: the f32 buffer stays bounded instead of a second + // 16-bytes-per-pixel copy of the whole page, and cancellation is polled per band. + const BAND_ROWS: usize = 256; + let row_bytes = width as usize * 4; + let band_bytes = row_bytes.saturating_mul(BAND_ROWS); + let mut data: Vec = Vec::new(); + if data.try_reserve_exact(band_bytes).is_err() { return Err(IoError::Unsupported(format!("PDF page {page_number} needs more memory than is available"))); } - for chunk in bytes.as_chunks::<4>().0 { - for &value in &chunk[..3] { - data.push(f32::from(value) / 255.0); - } - data.push(f32::from(chunk[3]) / 255.0); + for (band, rows) in bytes.chunks(band_bytes).enumerate() { + ctl.check().map_err(|_| IoError::Cancelled)?; + data.clear(); + data.extend(rows.iter().map(|&value| f32::from(value) / 255.0)); + let top = (band * BAND_ROWS) as i32; + let band_height = (rows.len() / row_bytes) as u32; + surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data); } - surface.write_region(Rect::from_xywh(x as i32, 0, width, height), &data); let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface)); let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index f63ff19482..95475ea200 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -103,6 +103,7 @@ fn first_artboard(document: &photocraft_doc::Document) -> Rect { group.artboard.as_ref().expect("page artboard").rect } +/// Each page becomes its own artboard at 72 and 300 DPI, with the print size preserved. #[test] fn imports_every_page_as_an_artboard_with_its_print_size() { let pdf = variant_pdf(); @@ -148,6 +149,7 @@ fn imports_every_page_as_an_artboard_with_its_print_size() { } } +/// A page over the renderer's side limit lowers the effective DPI instead of failing. #[test] fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { // 3000 pt at 300 dpi would be 12500 px wide, over craft-pdf's 8192 px side limit. @@ -162,6 +164,7 @@ fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt"); } +/// Cancelling on the last page check or the public boundary returns Cancelled, never a document. #[test] fn cancelling_on_the_last_checks_is_reported() { let pdf = variant_pdf(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 02a2da7f79..237e69921b 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -145,13 +145,13 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCraft editor choice, including nested PSB contents. AI/PDF/EPS working copies retain their format on save-back; a separate source-bound SVG display preview does not replace the native payload. Placement, shared instances, masks and Undo/Redo use existing smart-object transactions, with native bytes and previews persisted through .pcraft and PSD/PSB saves. Unsupported editor features may still change; standalone EPS/DCS import and lossless Adobe round-trip compatibility remain unverified. See [workflow, safety and validation limits](embedded-vector-editing.md). No corpus floor or parity percentage is changed. ## Revision history -| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | The original reference row retains its source date and historical totals; current totals are in the status and Actions row above. The original reference entry retains its source date and historical totals; current totals are in the status above. | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Photoshop PDF read: pages import as raster artboards through the shared craft-pdf (Hayro) renderer, up to 16 pages, 8192 px per side and 64M px per page; editable text/vectors and PDFium are gone. Write is unchanged. | | 2026-11-06 | minor | Scripted PSD/PSB saves take `maximizeCompatibility` (Save, Save As, Save a Copy, `app.save`, serve `doc.save`, MCP `doc_save`/`doc_export`, Batch, Image Processor, Layers to Files) over Preferences › File Handling for one save, and the CLI `--no-maximize-compatibility` (#8064). Layer channels and the merged image were already RLE (ZIP with prediction at 32-bit), as Photoshop writes them (#8645) | | 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). | | 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | From c5ebcd9dc77c62d5d498ae14005e4e31a2b03430 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 21:12:31 +0100 Subject: [PATCH 095/113] Regenerate docs/scorecard.md Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index cb666664b9..679d8b6cc5 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Tools](#tools) | 36 | 9 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 3 | 3 | 662 of 662 menu items live (100.0%) | +| [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -268,7 +268,7 @@ Menu wiring (`docs/parity-checklist.md`): 662 of 662 menu items live (100.0%). T | AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds/batch_run.rs and batch_naming.rs: flat subfolder output and last-result-wins names measured in Photoshop 2026; live open-document source; file naming components and serials; UTF-16 LE error log; stop-on-error; CLI and Batch dialog, #4579. Desktop Esc asks Continue/Stop, retaining one plan and error log; a read-only canvas preview shows each scratch-session input without a progress bar. Inputs are not live tabs with Layers panel content, so full window parity remains open. | | AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only | | AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency | -| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check | +| AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | From a91bc05a3df92266d3f1398f1f473d9933a4fea2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 21:26:04 +0100 Subject: [PATCH 096/113] Format the merged test module list Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 753f90fe55..8a810bd7ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -994,11 +994,11 @@ mod menu_item_labels_tests; #[cfg(test)] mod pen_path_ownership_tests; -#[cfg(test)] -mod brush_opacity_minimum_tests; #[cfg(test)] mod artboard_options_bar_tests; #[cfg(test)] +mod brush_opacity_minimum_tests; +#[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] mod layers_empty_area_menu_tests; From c7a4f6258e63b4b9bc564fd50452393c49b66b5b Mon Sep 17 00:00:00 2001 From: AethelisDEV Date: Sun, 8 Nov 2026 00:00:22 +0300 Subject: [PATCH 097/113] notices: format leftover blank lines --- crates/ui-egui/src/notices.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index 899d4cd63f..0e9a3035eb 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -318,8 +318,6 @@ mod tests { notice.lines.iter().map(|line| crate::i18n::fmt(line, &args)).collect::>().join(" ") } - - #[test] fn paste_hint_follows_the_shortcut_and_falls_back_to_the_menu() { let mut app = PhotocraftApp::new(Session::new(), Services::default()); From 38b7064daa7b5927bfe83fc9e8cff9c3884bcfd2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 22:17:47 +0100 Subject: [PATCH 098/113] Gradient stops: a stop dragged the other way off the bar comes off too (#10823) The reference application removes a colour stop dragged up past the opacity stops and an opacity stop dragged down past the colour stops, not only colour-down / opacity-up. The test that kept them now checks that they are removed. Co-Authored-By: ljkx Co-Authored-By: Claude Opus 5.5 --- .../ui-egui/src/tools/gradient_ui/editor_tests.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs index 34636bd376..0882a50ed2 100644 --- a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs +++ b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs @@ -278,17 +278,19 @@ fn an_opacity_stop_dragged_up_off_the_bar_is_removed() { } } -/// Only the stop's own direction takes it off: an opacity stop dragged down over the ramp and a -/// colour stop dragged up over it are kept, however far they go. +/// Either way off the bar takes a stop off, as in the reference application: an opacity stop +/// dragged down past the colour stops and a colour stop dragged up past the opacity stops are +/// removed too. #[test] -fn a_stop_dragged_the_other_way_is_kept() { +fn a_stop_dragged_the_other_way_comes_off_too() { for layer in [true, false] { - let (mut h, sink) = editor(layer); for opacity in [true, false] { + let (mut h, sink) = editor(layer); let from = marker(&h, 0.5, opacity); let to = from + vec2(0.0, if opacity { 70.0 } else { -70.0 }); - drag_through(&mut h, &[from, to], |h| assert_eq!(shown(h, sink), (3, 3), "layer {layer} opacity {opacity}: still shown")); - assert_eq!(counts(&h, sink), (3, 3), "layer {layer} opacity {opacity}: the stop is kept"); + let gone = if opacity { (3, 2) } else { (2, 3) }; + drag_through(&mut h, &[from, to], |h| assert_eq!(shown(h, sink), gone, "layer {layer} opacity {opacity}: gone from the preview")); + assert_eq!(counts(&h, sink), gone, "layer {layer} opacity {opacity}: the stop is removed"); } } } From b697d52ca0677b41c737188c4f56ad4f765c319b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 22:42:13 +0100 Subject: [PATCH 099/113] Background Eraser: Tolerance takes whole numbers 1-100 with an alert, bar tooltips (#11909) The options bar's Tolerance field stores whole numbers in 1..100. A value typed past the range becomes the closest one and, once the field is left, an alert with OK says "An integer between 1% and 100% is required. Closest value inserted." paint.backgroundEraser clamps tolerance to 1..100 and its params doc says so. The brush chip, Limits, Tolerance and Protect Foreground Color get the reference application's tooltips. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/eraser_cmds.rs | 4 +- ...background_eraser_tolerance_field_tests.rs | 163 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/panels/brush_controls.rs | 8 +- crates/ui-egui/src/tools/eraser_ui.rs | 41 ++++- 5 files changed, 212 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/background_eraser_tolerance_field_tests.rs diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index 1433498078..bf08c18ac2 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -140,7 +140,7 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet let bs = BgEraseSettings { sampling: enum_param(p, CMD, "sampling", Sampling::Continuous, "continuous|once|backgroundSwatch")?, limits: enum_param(p, CMD, "limits", Limits::Contiguous, "discontiguous|contiguous|findEdges")?, - tolerance: number(p, CMD, "tolerance", 50.0, 0.0..=100.0)? as f32 / 100.0, + tolerance: number(p, CMD, "tolerance", 50.0, 1.0..=100.0)? as f32 / 100.0, protect_foreground: flag(p, "protectForegroundColor", false), foreground: s.tools.foreground, background: s.tools.background, @@ -267,7 +267,7 @@ pub fn specs() -> Vec { label: "Background Eraser", menu: &[], shortcut: None, - params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##, + params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":1..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##, enabled: has_pixel_layer, run: background_eraser, journal: true, diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs new file mode 100644 index 0000000000..537fd02694 --- /dev/null +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -0,0 +1,163 @@ +//! #11909: the Background Eraser's Tolerance takes whole numbers 1..100; a value typed past the +//! range becomes the closest one and, once the field is left, an alert with OK says so. +//! `paint.backgroundEraser` clamps `tolerance` to 1..100 too, and the options bar's controls carry +//! the reference application's tooltips. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::eraser_ui::TOLERANCE_RANGE_ALERT; +use crate::state::{DialogKind, Tool}; + +fn app_harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.ui.tool = Tool::BackgroundEraser; + app + }); + h.run_steps(5); + h +} + +fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +/// Types `text` into the Tolerance field, then Tabs out of it. +fn type_tolerance(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alert(h: &Harness<'static, PhotocraftApp>) -> Option { + h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).and_then(|d| d.fields.get("message")).and_then(|m| m.as_str()).map(str::to_owned) +} + +fn tolerance(h: &Harness<'static, PhotocraftApp>) -> f32 { + h.state().ui.tool_options.bg_tolerance +} + +#[test] +fn tolerance_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("0", 1.0), ("150", 100.0), ("-5", 1.0)] { + let mut h = app_harness(); + type_tolerance(&mut h, typed); + assert_eq!(tolerance(&h), want, "{typed}"); + assert_eq!(alert(&h).as_deref(), Some(TOLERANCE_RANGE_ALERT), "{typed}"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alert(&h), None, "{typed}: OK closes the alert"); + assert_eq!(tolerance(&h), want, "{typed}: the clamped value is kept"); + } +} + +#[test] +fn the_alert_is_a_modal_the_control_channel_sees() { + let mut h = app_harness(); + type_tolerance(&mut h, "150"); + let dialogs = serde_json::to_value(&h.state().ui.dialogs).unwrap(); + assert!(dialogs.to_string().contains(TOLERANCE_RANGE_ALERT), "{dialogs}"); + assert!(h.query_by_label("OK").is_some(), "the alert has an OK button"); +} + +#[test] +fn tolerance_in_range_stores_a_whole_number_without_an_alert() { + let mut h = app_harness(); + type_tolerance(&mut h, "33.6"); + assert_eq!(tolerance(&h), 34.0); + assert_eq!(alert(&h), None); + type_tolerance(&mut h, "100"); + assert_eq!(tolerance(&h), 100.0); + assert_eq!(alert(&h), None, "the end of the range is in it"); + type_tolerance(&mut h, "abc"); + assert_eq!(tolerance(&h), 100.0, "not a number: the value stays"); + assert_eq!(alert(&h), None); +} + +/// The accessible descriptions (tooltips) of the widgets of `role` named `label`. +fn descriptions(h: &Harness<'static, PhotocraftApp>, role: Option, label: &str) -> Vec { + let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string()); + match role { + Some(role) => h.query_all_by_role(role).filter(|n| n.accesskit_node().label().as_deref() == Some(label)).filter_map(of).collect(), + None => h.query_all_by_label(label).filter_map(of).collect(), + } +} + +#[test] +fn the_bar_has_the_reference_tooltips() { + use egui::accesskit::Role; + for (role, label, tip) in [ + (Role::Button, "Brush Preset picker", "Click to open the Brush Preset picker"), + (Role::ComboBox, "Limits:", "How far to let the erasing spread"), + (Role::SpinButton, "Tolerance:", "Erase range of similar colors"), + (Role::CheckBox, "Protect Foreground Color", "Do not erase the foreground swatch color"), + ] { + let mut h = bar(Tool::BackgroundEraser); + assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover"); + let at = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).expect(label).rect().center(); + h.hover_at(at); + h.run_steps(8); + assert!(h.query_by_label(tip).is_some(), "{label}: resting on it shows {tip:?}"); + } +} + +#[test] +fn the_other_tools_keep_their_brush_chip_tooltip() { + for tool in [Tool::Eraser, Tool::Pencil] { + let h = bar(tool); + let found = descriptions(&h, None, "Brush Preset picker"); + assert!(found.iter().any(|d| d == "Brush Preset picker"), "{tool:?}: {found:?}"); + } +} + +/// The alpha at `(x, y)` after a Background Eraser stroke over white and a square one level off +/// white, with `tolerance`. +fn erased_alpha(tolerance: serde_json::Value, (x, y): (i32, i32)) -> f32 { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 40})).unwrap(); + s.execute("select.rect", json!({"x": 30, "y": 0, "width": 34, "height": 40, "antiAlias": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#feffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute( + "paint.backgroundEraser", + json!({"points": [[4, 20], [56, 20]], "size": 16, "hardness": 1, "sampling": "once", "limits": "discontiguous", "tolerance": tolerance}), + ) + .unwrap(); + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] +} + +#[test] +fn the_command_clamps_tolerance_to_1_through_100() { + // Sampled white; the square is 1/255 off it: Tolerance 1 % reaches it, 0 % would not. + let near = (45, 20); + assert!(erased_alpha(json!(1), near) < 1.0, "1 % erases the near-white square"); + assert_eq!(erased_alpha(json!(0), near), erased_alpha(json!(1), near), "0 is taken as 1"); + assert_eq!(erased_alpha(json!(-20), near), erased_alpha(json!(1), near), "below the range is taken as 1"); + assert_eq!(erased_alpha(json!(150), (6, 20)), erased_alpha(json!(100), (6, 20)), "150 is taken as 100"); +} + +#[test] +fn the_params_doc_says_1_through_100() { + let spec = photocraft_engine::commands::find("paint.backgroundEraser").expect("registered"); + assert!(spec.params.contains(r#""tolerance":1..100=50"#), "{}", spec.params); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f19ec41da9..420b030e60 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -771,6 +771,8 @@ impl SyntheticTarget { #[cfg(test)] mod artboard_add_mode_tests; #[cfg(test)] +mod background_eraser_tolerance_field_tests; +#[cfg(test)] mod brush_options_tooltips_tests; #[cfg(test)] mod brush_picker_escape_tests; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 9c07f56255..ddd45f38ba 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -125,8 +125,12 @@ pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushS ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim); icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Brush Preset picker"))); - // The Brush's own text (#11813); the other tools keep theirs. - let tip = if state.tool == crate::state::Tool::Brush { tl!("Click to open the Brush Preset picker") } else { tl!("Brush Preset picker") }; + // The Brush's and the Background Eraser's own text (#11813, #11909); the other tools keep theirs. + let tip = if matches!(state.tool, crate::state::Tool::Brush | crate::state::Tool::BackgroundEraser) { + tl!("Click to open the Brush Preset picker") + } else { + tl!("Brush Preset picker") + }; if resp.on_hover_text(tip).clicked() { if state.brush_picker.is_some() { crate::brush_picker::close(state); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index ac896eeb0b..a5a0fdb1cf 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -125,11 +125,48 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo ("findEdges".to_string(), tl!("Find Edges")), ]; widgets::dropdown(ui, "bg-eraser-limits", tl!("Limits:"), &mut o.bg_limits, &limits, 110.0); + // The dropdown's button, by the id its combo box takes from "bg-eraser-limits". + if let Some(limits) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("bg-eraser-limits"))) { + limits.on_hover_text(tl!("How far to let the erasing spread")); + } opt(ui, tl!("Tolerance:")); - widgets::value_field(ui, &mut o.bg_tolerance, 0.0..=100.0, "%", 62.0); - widgets::checkbox(ui, &mut o.bg_protect_fg, tl!("Protect Foreground Color")); + if tolerance_field(ui, &mut o.bg_tolerance) { + open_range_alert(app); + } + let o = &mut app.ui.tool_options; + widgets::checkbox(ui, &mut o.bg_protect_fg, tl!("Protect Foreground Color")).on_hover_text(tl!("Do not erase the foreground swatch color")); } _ => return false, } true } + +/// The alert for a Background Eraser Tolerance typed out of range (#11909). +pub const TOLERANCE_RANGE_ALERT: &str = "An integer between 1% and 100% is required. Closest value inserted."; + +/// The Background Eraser's Tolerance: whole numbers in 1..=100, as the reference application takes +/// them (#11909). A typed fraction becomes the nearest whole number, a value past the range the +/// closest one. Returns true when the field is left with a value typed out of range, so the +/// caller shows [`TOLERANCE_RANGE_ALERT`]. +fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { + // The field's own range is wide, so the typed value reaches here unclamped. + let mut typed = *value; + let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); + let out_id = r.id.with("out-of-range"); + if r.changed() && typed.is_finite() { + *value = typed.round().clamp(1.0, 100.0); + // Only what was typed alerts; a scrub past the ends just stops there. + let out = r.has_focus() && !(1.0..=100.0).contains(&typed); + ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); + } + r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) +} + +/// Shows [`TOLERANCE_RANGE_ALERT`]: a modal with OK, once even if more than one pass asks. +fn open_range_alert(app: &mut PhotocraftApp) { + let message = tl!(TOLERANCE_RANGE_ALERT).to_owned(); + let shown = app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} From 8f9643c932b0deafb5ac04a8761c5b4cdcdd430b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 22:54:47 +0100 Subject: [PATCH 100/113] Background Eraser: alert for an expression committed past the range, normalize a restored Tolerance (#11909) An expression such as 50*4 is applied as the field is left, so the out-of-range check now also counts the frame the field loses focus. A restored setting (an older 0, a fraction) shows and erases as the field would store it: a whole number in 1..100. Co-Authored-By: Claude Opus 5.5 --- ...background_eraser_tolerance_field_tests.rs | 28 +++++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 7 +++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 537fd02694..012c16c73e 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -93,6 +93,34 @@ fn tolerance_in_range_stores_a_whole_number_without_an_alert() { assert_eq!(alert(&h), None); } +#[test] +fn an_expression_committed_with_enter_past_the_range_alerts() { + let mut h = app_harness(); + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("50*4".into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(tolerance(&h), 100.0); + assert_eq!(alert(&h).as_deref(), Some(TOLERANCE_RANGE_ALERT)); +} + +#[test] +fn a_restored_tolerance_out_of_range_shows_as_the_field_stores_it() { + for (saved, want) in [(0.0, 1.0), (33.6, 34.0), (f32::NAN, 50.0)] { + let mut h = app_harness(); + h.state_mut().ui.tool_options.bg_tolerance = saved; + h.run_steps(3); + assert_eq!(tolerance(&h), want, "{saved}"); + assert_eq!(alert(&h), None, "{saved}: no alert for a restored value"); + } +} + /// The accessible descriptions (tooltips) of the widgets of `role` named `label`. fn descriptions(h: &Harness<'static, PhotocraftApp>, role: Option, label: &str) -> Vec { let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string()); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index a5a0fdb1cf..0d6ba3134e 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -149,14 +149,17 @@ pub const TOLERANCE_RANGE_ALERT: &str = "An integer between 1% and 100% is requi /// closest one. Returns true when the field is left with a value typed out of range, so the /// caller shows [`TOLERANCE_RANGE_ALERT`]. fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { + // A restored setting (an older 0, a fraction) shows and erases as the field would store it. + *value = if value.is_finite() { value.round().clamp(1.0, 100.0) } else { 50.0 }; // The field's own range is wide, so the typed value reaches here unclamped. let mut typed = *value; let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); let out_id = r.id.with("out-of-range"); if r.changed() && typed.is_finite() { *value = typed.round().clamp(1.0, 100.0); - // Only what was typed alerts; a scrub past the ends just stops there. - let out = r.has_focus() && !(1.0..=100.0).contains(&typed); + // Only what was typed alerts, also an expression committed as the field is left + // (`50*4` and Enter); a scrub past the ends just stops there. + let out = (r.has_focus() || r.lost_focus()) && !(1.0..=100.0).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); } r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) From 2a989225f6211aafd97550a377fa4fdab649ffdd Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 23:33:56 +0100 Subject: [PATCH 101/113] Background Eraser: no alert for a caption scrub, strokes use the stored Tolerance (#11909) A scrub of the Tolerance caption while the field has the keyboard stops at the range's end without the alert. Strokes send the Tolerance as the field stores it, so a restored fraction erases the same whether or not the options bar has drawn. Co-Authored-By: Claude Opus 5.5 --- ...background_eraser_tolerance_field_tests.rs | 42 +++++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 17 ++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 012c16c73e..9d5a1e8c22 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -121,6 +121,48 @@ fn a_restored_tolerance_out_of_range_shows_as_the_field_stores_it() { } } +#[test] +fn a_restored_fraction_reaches_the_stroke_as_a_whole_number() { + // The options bar need not have drawn: the stroke's params round it themselves. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for (saved, want) in [(23.6, 24.0), (0.0, 1.0), (f32::NAN, 50.0)] { + app.ui.tool_options.bg_tolerance = saved; + let p = crate::eraser_ui::background_eraser_params(&app, &[[1.0, 1.0, 1.0]]); + assert_eq!(p["tolerance"].as_f64(), Some(want), "{saved}"); + } +} + +#[test] +fn a_label_scrub_past_100_does_not_alert() { + let mut h = app_harness(); + type_tolerance(&mut h, "100"); + // The field keeps the keyboard while the caption is scrubbed past the end. + let field = h + .query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field"); + let rect = field.rect(); + field.click(); + h.run_steps(1); + // The caption sits just left of the field. + let from = egui::pos2(rect.left() - 25.0, rect.center().y); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(from + vec2(50.0 * k as f32, 0.0))); + h.run_steps(1); + } + let to = from + vec2(300.0, 0.0); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(tolerance(&h), 100.0); + assert_eq!(alert(&h), None, "a scrub stops at 100 without an alert"); +} + /// The accessible descriptions (tooltips) of the widgets of `role` named `label`. fn descriptions(h: &Harness<'static, PhotocraftApp>, role: Option, label: &str) -> Vec { let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string()); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 0d6ba3134e..779f56d3fd 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -53,7 +53,7 @@ pub(crate) fn background_eraser_params(app: &PhotocraftApp, points: &[[f64; 3]]) "points": points, "sampling": o.bg_sampling, "limits": o.bg_limits, - "tolerance": o.bg_tolerance, + "tolerance": stored_tolerance(o.bg_tolerance), "protectForegroundColor": o.bg_protect_fg, "seed": crate::retouch_ui::stroke_seed(points), }) @@ -150,7 +150,7 @@ pub const TOLERANCE_RANGE_ALERT: &str = "An integer between 1% and 100% is requi /// caller shows [`TOLERANCE_RANGE_ALERT`]. fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { // A restored setting (an older 0, a fraction) shows and erases as the field would store it. - *value = if value.is_finite() { value.round().clamp(1.0, 100.0) } else { 50.0 }; + *value = stored_tolerance(*value); // The field's own range is wide, so the typed value reaches here unclamped. let mut typed = *value; let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); @@ -158,13 +158,22 @@ fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { if r.changed() && typed.is_finite() { *value = typed.round().clamp(1.0, 100.0); // Only what was typed alerts, also an expression committed as the field is left - // (`50*4` and Enter); a scrub past the ends just stops there. - let out = (r.has_focus() || r.lost_focus()) && !(1.0..=100.0).contains(&typed); + // (`50*4` and Enter); a scrub past the ends (the field's or its caption's, even while + // the field has the keyboard) just stops there. + let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); + let out = typing && !(1.0..=100.0).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); } r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) } +/// A Tolerance as the field stores it: a whole number in 1..=100, the default 50 for a value +/// that is no number. Strokes use it too, so a restored setting erases the same before and after +/// the options bar shows it. +fn stored_tolerance(v: f32) -> f32 { + if v.is_finite() { v.round().clamp(1.0, 100.0) } else { 50.0 } +} + /// Shows [`TOLERANCE_RANGE_ALERT`]: a modal with OK, once even if more than one pass asks. fn open_range_alert(app: &mut PhotocraftApp) { let message = tl!(TOLERANCE_RANGE_ALERT).to_owned(); From 8b3e769173101cf96f40bf9922ed1d73c73f9f13 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 23:44:07 +0100 Subject: [PATCH 102/113] Background Eraser: drop a pending Tolerance alert when the field is entered again (#11909) An out-of-range edit cut off by hiding the options bar no longer shows its alert later, when the field is entered and left again without a change. The caption scrub test now starts at 90 and checks that it reaches 100. Co-Authored-By: Claude Opus 5.5 --- ...background_eraser_tolerance_field_tests.rs | 35 +++++++++++++++++-- crates/ui-egui/src/tools/eraser_ui.rs | 5 +++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 9d5a1e8c22..a976444c5d 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -135,8 +135,8 @@ fn a_restored_fraction_reaches_the_stroke_as_a_whole_number() { #[test] fn a_label_scrub_past_100_does_not_alert() { let mut h = app_harness(); - type_tolerance(&mut h, "100"); - // The field keeps the keyboard while the caption is scrubbed past the end. + type_tolerance(&mut h, "90"); + // The field keeps the keyboard while the caption is scrubbed from 90 past the end. let field = h .query_all_by_role(egui::accesskit::Role::SpinButton) .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) @@ -159,10 +159,39 @@ fn a_label_scrub_past_100_does_not_alert() { h.run_steps(3); h.key_press(egui::Key::Tab); h.run_steps(3); - assert_eq!(tolerance(&h), 100.0); + assert_eq!(tolerance(&h), 100.0, "the scrub reached the end"); assert_eq!(alert(&h), None, "a scrub stops at 100 without an alert"); } +#[test] +fn an_edit_cut_off_by_hiding_the_bar_leaves_no_stale_alert() { + let mut h = app_harness(); + let field = |h: &Harness<'static, PhotocraftApp>| { + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .rect() + .center() + }; + // 150 typed, then the bar goes away before the field is left. + let at = field(&h); + h.event(egui::Event::PointerMoved(at)); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("150".into())); + h.run_steps(1); + h.state_mut().ui.panels.options_bar = false; + h.run_steps(3); + h.state_mut().ui.panels.options_bar = true; + h.run_steps(3); + assert_eq!(tolerance(&h), 100.0); + // Back in the field and out again without a change: nothing to say. + type_tolerance(&mut h, "100"); + assert_eq!(alert(&h), None, "no alert for an edit that was already cut off"); +} + /// The accessible descriptions (tooltips) of the widgets of `role` named `label`. fn descriptions(h: &Harness<'static, PhotocraftApp>, role: Option, label: &str) -> Vec { let of = |n: egui_kittest::Node<'_>| n.accesskit_node().description().map(|d| d.to_string()); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 779f56d3fd..36451da695 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -155,6 +155,11 @@ fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { let mut typed = *value; let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); let out_id = r.id.with("out-of-range"); + // An edit the field never got to finish (the options bar was hidden while it had the + // keyboard) has nothing left to say once the field is entered again. + if r.gained_focus() { + ui.ctx().data_mut(|d| d.remove_temp::(out_id)); + } if r.changed() && typed.is_finite() { *value = typed.round().clamp(1.0, 100.0); // Only what was typed alerts, also an expression committed as the field is left From 3ad1695d3e14a62f9380221fbad8e95925de02e9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 00:01:49 +0100 Subject: [PATCH 103/113] Background Eraser: keep the Tolerance text while it is typed (#11909) While the field has the keyboard it gets back the value typed so far instead of the clamped one, so a leading 0 on the way to 05 no longer turns into 1 (and 15). The stored value is still clamped at once. Co-Authored-By: Claude Opus 5.5 --- ...background_eraser_tolerance_field_tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 13 ++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index a976444c5d..84160eea96 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -93,6 +93,25 @@ fn tolerance_in_range_stores_a_whole_number_without_an_alert() { assert_eq!(alert(&h), None); } +#[test] +fn a_leading_zero_typed_key_by_key_keeps_the_text() { + let mut h = app_harness(); + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + for c in ["0", "5"] { + h.event(egui::Event::Text(c.into())); + h.run_steps(2); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(tolerance(&h), 5.0, "0 then 5 is 05, not 15"); + assert_eq!(alert(&h), None, "05 is in range"); +} + #[test] fn an_expression_committed_with_enter_past_the_range_alerts() { let mut h = app_harness(); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 36451da695..1310057628 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -151,8 +151,11 @@ pub const TOLERANCE_RANGE_ALERT: &str = "An integer between 1% and 100% is requi fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { // A restored setting (an older 0, a fraction) shows and erases as the field would store it. *value = stored_tolerance(*value); + // While the field has the keyboard it gets back what was typed, not the stored value, so + // its text is left alone mid-entry (`0` on the way to `05` must not turn into `1`). + let draft_id = ui.make_persistent_id(egui::IdSalt::new("bg-eraser-tolerance-typed")); // The field's own range is wide, so the typed value reaches here unclamped. - let mut typed = *value; + let mut typed = ui.ctx().data(|d| d.get_temp::(draft_id)).unwrap_or(*value); let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); let out_id = r.id.with("out-of-range"); // An edit the field never got to finish (the options bar was hidden while it had the @@ -168,6 +171,14 @@ fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); let out = typing && !(1.0..=100.0).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); + if typing && r.has_focus() { + ui.ctx().data_mut(|d| d.insert_temp(draft_id, typed)); + } else { + ui.ctx().data_mut(|d| d.remove_temp::(draft_id)); + } + } + if !r.has_focus() { + ui.ctx().data_mut(|d| d.remove_temp::(draft_id)); } r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) } From e6992a855d41cfda79483b5656a888213385ca8d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 00:17:09 +0100 Subject: [PATCH 104/113] Background Eraser: a Tolerance set elsewhere wins over an interrupted edit (#11909) The typed-text draft remembers the setting it was stored with and is only used while that setting is unchanged, so a value set meanwhile (a tool preset while the options bar was hidden) shows from the first frame. Co-Authored-By: Claude Opus 5.5 --- ...background_eraser_tolerance_field_tests.rs | 29 +++++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 11 ++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs index 84160eea96..acf9d3de15 100644 --- a/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs +++ b/crates/ui-egui/src/background_eraser_tolerance_field_tests.rs @@ -112,6 +112,35 @@ fn a_leading_zero_typed_key_by_key_keeps_the_text() { assert_eq!(alert(&h), None, "05 is in range"); } +#[test] +fn a_tolerance_set_elsewhere_during_an_edit_wins_over_the_typed_text() { + let mut h = app_harness(); + h.query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("150".into())); + h.run_steps(1); + // The bar goes away mid-edit and a preset sets the Tolerance meanwhile. + h.state_mut().ui.panels.options_bar = false; + h.run_steps(2); + h.state_mut().ui.tool_options.bg_tolerance = 30.0; + h.state_mut().ui.panels.options_bar = true; + h.run_steps(1); + // From the first frame back, the field shows the preset's value. + let shown = h + .query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")) + .expect("the Tolerance field") + .accesskit_node() + .numeric_value(); + assert_eq!(shown, Some(30.0), "the field shows the preset's value, not the typed 150"); + h.run_steps(2); + assert_eq!(tolerance(&h), 30.0, "the preset's value, not the typed 150"); +} + #[test] fn an_expression_committed_with_enter_past_the_range_alerts() { let mut h = app_harness(); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 1310057628..3c5b997cb3 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -155,7 +155,10 @@ fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { // its text is left alone mid-entry (`0` on the way to `05` must not turn into `1`). let draft_id = ui.make_persistent_id(egui::IdSalt::new("bg-eraser-tolerance-typed")); // The field's own range is wide, so the typed value reaches here unclamped. - let mut typed = ui.ctx().data(|d| d.get_temp::(draft_id)).unwrap_or(*value); + // A draft only stands while the setting is still the one it stored: a value set elsewhere + // meanwhile (a tool preset while the bar was hidden) wins. + let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(draft_id)); + let mut typed = draft.filter(|(_, stored)| *stored == *value).map_or(*value, |(typed, _)| typed); let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "%", 62.0).on_hover_text(tl!("Erase range of similar colors")); let out_id = r.id.with("out-of-range"); // An edit the field never got to finish (the options bar was hidden while it had the @@ -172,13 +175,13 @@ fn tolerance_field(ui: &mut egui::Ui, value: &mut f32) -> bool { let out = typing && !(1.0..=100.0).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); if typing && r.has_focus() { - ui.ctx().data_mut(|d| d.insert_temp(draft_id, typed)); + ui.ctx().data_mut(|d| d.insert_temp(draft_id, (typed, *value))); } else { - ui.ctx().data_mut(|d| d.remove_temp::(draft_id)); + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id)); } } if !r.has_focus() { - ui.ctx().data_mut(|d| d.remove_temp::(draft_id)); + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id)); } r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) } From 47e14b5da298a00e2eb2e5a3f62e0a343eec35aa Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 00:28:37 +0100 Subject: [PATCH 105/113] Photo Filter keeps only Preserve Luminosity from its last OK (#9970) #9970 reopened Image > Adjustments > Photo Filter... at the filter, colour, density and Preserve Luminosity of its last OK. Measured in the reference application: after OK at 60, 70 and 74 %, with a preset or with Color and a custom colour, it reopens every time at Warming Filter (85), the orange swatch and 25 %; only Preserve Luminosity carries over (off after an OK with it off, on after an OK with it on). Opening now starts from the neutral settings and takes just that one value from the last OK; Alt still reopens at all the last settings (#8900). Tests and the ui-parity row follow the measured behaviour. Co-Authored-By: ljkx <177671075+ljkx@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/adjust_dialog.rs | 28 ++++++-- .../src/dialogs/adjust_dialog/tests.rs | 66 ++++++++++++------- docs/ui-parity.md | 6 +- 3 files changed, 68 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index fccaffbc24..f435bde1b4 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -284,15 +284,29 @@ pub fn reset(app: &PhotocraftApp, ctx: &egui::Context, fields: &mut Map Option { - if command.strip_prefix(PREFIX).is_some_and(|kind| REMEMBERS_LAST.contains(&kind)) { open_last(app, command) } else { open_neutral(app, command) } + let id = open_neutral(app, command)?; + let kind = command.strip_prefix(PREFIX).unwrap_or_default(); + let kept: Vec<(String, Value)> = match app.session.prefs().dialogs.get(command) { + Some(last) => KEEPS_LAST + .iter() + .filter(|(k, _)| *k == kind) + .filter_map(|(_, key)| last.get(*key).filter(|v| v.is_boolean()).map(|v| ((*key).to_owned(), v.clone()))) + .collect(), + None => Vec::new(), + }; + if let Some(d) = app.ui.dialog_mut(id) { + d.fields.extend(kept); + } + Some(id) } /// Opens the dialog for `command` with the kind's neutral settings. diff --git a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index a259987d42..c769f76c32 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -939,36 +939,50 @@ fn curves_on_a_targeted_filter_mask_is_a_gray_plane() { assert_eq!(curve_mode(&app, "curves"), photocraft_doc::ColorMode::Grayscale); } -/// #9879: Photo Filter opens at the filter and density last confirmed in it, without ⌥; Levels -/// still opens at its neutral settings, and a smart filter's dialog never takes the last ones. +/// #9879: the reference application's Photo Filter reopens at Warming Filter (85) and 25 % after +/// any OK, but keeps Preserve Luminosity as last confirmed (measured 2026-11-08); ⌥ reopens at all +/// the last settings; Levels still opens at its neutral settings, and a smart filter's dialog +/// never takes the last ones. #[test] -fn photo_filter_opens_at_its_last_settings() { +fn photo_filter_keeps_only_preserve_luminosity_from_its_last_ok() { let mut app = app_with_image(); let cmd = "image.adjustments.photoFilter"; let first = open_neutral(&mut app, cmd).unwrap(); let neutral = crate::filter_dialog::params_of(&app.ui.dialog_mut(first).unwrap().fields.clone()); app.ui.dialogs.clear(); let id = open(&mut app, cmd).unwrap(); - let sample = photocraft_engine::adjust_params::to_params( + let mut sample = photocraft_engine::adjust_params::to_params( &photocraft_engine::adjust_params::from_params("photoFilter", &sample_params("photoFilter"), None, photocraft_doc::ColorMode::Rgb).unwrap(), ); - assert_ne!(sample, neutral, "the sample differs from the neutral settings"); + // Preserve Luminosity is on by default; the sample turns it off with the other settings. + assert_eq!(neutral["preserveLuminosity"], json!(true)); + sample["preserveLuminosity"] = json!(false); + assert_ne!(sample["color"], neutral["color"], "the sample differs from the neutral settings"); + assert_ne!(sample["density"], neutral["density"]); if let Value::Object(p) = sample.clone() { app.ui.dialog_mut(id).unwrap().fields.extend(p); } crate::dialogs::confirm(&mut app, id).unwrap(); let again = open(&mut app, cmd).unwrap(); - assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()), sample, "reopened at the last settings"); - // Preserve Luminosity is on by default; turned off and confirmed, it reopens off. - assert_eq!(neutral["preserveLuminosity"], json!(true)); - app.ui.dialog_mut(again).unwrap().fields.insert("preserveLuminosity".into(), json!(false)); + let reopened = crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()); + assert_eq!(reopened["preserveLuminosity"], json!(false), "Preserve Luminosity off is kept"); + assert_eq!(reopened["color"], neutral["color"], "the colour is the neutral one again"); + assert_eq!(reopened["density"], neutral["density"], "and so is the density"); + // Turned on again and confirmed, it reopens on. + app.ui.dialog_mut(again).unwrap().fields.insert("preserveLuminosity".into(), json!(true)); crate::dialogs::confirm(&mut app, again).unwrap(); let again = open(&mut app, cmd).unwrap(); - let reopened = crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()); - assert_eq!(reopened["preserveLuminosity"], json!(false), "Preserve Luminosity off is remembered"); - assert_eq!(reopened["color"], sample["color"], "with the rest of the last settings"); - assert_eq!(reopened["density"], sample["density"]); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(again).unwrap().fields.clone()), neutral, "all neutral again"); + app.ui.dialogs.clear(); + // ⌥ reopens at every last setting (#8900). + let id = open(&mut app, cmd).unwrap(); + if let Value::Object(p) = sample.clone() { + app.ui.dialog_mut(id).unwrap().fields.extend(p); + } + crate::dialogs::confirm(&mut app, id).unwrap(); + let alt = open_last(&mut app, cmd).unwrap(); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(alt).unwrap().fields.clone()), sample, "⌥ reopens at the last settings"); app.ui.dialogs.clear(); let smart = open_neutral(&mut app, cmd).unwrap(); assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(smart).unwrap().fields.clone()), neutral, "open_neutral ignores them"); @@ -984,26 +998,34 @@ fn photo_filter_opens_at_its_last_settings() { assert_eq!(app.ui.dialog_mut(again).unwrap().fields["inBlack"], defaults["inBlack"], "Levels opens neutral without ⌥"); } -/// #9879 review: a custom colour confirmed in Photo Filter reopens with Color chosen, even after an -/// opening that switched to Filter and was cancelled (the choice lives in the editor memory). +/// #9879: Photo Filter reopens with Filter chosen for its neutral preset colour, even after an OK +/// with Color chosen (the choice lives in the editor memory), as the reference application does; +/// ⌥ reopens a custom colour with Color chosen, also after an opening that chose Filter and was +/// cancelled. #[test] fn photo_filter_reopens_with_the_choice_its_colour_implies() { let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); let cmd = "image.adjustments.photoFilter"; - let id = open(h.state_mut(), cmd).unwrap(); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456")); - h.run_steps(2); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - // The next opening chooses Filter (what clicking its radio stores), then is cancelled. let mode = dialog_mem("photoFilter").with(crate::adjust_editors::PHOTO_FILTER_MODE); let id = open(h.state_mut(), cmd).unwrap(); h.run_steps(2); - h.ctx.data_mut(|d| d.insert_temp(mode, false)); - h.state_mut().ui.close_dialog(id); + let neutral = h.state_mut().ui.dialog_mut(id).unwrap().fields["color"].clone(); + // Color chosen (what clicking its radio stores), a custom colour, OK. + h.ctx.data_mut(|d| d.insert_temp(mode, true)); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456")); + h.run_steps(2); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); h.run_steps(1); let id = open(h.state_mut(), cmd).unwrap(); h.run_steps(2); + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["color"], neutral, "the neutral colour again"); + assert_eq!(h.ctx.data(|d| d.get_temp::(mode)), Some(false), "Filter is chosen for the preset colour"); + // That opening is cancelled with Filter chosen; ⌥ brings the custom colour back with Color. + h.state_mut().ui.close_dialog(id); + h.run_steps(1); + let id = open_last(h.state_mut(), cmd).unwrap(); + h.run_steps(2); assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["color"], json!("#123456")); assert_eq!(h.ctx.data(|d| d.get_temp::(mode)), Some(true), "Color is chosen for the custom colour"); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e69b1f6b76..8840897f38 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Image › Adjustments › Photo Filter… opens at the filter and density of its last OK, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -224,7 +224,7 @@ for partial sets; [scope, tests and visual evidence](multi-channel-editing.md). | Paragraph box overflow mark: text past the box shows a + in its lower-right handle | done (2026-10-29): text a box can't hold (dropped layout lines) enlarges the box's lower-right handle and shows a black + in it, as the reference application does; agents read `typeBoxOverflow` in `ui.inspect` (false once the edit session ends). Differs: shown while the inline edit session is on the box, and not while its transform handles are up | `text::TextLayout::overflows`, `canvas_tests.rs` `an_overflowing_box_shows_a_plus_in_its_enlarged_lower_right_handle` | | Image › Adjustments › Selective Color: each of the nine colours keeps its own Cyan, Magenta, Yellow and Black; choosing another colour shows its values; OK and Preview apply all nine | done (#11463): one editor shared with the Properties panel (`adjust_editors/selective_color.rs`, `adjust_dialog/tests.rs`, 2026-11-05). Preset menu and `.asv` files not yet | | | ⌥ + an adjustment's shortcut opens it at its last settings (⌥⌘L Levels, ⌥⌘M Curves, and so ⌥⌘U, ⌥⌘B) | done (#8900): the settings of the last OK, kept in the preferences; Cancel and smart filter edits keep nothing; a key assigned to another command stays that command's. ⌥ while choosing the item from Image › Adjustments does the same | `shortcut_dispatch/tests.rs` `alt_adjustment_shortcut_reopens_the_last_confirmed_settings`, `alt_choosing_an_adjustment_from_the_menu_reopens_the_last_settings` | -| Photo Filter remembers its last settings: Image › Adjustments › Photo Filter… opens at the filter, colour, density and Preserve Luminosity of its last OK | done (#9879): the other adjustments still open at their neutral settings and take the last ones with ⌥; a smart filter's dialog shows that filter's own settings | `adjust_dialog/tests.rs` `photo_filter_opens_at_its_last_settings` | +| Photo Filter keeps Preserve Luminosity: Image › Adjustments › Photo Filter… opens at Warming Filter (85) and 25 % after any OK, with Preserve Luminosity as last confirmed | done (#9879): measured in the reference application 2026-11-08 (filter, colour and density are not kept); ⌥ reopens at all the last settings; a smart filter's dialog shows that filter's own settings | `adjust_dialog/tests.rs` `photo_filter_keeps_only_preserve_luminosity_from_its_last_ok`, `photo_filter_reopens_with_the_choice_its_colour_implies` | | Guides: click selects, Delete deletes, right-click menu, ⌥-click turns a guide, double-click opens Guides, Grid & Slices | done (2026-10-12) | a guide let go over either ruler is removed, not only off the canvas (#6286) | | Blend mode keys: ⇧⌥ + letter picks a mode (N Normal, I Dissolve, R Clear, P Pass Through, K M B A darken, G S D W lighten, O F H V J Z L contrast, E X difference, U T C Y component), ⇧+ / ⇧− step through them | done (2026-10-14): Brush, Pencil and Gradient take them as their own mode (Clear on Brush, Pencil and Paint Bucket only), any non-painting tool sets every selected layer in one undo step (Pass Through on groups only; the Background is skipped); the typed letter wins, the physical key is the fallback for ⌥ characters on a Mac. ⇧⌥ letters no longer switch tools. While a Free Transform box is open they, and the number keys, still reach the tool (or the layers) without closing it; Puppet Warp and Perspective Warp keep them to themselves. Clone Stamp, Pattern Stamp, History Brush, Healing (its own short list) and Paint Bucket (with Clear) take them as their own mode; tools without a blend mode (the Erasers, Mixer Brush) set the layers. Differs: Behind (⇧⌥Q) is not implemented; Spot Healing, Color Replacement, Blur, Sharpen and Smudge ignore the keys until their options bar has a Mode, and Dodge, Burn and Sponge ignore them until their Range and mode keys (⇧⌥S/M/H, ⇧⌥D/S) exist | `blend_keys.rs` | @@ -273,13 +273,13 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK; filter, colour and density reopen at Warming Filter (85) and 25 %, measured in the reference application (#9879); no percentage changed | | 2026-11-07 | minor | Foreground/background colours restored before the first frame (`Preferences.toolColors`, #8485), with separate pixel/mask pairs, HDR/alpha, exact CMYK ink picks and a final normal-exit flush; malformed values are ignored one by one, and first saves from older preferences merge against the default swatches so separate edits in two instances survive. No percentage changed | | 2026-11-07 | minor | Reset Transform on a smart object also clears the **Warp**, and centres on the average of the placement's four corners rather than the point its box centre maps to: measured in the reference application 2026-11-06 (a smart object warped with Arc 50, rotated 20° and scaled to 80 % came back with no warp at all, at its contents' own size, unrotated), which corrects the row below (#11662, discussion in #11675). The corner average is the box centre for an affine placement, so only Distort and Perspective placements move; the Smart Filter mask and linked masks keep following the placement, as under Free Transform. The step also requires its re-render: a visible filter PhotoCraft doesn't implement, or contents that can't be read, refuses it whole (no history state, placement and warp untouched) rather than recording the old warped pixels at the reset placement. No percentage changed | | 2026-11-06 | minor | Layer ▸ Smart Objects ▸ Reset Transform, and the same item in the Layers panel row menu for a smart object layer (#11662): 100 % of the current contents' own size again with rotation, skew, Distort and Perspective cleared and the object left centred where it is, in one undo step; the Warp and the smart filters are untouched, as Photoshop resets the transform and not the warp. No percentage changed | | 2026-11-06 | minor | Channels panel menu (☰): the channel items, not only the rows' context menu; New Channel…, New Spot Channel…, Channel Options… and Merge Channels… open their dialogs (New Channel and Merge Channels are new), and Channel Options… in Quick Mask mode opens a targeted alpha channel's options (#11451). No percentage changed | | 2026-11-05 | minor | Image › Adjustments › Selective Color keeps each colour's own Cyan, Magenta, Yellow and Black, and OK and Preview apply all nine colours; the dialog and the Properties panel share one editor (#11463) | | 2026-11-02 | minor | Edit › Transform › Distort: the side handles move their edge freely, both its corners by the drag, stopping before the box folds as a corner does; Perspective's side handles skew along their edge, as in Photoshop (#10085). Not a new command, so no percentage changed | -| 2026-11-02 | minor | Image › Adjustments › Photo Filter… opens at the filter and density of its last OK, without ⌥, as in Photoshop (#9879); no percentage changed | | 2026-11-01 | minor | Every preference takes effect: 11 of 183 do nothing (was 12); Graphics Adapter always worked, but startup read it by raw JSON key, which the scorecard audit can't see | | 2026-10-31 | minor | Layers panel filter-type dropdown: Color filters by the layers' label colour (#5898); Kind, Name, Mode, Color, Smart Object and Artboard, the other three missing; no percentage changed | | 2026-10-29 | minor | Paragraph box overflow: text a box can't hold enlarges the box's lower-right handle and shows a black + in it, as the reference application does (#8311); agents read `typeBoxOverflow` in `ui.inspect`. Not a new command, so no percentage changed | From de9e11df9b345391f712d61d2ed7eed15d99f354 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 11:33:24 -0600 Subject: [PATCH 106/113] Toolbar: Star Tool in the shape slot between Polygon and Line (#11377) --- README.md | 4 +- crates/engine/src/shell_commands.rs | 1 + crates/ui-egui/src/canvas/snap_ui.rs | 6 +- crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/panels/toolbar.rs | 2 +- crates/ui-egui/src/star_tool_tests.rs | 103 +++++++++++++++++++ crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/state/tool.rs | 8 +- crates/ui-egui/src/tools/corner_radius.rs | 2 +- crates/ui-egui/src/tools/shape_bounds_box.rs | 2 +- crates/ui-egui/src/tools/tool_reset.rs | 2 +- crates/ui-egui/src/tools/vector_ui/shapes.rs | 4 +- 13 files changed, 129 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/star_tool_tests.rs diff --git a/README.md b/README.md index b1b453a318..c1789ab7d2 100644 --- a/README.md +++ b/README.md @@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 68 tools

- Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 69 tools

+ Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index 49db9509e5..7aaf58ffcd 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -169,6 +169,7 @@ pub const TOOLS: &[(&str, &str, Option<&str>)] = &[ ("tools.select.ellipseShape", "Ellipse Tool", Some("U")), ("tools.select.triangle", "Triangle Tool", Some("U")), ("tools.select.polygon", "Polygon Tool", Some("U")), + ("tools.select.star", "Star Tool", Some("U")), ("tools.select.line", "Line Tool", Some("U")), ("tools.select.customShape", "Custom Shape Tool", Some("U")), ("tools.select.slice", "Slice Tool", Some("C")), diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index 989af47e1c..f1a8917b63 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -146,6 +146,7 @@ fn is_point_tool(t: Tool) -> bool { | Tool::EllipseShape | Tool::Triangle | Tool::Polygon + | Tool::Star | Tool::Line | Tool::Type | Tool::VerticalType @@ -334,7 +335,10 @@ pub(crate) fn snap_click(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers /// the pixel grid. fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] { if app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid - && matches!(app.ui.tool, Tool::Pen | Tool::CurvaturePen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line) + && matches!( + app.ui.tool, + Tool::Pen | Tool::CurvaturePen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line + ) { [p[0].round(), p[1].round()] } else { diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c102064a7f..0a40f7b034 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -179,6 +179,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::EllipseShape => "circle", Tool::Triangle => "triangle", Tool::Polygon => "pentagon", + Tool::Star => "star", Tool::Line => "slash", Tool::CustomShape => "cloud", } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7d5d2a90e8..2388c9d29d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -865,6 +865,9 @@ mod transform_reference_point_tests; #[cfg(test)] mod transform_relative_position_tests; +#[cfg(test)] +mod star_tool_tests; + #[cfg(test)] mod transform_several_tests; diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index 12f85de2c1..da8500f535 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -30,7 +30,7 @@ pub(crate) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint, Tool::ConvertPoint], &[Tool::Type, Tool::VerticalType, Tool::VerticalTypeMask, Tool::HorizontalTypeMask], &[Tool::PathSelection, Tool::DirectSelection], - &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape], + &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Star, Tool::Line, Tool::CustomShape], ], &[&[Tool::Hand, Tool::RotateView], &[Tool::Zoom]], ]; diff --git a/crates/ui-egui/src/star_tool_tests.rs b/crates/ui-egui/src/star_tool_tests.rs new file mode 100644 index 0000000000..e79fa9f4c3 --- /dev/null +++ b/crates/ui-egui/src/star_tool_tests.rs @@ -0,0 +1,103 @@ +//! The Star Tool (#11377): in the shape slot between Polygon and Line, on U, and a drag makes a +//! live star shape layer with PhotoCraft's star defaults (5 points, star ratio 0.5). + +use egui::{Key, Modifiers}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::state::Tool; + +const SHAPES: [Tool; 7] = [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Star, Tool::Line, Tool::CustomShape]; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +fn live_shape(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + match &st.doc.layer(st.active_layer?)?.content { + LayerContent::Shape(s) => s.live.clone(), + _ => None, + } +} + +#[test] +fn star_sits_in_the_shape_slot_after_polygon() { + let slot = TOOL_SECTIONS.iter().flat_map(|s| s.iter()).find(|slot| slot.contains(&Tool::Star)).copied(); + assert_eq!(slot, Some(&SHAPES[..])); + let pos = |t: Tool| Tool::ALL.iter().position(|x| *x == t); + assert_eq!(pos(Tool::Star), pos(Tool::Polygon).map(|p| p + 1), "Tool::ALL keeps the slot order"); +} + +#[test] +fn star_is_a_shape_tool_on_u_with_its_label_icon_and_name() { + assert!(crate::tools::vector_ui::is_shape_tool(Tool::Star)); + assert_eq!(Tool::Star.key(), 'U'); + assert_eq!(Tool::Star.label(), "Star Tool"); + assert_eq!(Tool::from_name("Star Tool"), Some(Tool::Star)); + assert_eq!(Tool::from_name("star"), Some(Tool::Star)); + assert_eq!(crate::icons::tool_icon(Tool::Star), "star"); +} + +#[test] +fn shift_u_steps_from_polygon_to_star_to_line() { + let mut app = app(); + app.ui.tool = Tool::Polygon; + press(&mut app, Key::U, Modifiers::SHIFT); + assert_eq!(app.ui.tool, Tool::Star); + press(&mut app, Key::U, Modifiers::SHIFT); + assert_eq!(app.ui.tool, Tool::Line); +} + +#[test] +fn a_drag_makes_a_live_star_shape_layer_with_one_undo_step() { + let mut app = app(); + app.ui.tool = Tool::Star; + let before = app.session.active().unwrap().history.past_len(); + drag(&mut app, [20.0, 30.0], [120.0, 90.0], Modifiers::NONE); + match live_shape(&app) { + Some(LiveShape::Polygon { rect, sides, star_ratio, .. }) => { + assert_eq!((sides, star_ratio), (5, 0.5)); + assert_eq!(rect, [20.0, 30.0, 100.0, 60.0]); + } + other => panic!("a live star shape, got {other:?}"), + } + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "one history step"); + app.run("edit.undo", json!({})).unwrap(); + assert!(live_shape(&app).is_none(), "undo takes the star away"); +} + +#[test] +fn shift_and_alt_constrain_and_centre_the_star_like_the_polygon_tool() { + let mut app = app(); + app.ui.tool = Tool::Star; + drag(&mut app, [100.0, 100.0], [140.0, 120.0], Modifiers::SHIFT | Modifiers::ALT); + match live_shape(&app) { + Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [60.0, 60.0, 80.0, 80.0], "a square box drawn from the centre"), + other => panic!("a live star shape, got {other:?}"), + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 256a88bb38..5b79331819 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -769,7 +769,7 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 68); + assert_eq!(Tool::ALL.len(), 69); } fn vector_tool_names_parse() { diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 8dda7ce231..66aa7d53f6 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -71,6 +71,8 @@ pub enum Tool { EllipseShape, Triangle, Polygon, + /// The shape flyout's Star Tool (#11377): a live polygon shape with a star ratio. + Star, Line, CustomShape, Slice, @@ -79,7 +81,7 @@ pub enum Tool { } impl Tool { - pub const ALL: [Tool; 68] = [ + pub const ALL: [Tool; 69] = [ Tool::Move, Tool::Artboard, Tool::RectMarquee, @@ -143,6 +145,7 @@ impl Tool { Tool::EllipseShape, Tool::Triangle, Tool::Polygon, + Tool::Star, Tool::Line, Tool::CustomShape, Tool::Slice, @@ -218,6 +221,7 @@ impl Tool { Tool::EllipseShape => "Ellipse Tool", Tool::Triangle => "Triangle Tool", Tool::Polygon => "Polygon Tool", + Tool::Star => "Star Tool", Tool::Line => "Line Tool", Tool::CustomShape => "Custom Shape Tool", } @@ -288,7 +292,7 @@ impl Tool { // In the Pen flyout, but P never reaches them. Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => '', Tool::PathSelection | Tool::DirectSelection => 'A', - Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U', + Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line | Tool::CustomShape => 'U', } } /// Glyph drawn in the toolbar (vector icons come later). diff --git a/crates/ui-egui/src/tools/corner_radius.rs b/crates/ui-egui/src/tools/corner_radius.rs index 6358ffd139..f5ec3192e9 100644 --- a/crates/ui-egui/src/tools/corner_radius.rs +++ b/crates/ui-egui/src/tools/corner_radius.rs @@ -150,7 +150,7 @@ pub struct Drag { fn shows(app: &PhotocraftApp) -> bool { app.ui.transform.is_none() && match app.ui.tool { - Tool::PathSelection | Tool::Rectangle | Tool::Triangle | Tool::Polygon => true, + Tool::PathSelection | Tool::Rectangle | Tool::Triangle | Tool::Polygon | Tool::Star => true, Tool::Move => app.ui.tool_options.move_show_transform, _ => false, } diff --git a/crates/ui-egui/src/tools/shape_bounds_box.rs b/crates/ui-egui/src/tools/shape_bounds_box.rs index ee137bc541..d56508bf96 100644 --- a/crates/ui-egui/src/tools/shape_bounds_box.rs +++ b/crates/ui-egui/src/tools/shape_bounds_box.rs @@ -62,7 +62,7 @@ pub struct Drag { fn shows(app: &PhotocraftApp) -> bool { app.ui.transform.is_none() && app.ui.view.shows(app.ui.view.show.target_path) - && matches!(app.ui.tool, Tool::PathSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line) + && matches!(app.ui.tool, Tool::PathSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line) } /// The selected shape layers and the box round their paths. `None` unless at least one layer is diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 5ae380a4be..6c19b9e42b 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -257,7 +257,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { arrow_length, arrow_concavity, ), - Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::CustomShape => { + Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::CustomShape => { reset!(shape_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight) } Tool::ColorSampler diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 7b67544721..562e700bc3 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -3,7 +3,7 @@ use super::overlay::path_lines; use super::{Affine, Color32, PhotocraftApp, Tokens, Tool, ToolOptions, Value, ViewXform, json, paint_param}; pub fn is_shape_tool(t: Tool) -> bool { - matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape) + matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line | Tool::CustomShape) } fn rgb32(c: [f32; 4]) -> Color32 { @@ -80,6 +80,8 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), + // PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377). + Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}), _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), } }) From fe13a8acc376189883d316ca369072145abefe62 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 7 Nov 2026 17:41:12 -0600 Subject: [PATCH 107/113] Star Tool test: the star layer keeps the tool's fill and stroke (maintainer suggestion) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/star_tool_tests.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/star_tool_tests.rs b/crates/ui-egui/src/star_tool_tests.rs index e79fa9f4c3..b83bb15d83 100644 --- a/crates/ui-egui/src/star_tool_tests.rs +++ b/crates/ui-egui/src/star_tool_tests.rs @@ -2,7 +2,7 @@ //! live star shape layer with PhotoCraft's star defaults (5 points, star ratio 0.5). use egui::{Key, Modifiers}; -use photocraft_doc::{LayerContent, LiveShape}; +use photocraft_doc::{Color, Fill, LayerContent, LiveShape, ShapeLayer}; use serde_json::json; use crate::PhotocraftApp; @@ -37,14 +37,18 @@ fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); } -fn live_shape(app: &PhotocraftApp) -> Option { +fn shape_layer(app: &PhotocraftApp) -> Option { let st = app.session.active()?; match &st.doc.layer(st.active_layer?)?.content { - LayerContent::Shape(s) => s.live.clone(), + LayerContent::Shape(s) => Some(s.clone()), _ => None, } } +fn live_shape(app: &PhotocraftApp) -> Option { + shape_layer(app)?.live +} + #[test] fn star_sits_in_the_shape_slot_after_polygon() { let slot = TOOL_SECTIONS.iter().flat_map(|s| s.iter()).find(|slot| slot.contains(&Tool::Star)).copied(); @@ -77,6 +81,9 @@ fn shift_u_steps_from_polygon_to_star_to_line() { fn a_drag_makes_a_live_star_shape_layer_with_one_undo_step() { let mut app = app(); app.ui.tool = Tool::Star; + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + app.ui.tool_options.shape_fill = true; + app.ui.tool_options.stroke_width = 5.0; let before = app.session.active().unwrap().history.past_len(); drag(&mut app, [20.0, 30.0], [120.0, 90.0], Modifiers::NONE); match live_shape(&app) { @@ -86,6 +93,11 @@ fn a_drag_makes_a_live_star_shape_layer_with_one_undo_step() { } other => panic!("a live star shape, got {other:?}"), } + let shape = shape_layer(&app).expect("a star shape layer"); + let solid = |r, g, b| Fill::Solid(Color::rgba(r, g, b, 1.0)); + assert_eq!(shape.fill, Some(solid(1.0, 0.0, 0.0)), "filled with the foreground colour"); + let stroke = shape.stroke.expect("the star keeps the tool's stroke"); + assert_eq!((stroke.paint, stroke.width), (solid(0.0, 0.0, 1.0), 5.0), "stroked with the background colour at the tool's width"); assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "one history step"); app.run("edit.undo", json!({})).unwrap(); assert!(live_shape(&app).is_none(), "undo takes the star away"); From 6547fadccd87ca2f8ffb4f7a73a970a6121865ff Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 01:24:18 +0000 Subject: [PATCH 108/113] Floor a restored brush's opacity at 1 % A brush remembered at 0 % opacity (saved before the 1 % floor) read back at 0: the options bar showed 1 % but strokes painted nothing. Restoring now floors opacity at 1 %, like tools.setBrush (#11812). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 7 +++++-- crates/engine/src/cmd/brush_cmds/tests.rs | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 9f371bcd17..61a35e5150 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -1172,8 +1172,8 @@ pub fn remembered_settings(b: &BrushSettings) -> Option { /// A brush remembered by [`remembered_settings`], read back at launch: `None` when the value is /// not a brush or fails the checks `tools.setBrush` makes (a size or scatter out of range). The -/// options-bar values are clamped to the ranges their controls allow (size 1..max px; hardness, -/// opacity, flow and smoothing 0..100 %), and stored tips load when the store is attached (else +/// options-bar values are clamped to the ranges their controls allow (size 1..max px; opacity +/// 1..100 %; hardness, flow and smoothing 0..100 %), and stored tips load when the store is attached (else /// they paint with their previews until `Session::attach_preset_store`). pub fn restored_settings(s: &Session, v: &Value) -> Option { if !v.is_object() { @@ -1185,6 +1185,9 @@ pub fn restored_settings(s: &Session, v: &Value) -> Option { for f in [&mut b.hardness, &mut b.opacity, &mut b.flow, &mut b.smoothing.amount] { *f = if f.is_nan() { 1.0 } else { f.clamp(0.0, 1.0) }; } + // Opacity takes 1-100 %, as `tools.setBrush` floors it: a brush remembered at 0 % (saved + // before that floor) would show 1 % but paint nothing (#11812). + b.opacity = b.opacity.max(0.01); let _ = s.load_brush_tips(&mut b); Some(b) } diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index f72a0e207b..3abf932823 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -1380,6 +1380,22 @@ fn restored_brush_settings_are_clamped_or_rejected() { } } +/// #11812: a brush remembered at 0 % opacity (saved before the 1 % floor) reads back at 1 %, the +/// value its options-bar field shows, so it paints instead of laying down nothing. +#[test] +fn restored_brush_opacity_floors_at_one_percent() { + let s = Session::new(); + for opacity in [0.0, -1.0, 0.004] { + let b = restored_settings(&s, &json!({"opacity": opacity})).unwrap(); + assert_eq!(b.opacity, 0.01, "{opacity}"); + } + assert_eq!(restored_settings(&s, &json!({"opacity": 0.37})).unwrap().opacity, 0.37, "values above the floor are kept"); + let mut t = Session::new(); + t.prefs.edit(|p| p.last_brush = json!({"brush": {"opacity": 0.0}})); + restore_brush(&mut t); + assert_eq!(t.tools.brush.opacity, 0.01, "the remembered session brush"); +} + #[test] fn remembered_brushes_never_embed_large_bitmaps() { use std::sync::Arc; From 4750447f23c011b3294cea98da4b70b8c767d038 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 01:03:17 +0100 Subject: [PATCH 109/113] Floor an imported brush's opacity at 1 % when it is selected Importing an .abr with select picked its first brush without the 1 % opacity floor, so a preset saved at 0 % showed 1 % but painted nothing (#11812). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/preset_import_cmds.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 3adbee6f06..4430f4d1d2 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -176,6 +176,9 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io && let Some(pr) = photocraft_paint::presets::find(&s.tools.presets, first) { let mut b = pr.brush.clone().picked_over(&s.tools.brush); + // Opacity takes 1-100 %, as `tools.setBrush` floors it: a preset saved at 0 % would show + // 1 % but paint nothing (#11812). + b.opacity = b.opacity.max(0.01); s.load_brush_tips(&mut b).map_err(|e| bad("brush.presets.importAbr", e))?; s.tools.brush = b; s.tools.brush_changed(); @@ -477,6 +480,24 @@ mod tests { .unwrap() } + /// #11812: selecting an imported brush whose tool options hold 0 % opacity floors it at 1 %, + /// the value its options-bar field shows, so it paints instead of laying down nothing. + #[test] + fn selecting_an_imported_zero_opacity_brush_floors_it_at_one_percent() { + use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; + let preset = |opacity: i32| { + Descriptor::new("brushPreset") + .with("Nm ", D::Text(UnicodeString::new_nul("Faint"))) + .with("toolOptions", D::Descriptor(Descriptor::new("currentToolOptions").with("Opct", D::Integer(opacity)))) + }; + for (opacity, expected) in [(0, 0.01), (37, 0.37)] { + let abr = photocraft_psd::abr::write_v6_folders(2, &[], &[], &[preset(opacity)], &[vec![]], true).unwrap(); + let mut s = Session::new(); + s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&abr), "select": true})).unwrap(); + assert!((s.tools.brush.opacity - expected).abs() < 1e-6, "{opacity}: {}", s.tools.brush.opacity); + } + } + #[test] fn import_adds_a_group_and_paints() { let mut s = Session::new(); From caae1c8a1f29560766a27ca20ef718dd2772cc79 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 02:19:35 +0100 Subject: [PATCH 110/113] Address CodeRabbit review: close the sampler menu when its sampler changes The Color Sampler menu kept only the sampler's index. If a control command deleted an earlier sampler while the menu was open, the index named another sampler and Delete removed that one. The menu now also remembers the active document and the sampler's position; when either no longer matches, Delete greys out and the menu closes. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 24 +++++++++++++++-- .../tools/analysis_ui/sampler_menu_tests.rs | 27 +++++++++++++++++++ crates/ui-egui/src/transform_type_tests.rs | 1 + 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 098304d147..50059007ad 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -50,6 +50,11 @@ pub struct CanvasToolMenu { /// `None` off a sampler, where every row is greyed. #[serde(default)] pub sampler: Option, + /// Where that sampler was when the menu opened: the active document's index and the sampler's + /// position. Once a control command deletes, moves or renumbers samplers, or another document + /// becomes active, the index may name a different sampler, so the menu closes and Delete greys. + #[serde(default)] + pub sampler_at: Option<(usize, [f64; 2])>, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -308,6 +313,7 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; spelling: None, crop: Some(users), sampler: None, + sampler_at: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -478,6 +484,14 @@ pub const SAMPLER_MENU: &[Row] = &[ Some(("Total Ink", "colorSampler.readout.totalInk")), ]; +/// Does the Color Sampler menu's index still name the sampler it opened on, in the same document? +/// `true` off a sampler, where there is nothing to go stale. +fn sampler_current(app: &PhotocraftApp, menu: &CanvasToolMenu) -> bool { + let Some(i) = menu.sampler else { return true }; + let now = app.session.active_index().zip(app.session.active().and_then(|d| d.color_samplers.get(i).copied())); + now.is_some() && now == menu.sampler_at +} + /// Is `menu` the Color Sampler's own menu (not the pasteboard, guide or transform menu opened /// with it)? fn sampler_menu(menu: &CanvasToolMenu) -> bool { @@ -693,6 +707,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> spelling: None, crop: None, sampler: None, + sampler_at: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -775,6 +790,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: spelling: None, crop: None, sampler: None, + sampler_at: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -807,6 +823,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui spelling: None, crop: None, sampler: None, + sampler_at: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -861,8 +878,7 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) } // Off a sampler every row is greyed. The readout rows wait for per-sampler readout modes. if sampler_menu(menu) { - let count = app.session.active().map_or(0, |d| d.color_samplers.len()); - return command == SAMPLER_DELETE && menu.sampler.is_some_and(|i| i < count); + return command == SAMPLER_DELETE && menu.sampler.is_some() && sampler_current(app, menu); } if menu.transform || !path_menu(menu.tool) { return crate::menus::is_enabled(app, command); @@ -925,6 +941,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; + let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); app.ui.canvas_tool_menu = Some(CanvasToolMenu { pos, tool, @@ -940,6 +957,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] spelling, crop: None, sampler, + sampler_at, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -968,6 +986,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; spelling: None, crop: None, sampler: None, + sampler_at: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1213,6 +1232,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { || (menu.text && app.ui.text_edit.is_none()) || (menu.type_layer && app.ui.text_edit.is_some()) || (menu.crop.is_some() && !crate::crop_ui::pending(app)) + || (sampler_menu(&menu) && !sampler_current(app, &menu)) { app.ui.canvas_tool_menu = None; return; diff --git a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs index feef455427..9388a31f68 100644 --- a/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs +++ b/crates/ui-egui/src/tools/analysis_ui/sampler_menu_tests.rs @@ -112,6 +112,33 @@ fn delete_removes_the_sampler_under_the_pointer_and_renumbers_the_rest() { assert_eq!(listed["samplers"][1]["number"], json!(2)); } +#[test] +fn delete_never_removes_another_sampler_after_the_list_changes_under_the_menu() { + let (mut app, ctx) = app(); + app.run("view.colorSamplers.add", json!({"x": 180, "y": 90})).unwrap(); + right_click(&mut app, &ctx, 120.0, 60.0); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + // An agent deletes #1 while the menu is open: index 1 now names the old #3. + app.run("view.colorSamplers.delete", json!({"index": 0})).unwrap(); + let r = control(&mut app, &ctx, "ui.context.choose", json!({"id": SAMPLER_DELETE})); + assert_eq!(r["ok"], json!(false), "Delete greys out: {r}"); + assert_eq!(samplers(&app), [[120.0, 60.0], [180.0, 90.0]], "no other sampler is deleted"); + // The menu itself closes on the next frame. + right_click(&mut app, &ctx, 120.0, 60.0); + app.run("view.colorSamplers.move", json!({"index": 0, "x": 30, "y": 30})).unwrap(); + ctx.run_ui(Default::default(), |ui| crate::canvas_tool_menu::show(&mut app, ui.ctx())).textures_delta.clear(); + assert!(app.ui.canvas_tool_menu.is_none(), "a moved sampler closes the menu"); + // Another document with a sampler at the same index and spot: still not this menu's sampler. + right_click(&mut app, &ctx, 180.0, 90.0); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.sampler), Some(1)); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + for (x, y) in [(20, 20), (180, 90)] { + app.run("view.colorSamplers.add", json!({"x": x, "y": y})).unwrap(); + } + let menu = app.ui.canvas_tool_menu.clone().expect("the menu is still open"); + assert!(!crate::canvas_tool_menu::entry_enabled(&app, &menu, SAMPLER_DELETE), "another document's sampler"); +} + #[test] fn readout_rows_do_nothing_until_samplers_have_readout_modes() { let (mut app, ctx) = app(); diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index c62e7cf87d..e179e4f6d5 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -57,6 +57,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { spelling: None, crop: None, sampler: None, + sampler_at: None, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); From 1df674997b3d10368b4c8237155a8d68d720ea48 Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:34:58 +0100 Subject: [PATCH 111/113] PDF: cancel dense pages, complete page labels, isolate artboards - render_page: forward Interrupt to craft-pdf through an owned flag and a scoped 5 ms watcher, so dense vector pages stop mid-render. - Warn when craft-pdf reports a substituted font (the backend does not emit the flag yet). - /PageLabels: emit an entry for every page, start at 0, and write no tree when every artboard name is empty. - Export budget: charge retained page data plus the largest page's two f32 buffers instead of the whole document canvas, saturating on overflow. - Render each artboard from a document holding only its group, so overlapping boards no longer paint on each other's pages. One document shell is cloned and reused. - Tests: dense-page cancellation, labels with an empty middle name and all empty, overlapping artboard pixels, sparse 9000x9000 canvas, seven US Letter pages. --- crates/io/src/pdf.rs | 52 ++++++++----- crates/io/src/pdf/tests.rs | 127 ++++++++++++++++++++++++++++++- crates/io/src/pdf_import.rs | 123 +++++++++++++++++++++++++++++- crates/io/tests/it/pdf_import.rs | 53 +++++++------ 4 files changed, 308 insertions(+), 47 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 7bf228320f..86b03b565a 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -144,14 +144,16 @@ fn print_pdf_pages( out.extend_from_slice(b"\nendobj\n"); }; let n = pages.len(); - let selections_on = pages.iter().any(|p| p.page_label.is_some()); + // A label tree is written only for a non-empty name: an all-empty tree would be `/Nums []`, + // and filtering the first empty name away would start the tree at page index 1, not 0. + let labels_on = pages.iter().any(|p| p.page_label.as_deref().is_some_and(|label| !label.is_empty())); // 1 catalog, 2 pages, then per page: page, contents, image; then the shared font/ICC/selection. let font_obj = 3 + n * 3; let icc = first.image.icc.as_ref(); let icc_obj = icc.map(|_| font_obj + 1); let selection_base = font_obj + if icc.is_some() { 2 } else { 1 }; let selection_objects = selection_font.objects(selection_base); - let labels_obj = selections_on.then_some((selection_base + selection_objects.len()) as u32); + let labels_obj = labels_on.then_some((selection_base + selection_objects.len()) as u32); obj(&mut out, format!("<< /Type /Catalog /Pages 2 0 R{} >>", labels_obj.map(|o| format!(" /PageLabels {o} 0 R")).unwrap_or_default()).as_bytes()); let kids = (0..n).map(|i| format!("{} 0 R", 3 + i * 3)).collect::>().join(" "); obj(&mut out, format!("<< /Type /Pages /Kids [{kids}] /Count {n} >>").as_bytes()); @@ -226,10 +228,16 @@ fn print_pdf_pages( obj(&mut out, body); } if labels_obj.is_some() { + // Every page gets an entry: a number-tree range runs until the next key, so omitting an + // empty name would make that page inherit the previous page's label. An empty + // dictionary gives the page the default (decimal) label instead. let nums = pages .iter() .enumerate() - .filter_map(|(i, p)| p.page_label.as_deref().filter(|l| !l.is_empty()).map(|l| format!("{i} << /P {} >>", pdf_unicode_string(l)))) + .map(|(i, p)| match p.page_label.as_deref().filter(|label| !label.is_empty()) { + Some(label) => format!("{i} << /P {} >>", pdf_unicode_string(label)), + None => format!("{i} << >>"), + }) .collect::>() .join(" "); obj(&mut out, format!("<< /Nums [{nums}] >>").as_bytes()); @@ -315,6 +323,11 @@ fn collect_vectors(doc: &Document) -> (Vec<(usize, String)>, selection::Selectio (layers, selection_font) } +/// Pixels in `rect`, saturating on overflow. +fn rect_pixels(rect: photocraft_geom::Rect) -> u64 { + u64::from(rect.width()).saturating_mul(u64::from(rect.height())) +} + /// File › Save As / Save a Copy › PDF (#3401): the flattened document at its print size /// (pixels ÷ resolution × 72 pt). One page per artboard when the document has artboards, else one /// page for the whole document. Layers and transparency are dropped — the warning says so — and @@ -341,8 +354,13 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result if !artboards.is_empty() { // Every page's encoded pixels are kept until the PDF is assembled; bound that peak. const MAX_PDF_EXPORT_BYTES: u64 = 1 << 30; - let pixels: u64 = artboards.iter().map(|(_, _, a)| u64::from(a.rect.width()) * u64::from(a.rect.height())).sum(); - let estimate = pixels.saturating_mul(device as u64) + w as u64 * h as u64 * n as u64 * 4; + let page_pixels: u64 = artboards.iter().fold(0u64, |bytes, (_, _, a)| bytes.saturating_add(rect_pixels(a.rect))); + let retained = page_pixels.saturating_mul(device as u64); + // One page renders at a time: its f32 composite surface plus the region read back from + // it, both `n` channels at 4 bytes per pixel. The whole-document canvas is never held. + let largest = artboards.iter().map(|(_, _, a)| rect_pixels(a.rect)).max().unwrap_or(0); + let temporary = largest.saturating_mul(n as u64).saturating_mul(4).saturating_mul(2); + let estimate = retained.saturating_add(temporary); if estimate > MAX_PDF_EXPORT_BYTES { return Err(IoError::Unsupported(format!( "PDF export would need about {} MB for {} artboards; export them in smaller batches", @@ -350,6 +368,12 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result artboards.len() ))); } + // One document shell is reused for every page. Each page renders a document holding only + // its artboard group (the same isolation as `artboard_document`), so an overlapping board + // cannot paint on another board's page. Layer pixels are shared with `doc`; this one + // clone and the per-page group clone hold no new pixel buffers, but they are outside the + // 1 GiB estimate because they are not retained page data. + let mut one = doc.clone(); let mut pages = Vec::with_capacity(artboards.len()); for (id, name, artboard) in &artboards { ctl.check().map_err(|_| IoError::Cancelled)?; @@ -360,19 +384,13 @@ pub fn export(doc: &Document, ctl: &photocraft_raster::Interrupt) -> std::result } // A hidden artboard still gets its page, rendered from its own content rather than // left blank by the group's visibility. - let shown; - let doc = if doc.layer(*id).is_some_and(|l| !l.visible) { - let mut copy = doc.clone(); - if let Some(layer) = copy.layer_mut(*id) { - layer.visible = true; - } - shown = copy; - &shown - } else { - doc - }; + let Some(layer) = doc.layer(*id) else { continue }; + let mut group = layer.clone(); + group.visible = true; + one.layers.clear(); + one.layers.push(group); // Render only this artboard's rect; the surface never holds the whole document. - let surface = photocraft_compose::composite_to_surface(doc, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None); + let surface = photocraft_compose::composite_to_surface(&one, rect, PixelFormat::new(fmt.mode, fmt.sample, true), None); let values = surface.read_region(rect); let mut data = Vec::with_capacity((aw as usize * ah as usize).saturating_mul(device)); for px in values.chunks(n) { diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 6741fea346..247ab99192 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -1,8 +1,9 @@ //! PDF export: structure, pixel oracle, colour modes and refusal paths. use super::*; +use lopdf::{Object, StringFormat}; use photocraft_color::{PixelFormat, SampleType}; -use photocraft_doc::{Layer, LayerContent, Size}; +use photocraft_doc::{Artboard, Group, Layer, LayerContent, Size}; use photocraft_geom::Rect; use photocraft_raster::{Interrupt, Surface}; @@ -420,3 +421,127 @@ fn artboards_export_as_one_page_each() { } assert_eq!(out.bytes.windows(15).filter(|w| *w == b"/Subtype /Image").count(), 2); } + +/// Side-by-side 2x2 artboards at 72 dpi, named by `names` (empty names are kept). +fn artboard_doc(names: &[&str]) -> Document { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let width = (names.len() as u32).saturating_mul(2).max(2); + let mut d = Document::new("labels.pdf", Size { width, height: 2 }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 72.0; + for (index, name) in names.iter().enumerate() { + let x0 = (index as i32) * 2; + let rect = Rect::new(x0, 0, x0 + 2, 2); + let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, rect.y0, rect.x1, rect.y1, &[0.5, 0.5, 0.5, 1.0]))); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + d.layers.push(Layer::new(*name, LayerContent::Group(group))); + } + d +} + +/// The decompressed samples of page `id`'s first image XObject (`/Im0`). +fn page_image(pdf: &lopdf::Document, id: lopdf::ObjectId) -> Vec { + let page = pdf.get_dictionary(id).expect("page dictionary"); + let resources = page.get(b"Resources").expect("page resources").as_dict().expect("resources dictionary"); + let xobjects = resources.get(b"XObject").expect("xobjects").as_dict().expect("xobject dictionary"); + let image = xobjects.get(b"Im0").expect("Im0").as_reference().expect("image reference"); + pdf.get_object(image).expect("image object").as_stream().expect("image stream").decompressed_content().expect("image samples") +} + +/// A named artboard gives every page a `/PageLabels` entry, and an empty name gets an empty +/// label dictionary rather than inheriting the previous name. +#[test] +fn page_labels_name_every_page_and_an_empty_name_does_not_inherit() { + let d = artboard_doc(&["A", "", "C"]); + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; + check_structure(&pdf); + let parsed = lopdf::Document::load_mem(&pdf).unwrap(); + let labels = parsed + .catalog() + .unwrap() + .get(b"PageLabels") + .expect("a named artboard gives the PDF page labels") + .as_reference() + .expect("the label tree is an indirect object"); + let nums = parsed.get_dictionary(labels).unwrap().get(b"Nums").unwrap().as_array().unwrap(); + assert_eq!(nums.len(), 6, "one key and one label dictionary per page"); + for page in 0..3 { + assert_eq!(nums[page * 2].as_i64().unwrap(), page as i64, "the tree starts at page index 0 and covers every page"); + } + let label = |page: usize| nums[page * 2 + 1].as_dict().unwrap(); + assert_eq!(label(0).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x41], StringFormat::Hexadecimal), "page 1 is A"); + assert!(label(1).get(b"P").is_err(), "the empty name gets an empty dictionary, not A"); + assert_eq!(label(2).get(b"P").unwrap(), &Object::String(vec![0xFE, 0xFF, 0x00, 0x43], StringFormat::Hexadecimal), "page 3 is C"); + assert_eq!(parsed.get_pages().len(), 3); +} + +/// With no non-empty name there is no label tree at all: an empty `/Nums` would be invalid. +#[test] +fn an_all_empty_artboard_names_document_has_no_page_labels_tree() { + let d = artboard_doc(&["", "", ""]); + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; + check_structure(&pdf); + let parsed = lopdf::Document::load_mem(&pdf).unwrap(); + assert!(parsed.catalog().unwrap().get(b"PageLabels").is_err(), "no names means no /PageLabels"); + assert!(!has(&pdf, "/PageLabels")); + assert_eq!(parsed.get_pages().len(), 3, "the pages themselves are still written"); +} + +/// Two artboards at the same rectangle: each page must hold only its own board's pixels, not +/// the other board composited over it. +#[test] +fn overlapping_artboards_export_only_their_own_pixels() { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let mut d = Document::new("overlap.pdf", Size { width: 2, height: 2 }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 72.0; + for (name, color) in [("Red", [1.0, 0.0, 0.0, 1.0]), ("Blue", [0.0, 0.0, 1.0, 1.0])] { + let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, 0, 0, 2, 2, &color))); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(Rect::new(0, 0, 2, 2))), frame_stroke: None }; + d.layers.push(Layer::new(name, LayerContent::Group(group))); + } + let pdf = export(&d, &Interrupt::NONE).unwrap().bytes; + let parsed = lopdf::Document::load_mem(&pdf).unwrap(); + let pages = parsed.get_pages(); + let images = pages.values().map(|id| page_image(&parsed, *id)).collect::>(); + assert_eq!(images.len(), 2); + assert_eq!(images[0], [255u8, 0, 0].repeat(4), "the bottom board's page is red, not blue over red"); + assert_eq!(images[1], [0u8, 0, 255].repeat(4), "the top board's page is blue"); +} + +/// A large, mostly empty canvas must not be charged as if its whole area were rendered. +#[test] +fn sparse_canvas_artboards_export_without_a_false_memory_limit() { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + let mut d = Document::new("sparse.pdf", Size { width: 9000, height: 9000 }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 72.0; + for index in 0..2 { + let x0 = index * 10; + let rect = Rect::new(x0, 0, x0 + 2, 2); + let layer = Layer::new("Pixels", LayerContent::Raster(solid(fmt, rect.x0, 0, rect.x1, 2, &[1.0, 0.0, 0.0, 1.0]))); + let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + d.layers.push(Layer::new("Page", LayerContent::Group(group))); + } + let out = export(&d, &Interrupt::NONE).expect("two 2x2 boards on a 9000x9000 canvas must fit the export budget"); + let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); + assert_eq!(parsed.get_pages().len(), 2); +} + +/// Seven US Letter boards at 300 dpi with the importer's gaps: the pages are retained as encoded +/// data, but no whole-canvas buffer exists, so the old whole-canvas charge rejected this. +#[test] +fn seven_us_letter_artboards_export_without_a_false_memory_limit() { + const PAGE_W: u32 = 2550; + const PAGE_H: u32 = 3300; + const GAP: u32 = 80; + const PAGES: u32 = 7; + let mut d = Document::new("letters.pdf", Size { width: PAGES * PAGE_W + (PAGES - 1) * GAP, height: PAGE_H }, ColorMode::Rgb, SampleType::F32); + d.resolution_dpi = 300.0; + for index in 0..PAGES { + let x0 = (index * (PAGE_W + GAP)) as i32; + let rect = Rect::new(x0, 0, x0 + PAGE_W as i32, PAGE_H as i32); + let group = Group { children: Vec::new(), expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + d.layers.push(Layer::new(format!("Letter {}", index + 1), LayerContent::Group(group))); + } + let out = export(&d, &Interrupt::NONE).expect("seven US Letter pages at 300 dpi fit the export budget"); + let parsed = lopdf::Document::load_mem(&out.bytes).unwrap(); + assert_eq!(parsed.get_pages().len(), 7); +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index 79db591088..d4c8aa4eac 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -8,6 +8,9 @@ //! //! The renderer is pure Rust and runs on every desktop platform: no shared library is loaded //! or shipped, and a malformed file is reported as an error rather than taking the process down. +//! +//! Pages are drawn with the interpreter's default annotation settings, so annotations and +//! filled-in form fields are rendered; comments are not hidden. use crate::{ImportOptions, ImportResult, IoError}; #[cfg(not(target_arch = "wasm32"))] @@ -23,6 +26,12 @@ use photocraft_geom::{Rect, Size}; use photocraft_raster::Interrupt; #[cfg(not(target_arch = "wasm32"))] use photocraft_raster::Surface; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Arc; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(not(target_arch = "wasm32"))] +use std::time::Duration; /// `%PDF-` magic. `.ai` files that start with it are PDFs and render through this importer. pub fn is_pdf(bytes: &[u8]) -> bool { @@ -139,19 +148,26 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI"))); } let cache = RenderCache::new(); - let settings = InterpreterSettings::default(); let options = raster::Options { scale: [(dpi / 72.0) as f32; 2], size: Some([width, height]), offset: [0.0, 0.0], // PDF pages composite onto white, as every PDF viewer and the previous importer did. + // craft-pdf returns premultiplied RGBA8; an opaque background makes alpha 1, so the + // bytes below can be written as straight alpha. A transparent background would need + // un-premultiplying (dividing each colour by alpha) first. background: [255, 255, 255, 255], color_replacement: None, }; - let rendered = raster::render(page, &cache, &settings, &options).map_err(|error| render_error(page_number, dpi, error))?; + let rendered = render_page(page, &cache, &options, ctl).map_err(|error| render_error(page_number, dpi, error))?; if rendered.diagnostics.image_decode_failed { warnings.push(format!("PDF page {page_number}: an image could not be decoded and is missing")); } + // craft-pdf's hayro backend does not emit this flag yet (its README says so); keep the + // warning ready so a backend that starts reporting font substitution needs no change here. + if rendered.diagnostics.unsupported_font { + warnings.push(format!("PDF page {page_number}: a font could not be used and was substituted, so text may look different")); + } if rendered.diagnostics.content_truncated { warnings.push(format!("PDF page {page_number}: some content was omitted (a decode or memory limit)")); } @@ -187,6 +203,43 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } +/// Renders one page, forwarding `ctl`'s cancellation to craft-pdf while it interprets content. +/// +/// craft-pdf checks `InterpreterSettings::cancelled` between content operators, so a dense +/// vector page (CAD, maps) can be stopped part-way through. `Interrupt` is a borrowed callback +/// while the setting needs an owned flag, so a scoped watcher thread copies one into the other +/// every few milliseconds until the render returns. +#[cfg(not(target_arch = "wasm32"))] +fn render_page<'a>( + page: &'a craft_pdf::syntax::page::Page<'a>, + cache: &RenderCache<'a>, + options: &raster::Options, + ctl: &Interrupt, +) -> Result { + if ctl.cancelled() { + return Err(raster::Error::Cancelled); + } + let cancelled = Arc::new(AtomicBool::new(false)); + let finished = Arc::new(AtomicBool::new(false)); + let settings = InterpreterSettings { cancelled: Some(Arc::clone(&cancelled)), ..InterpreterSettings::default() }; + std::thread::scope(|scope| { + let flag = Arc::clone(&cancelled); + let done = Arc::clone(&finished); + let ctl = *ctl; + scope.spawn(move || { + while !done.load(Ordering::Relaxed) { + if ctl.cancelled() { + flag.store(true, Ordering::Relaxed); + } + std::thread::sleep(Duration::from_millis(5)); + } + }); + let rendered = raster::render(page, cache, &settings, options); + finished.store(true, Ordering::Relaxed); + rendered + }) +} + /// One page's raster width or height in pixels at `dpi`, at least one. #[cfg(not(target_arch = "wasm32"))] fn page_pixels(points: f64, dpi: f64) -> u32 { @@ -249,3 +302,69 @@ fn render_error(page: usize, dpi: f64, error: raster::Error) -> IoError { Error::InvalidOptions | Error::BufferLength => IoError::Unsupported(format!("PDF page {page} could not be rendered")), } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use std::sync::atomic::AtomicUsize; + + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; + + use super::*; + + /// A one-page PDF whose content stream is `operators` short strokes: rendering costs time + /// per operator, not per pixel. + fn dense_operator_pdf(operators: usize) -> Result, lopdf::Error> { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let mut content = String::with_capacity(operators.saturating_mul(24)); + content.push_str("0 0 1 RG 0.5 w\n"); + for i in 0..operators { + let x = (i % 200) as f32 * 0.5; + let y = ((i / 200) % 100) as f32 * 0.5; + content.push_str(&format!("{x:.1} {y:.1} m {:.1} {y:.1} l S\n", x + 0.4)); + } + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.into_bytes())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]), + "Contents" => content_id, + "Resources" => dictionary! {}, + }); + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(vec![Object::Reference(page_id)]), + "Count" => 1, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes)?; + Ok(bytes) + } + + /// Hundreds of thousands of path operators take far longer than the watcher's polling + /// interval, so the interrupt lands mid-render and the page reports Cancelled. + #[test] + fn a_dense_page_stops_when_the_interrupt_fires_mid_render() { + let pdf = dense_operator_pdf(300_000).expect("writing the dense PDF"); + let document = craft_pdf::open_slice_with_options(&pdf, None, &craft_pdf::OpenOptions::default()).expect("the dense PDF opens"); + let cache = RenderCache::new(); + let options = + raster::Options { scale: [1.0, 1.0], size: Some([200, 100]), offset: [0.0, 0.0], background: [255, 255, 255, 255], color_replacement: None }; + let polls = AtomicUsize::new(0); + // `render_page` checks once before spawning; the watcher then polls every 5 ms. Ten + // polls put the cancellation about 45 ms into a render that takes much longer. + let cancel = || polls.fetch_add(1, Ordering::SeqCst) >= 9; + let ctl = Interrupt::cancel_only(&cancel); + let error = match render_page(&document.pages()[0], &cache, &options, &ctl) { + Err(error) => error, + Ok(_) => panic!("the dense page rendered to completion before the interrupt fired"), + }; + assert!(matches!(render_error(1, 72.0, error), IoError::Cancelled), "the render error maps to Cancelled"); + assert!(polls.load(Ordering::SeqCst) >= 10, "the watcher must keep polling the interrupt"); + } +} diff --git a/crates/io/tests/it/pdf_import.rs b/crates/io/tests/it/pdf_import.rs index 95475ea200..b614f54c97 100644 --- a/crates/io/tests/it/pdf_import.rs +++ b/crates/io/tests/it/pdf_import.rs @@ -5,8 +5,7 @@ //! a blue rectangle sampled from the raster, and the renderer's side/pixel limits respected by //! lowering the effective DPI on a huge page. -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::{Duration, Instant}; +use std::sync::atomic::{AtomicBool, Ordering}; use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; use photocraft_doc::LayerContent; @@ -164,34 +163,34 @@ fn huge_pages_lower_the_effective_dpi_within_the_renderer_bounds() { assert!((print_width - 3000.0).abs() < 1.0, "print width {print_width:.1} pt should stay 3000 pt"); } -/// Cancelling on the last page check or the public boundary returns Cancelled, never a document. +/// Cancelling at the public boundary or between pages returns Cancelled, never a document. +/// +/// The renderer's watcher polls the interrupt while a page is being interpreted, so the number +/// of checks is not fixed any more; these triggers do not depend on counting them. #[test] -fn cancelling_on_the_last_checks_is_reported() { +fn cancelling_before_and_between_pages_is_reported() { let pdf = variant_pdf(); let options = ImportOptions { pdf_dpi: 72.0, ..Default::default() }; - let count = AtomicUsize::new(0); - let cancel = || { - count.fetch_add(1, Ordering::SeqCst); - false - }; - let ctl = Interrupt::cancel_only(&cancel); - let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl); - assert!(result.is_ok(), "uncancelled import failed: {:?}", result.err()); - let total = count.load(Ordering::SeqCst); - assert!(total >= 3, "a complete import should check cancellation at least three times, got {total}"); - for (label, threshold) in [("the last page check", total - 1), ("the public boundary check", total)] { - let seen = AtomicUsize::new(0); - let cancel = || seen.fetch_add(1, Ordering::SeqCst) + 1 >= threshold; - let ctl = Interrupt::cancel_only(&cancel); - let started = Instant::now(); - let result = import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl); - let elapsed = started.elapsed(); - assert_eq!(seen.load(Ordering::SeqCst), threshold, "cancelling on {label} should stop at check {threshold} of {total}"); - match result { - Err(IoError::Cancelled) => {} - Ok(_) => panic!("cancelling on {label} returned a document"), - Err(error) => panic!("cancelling on {label} returned {error:?}"), + + // The boundary check before dispatch: already cancelled. + let always = || true; + let ctl = Interrupt::cancel_only(&always); + match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) { + Err(IoError::Cancelled) => {} + other => panic!("an already-cancelled import returned {:?}", other.map(|_| ())), + } + + // The per-page loop's check: the first page's progress cancels the next iteration. + let cancelled = AtomicBool::new(false); + let cancel = || cancelled.load(Ordering::SeqCst); + let progress = |fraction: f32| { + if fraction > 0.0 { + cancelled.store(true, Ordering::SeqCst); } - assert!(elapsed < Duration::from_secs(10), "cancelling on {label} took {elapsed:?}"); + }; + let ctl = Interrupt::new(&cancel, &progress); + match import_with_options_and_interrupt("variants.pdf", &pdf, &options, &ctl) { + Err(IoError::Cancelled) => {} + other => panic!("cancelling after the first page returned {:?}", other.map(|_| ())), } } From 3ef91ec45af2e29aa1e4ff0e0471494aec88b8ba Mon Sep 17 00:00:00 2001 From: Triwarr <170976175+Triwarr@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:41:37 +0100 Subject: [PATCH 112/113] PDF: widen the dense-page cancellation margin Raise the synthetic page to a million strokes so the 45 ms watcher threshold keeps a wide margin on an optimised test build, and record why the importer keeps one RenderCache per page. --- crates/io/src/pdf_import.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index d4c8aa4eac..d55676ac16 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -147,6 +147,9 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS { return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI"))); } + // A cache per page, deliberately: a shared one would keep decoded images and fonts alive + // across up to 16 pages outside the pixel budget, and would hide an image-decode warning + // on a later page after the page that first hit it. let cache = RenderCache::new(); let options = raster::Options { scale: [(dpi / 72.0) as f32; 2], @@ -347,10 +350,11 @@ mod tests { } /// Hundreds of thousands of path operators take far longer than the watcher's polling - /// interval, so the interrupt lands mid-render and the page reports Cancelled. + /// interval, so the interrupt lands mid-render and the page reports Cancelled. A million + /// strokes leaves a wide margin even on a fast, optimised test build. #[test] fn a_dense_page_stops_when_the_interrupt_fires_mid_render() { - let pdf = dense_operator_pdf(300_000).expect("writing the dense PDF"); + let pdf = dense_operator_pdf(1_000_000).expect("writing the dense PDF"); let document = craft_pdf::open_slice_with_options(&pdf, None, &craft_pdf::OpenOptions::default()).expect("the dense PDF opens"); let cache = RenderCache::new(); let options = From fda05f7b02086c8c3b4d09d4bc1e95f3332e4d56 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 03:45:37 +0100 Subject: [PATCH 113/113] Regenerate docs/scorecard.md (merge queue) On main + #10448, so main's gate stays green after the merge. --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index bc6eba171c..7a0d30a8ce 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 195 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 196 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 195** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 196** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`.