From fce9f00414494e065cb78f38ab9c999233b3fbda Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 11 Oct 2026 17:39:10 +0200 Subject: [PATCH 01/73] History: History Options with Allow Non-Linear History and undoable visibility changes (#2966) History panel menu > History Options... in Photoshop has five options; this lands the two that don't need snapshots, as preferences (`historyOptions.*`, `prefs.set`, reported by `ui.inspect` under session.historyOptions) plus the dialog and a `history.options` command. - Allow Non-Linear History (default off): an edit after stepping back keeps the later states and is appended at the end (ops::History::non_linear); History panel Delete then removes only that state (History::remove / drop_current), the later ones stay. - Make Layer Visibility Changes Undoable (default on, as in Photoshop and PhotoCraft today): when off, the eye, Alt-click (Show Only), Hide/Show Layers change the document without a history state (Session::edit_visibility), leaving redo states alone. - history.options: with params sets them (validated, unknown keys and non-bools are errors); without params the GUI opens the History Options dialog (checkboxes, OK/Cancel). - New strings translated in all 16 catalogs. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/commands.rs | 6 +- crates/engine/src/extra_cmds.rs | 4 +- crates/engine/src/history_cmds.rs | 8 +- crates/engine/src/history_options_cmds.rs | 249 ++++++++++++++++++++++ crates/engine/src/inspect.rs | 2 + crates/engine/src/layer_multi_cmds.rs | 2 +- crates/engine/src/lib.rs | 29 ++- crates/engine/src/prefs.rs | 29 ++- crates/ops/src/lib.rs | 138 +++++++++++- crates/ui-egui/src/history_options_ui.rs | 98 +++++++++ crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 4 + docs/scorecard.md | 4 +- 29 files changed, 641 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/history_options_cmds.rs create mode 100644 crates/ui-egui/src/history_options_ui.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3d4b73f4d2..6a9491697c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -598,7 +598,10 @@ fn build() -> Vec { let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); // Clipping and channel changes reach the layers around it: recomposite everything. let local = p.get("clipped").is_none() && p.get("channels").is_none(); - s.edit(label, |doc, _| { + // The eye: a history state only with History Options › Make Layer Visibility + // Changes Undoable. + let record = !only_visibility || s.visibility_undoable(); + s.edit_with(label, record, |doc, _| { let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if let Some(v) = p.get("name").and_then(Value::as_str) { l.name = v.to_string(); @@ -1179,6 +1182,7 @@ fn build() -> Vec { v.extend(crate::analysis_cmds::specs()); v.extend(crate::notes_cmds::specs()); v.extend(crate::history_cmds::specs()); + v.extend(crate::history_options_cmds::specs()); v.extend(crate::proof_sim::specs()); v.extend(crate::presets::specs()); v.extend(crate::document_preset_cmds::specs()); diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index f25ea9a2e9..99a74c4b95 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -556,7 +556,7 @@ fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result { return crate::layer_multi_cmds::set_visible_selected(s, visible); } let id = layer_param(s, p)?; - s.edit(if visible { "Show Layer" } else { "Hide Layer" }, |doc, _| { + s.edit_visibility(if visible { "Show Layer" } else { "Hide Layer" }, |doc, _| { doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.visible = visible; Ok(()) })?; @@ -593,7 +593,7 @@ fn show_only(s: &mut Session, p: &Value) -> Result { let rows = walk.iter().map(|(p, _, l)| (p.clone(), before.as_ref().is_none_or(|b| b.get(&l.id).copied().unwrap_or(l.visible)))).collect(); ("Show Layers", rows, None) }; - s.edit(label, |doc, _| { + s.edit_visibility(label, |doc, _| { for (p, visible) in &rows { if let Some(l) = doc.layer_at_mut(p) { l.visible = *visible; diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index d9ca98f962..aa8f2bb29c 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -30,7 +30,7 @@ fn state_index(s: &Session, cmd: &str, p: &Value) -> Result<(usize, usize)> { } /// History panel › Delete: drop the state and every state after it, as Photoshop does in linear -/// history. The document returns to the state before it, and the deleted steps can't be redone. +/// history (in non-linear history only that state, `history_options_cmds::delete_state`). The document returns to the state before it, and the deleted steps can't be redone. /// The oldest state (the document as opened) can't be deleted. fn delete_state(s: &mut Session, p: &Value) -> Result { const CMD: &str = "history.deleteState"; @@ -38,6 +38,12 @@ fn delete_state(s: &mut Session, p: &Value) -> Result { if i == 0 { return Err(bad(CMD, "the oldest state can't be deleted")); } + // History Options › Allow Non-Linear History: only that state goes. + if s.active().is_some_and(|st| st.history.non_linear) { + crate::history_options_cmds::delete_state(s, i, current)?; + let entries = s.active().ok_or(EngineError::NoDocument)?.history.entries(); + return Ok(json!({ "states": entries.len(), "current": entries.last() })); + } // Step back to the state before `i`; the steps from `i` on are then redo states. for _ in i..=current { if !s.undo() { diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs new file mode 100644 index 0000000000..b76127f25f --- /dev/null +++ b/crates/engine/src/history_options_cmds.rs @@ -0,0 +1,249 @@ +//! History panel › History Options… (#2966): Allow Non-Linear History and Make Layer Visibility +//! Changes Undoable. The values are preferences (`historyOptions.*`, also `prefs.set`), applied +//! by [`Session::apply_prefs`] and [`Session::edit_visibility`]. Without params the command +//! reports them; the GUI opens its dialog instead and runs it with the dialog's values on OK. +//! +//! Photoshop's three snapshot options (Automatically Create First Snapshot, Automatically +//! Create New Snapshot When Saving, Show New Snapshot Dialog by Default) are not here: snapshots +//! are not implemented, and a checkbox that does nothing is worse than a missing one. + +use serde_json::{Map, Value}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "history.options"; + +/// The option keys, as in `prefs.get historyOptions` and the command's params. +pub const OPTIONS: [&str; 2] = ["allowNonLinearHistory", "makeLayerVisibilityChangesUndoable"]; + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } +} + +/// The current History Options as `{allowNonLinearHistory, makeLayerVisibilityChangesUndoable}`. +pub fn current(s: &Session) -> Value { + let o = &s.prefs().history_options; + serde_json::json!({ + "allowNonLinearHistory": o.allow_non_linear_history, + "makeLayerVisibilityChangesUndoable": o.make_layer_visibility_changes_undoable, + }) +} + +fn options(s: &mut Session, p: &Value) -> Result { + let given: Map = match p { + Value::Null => Map::new(), + Value::Object(m) => m.clone(), + _ => return Err(bad("params must be an object")), + }; + // Validate everything before changing anything. + let mut set = Vec::new(); + for (k, v) in &given { + if !OPTIONS.contains(&k.as_str()) { + return Err(bad(format!("unknown option `{k}` (expected {})", OPTIONS.join(", ")))); + } + let b = v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false")))?; + set.push((k.clone(), b)); + } + if !set.is_empty() { + s.edit_prefs(|prefs| { + for (k, b) in &set { + match k.as_str() { + "allowNonLinearHistory" => prefs.history_options.allow_non_linear_history = *b, + _ => prefs.history_options.make_layer_visibility_changes_undoable = *b, + } + } + }); + } + Ok(current(s)) +} + +/// History panel › Delete in non-linear history: delete state `i` (indexed like +/// [`photocraft_ops::History::entries`], `current` = the current state's index) and nothing +/// else. Deleting the current state steps back to the one before it; the later states stay. +pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result<()> { + if i == 0 { + return Err(EngineError::BadParams { cmd: "history.deleteState".into(), msg: "the oldest state can't be deleted".into() }); + } + // A background job is computing from the current state: it must not move under it. + if s.active_job().is_some() { + return Err(EngineError::Other("the history can't step back right now".into())); + } + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + st.coalesce = None; + if i < current { + if !st.history.remove(i) { + return Err(EngineError::Other(format!("state {i} is not held"))); + } + // The document is unchanged, but the History panel's rows are not. + st.revision += 1; + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + return Ok(()); + } + let (mut d, layers) = st.history.drop_current().ok_or_else(|| EngineError::Other("the history can't step back right now".into()))?; + // As Undo does: Save As changes file identity outside history. + if d.name != st.doc.name { + std::sync::Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = crate::layer_multi_cmds::step_damage(&d, &st.doc); + st.doc = d; + crate::restore_target(st, layers); + st.revision += 1; + st.last_damage = damage; + Ok(()) +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: CMD, + label: "History Options…", + menu: &[], + shortcut: None, + params: r##"{"allowNonLinearHistory":bool?,"makeLayerVisibilityChangesUndoable":bool?} → both values (no params: report them). Allow Non-Linear History: an edit after stepping back keeps the later states and is appended at the end; deleting a state deletes only it (default off). Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state (default on). Also `prefs.set historyOptions.*`"##, + enabled: always, + run: options, + journal: false, + }] +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn entries(s: &Session) -> Vec { + s.active().unwrap().history.entries() + } + + /// A document with a layer above the background: entries Open, New Layer. + fn doc() -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + (s, id) + } + + #[test] + fn defaults_match_photoshop_and_round_trip_through_prefs() { + let mut s = Session::new(); + assert_eq!(s.execute(CMD, json!({})).unwrap(), json!({"allowNonLinearHistory": false, "makeLayerVisibilityChangesUndoable": true})); + assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions"})).unwrap(), current(&s)); + let r = s.execute(CMD, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})).unwrap(); + assert_eq!(r, json!({"allowNonLinearHistory": true, "makeLayerVisibilityChangesUndoable": false})); + assert_eq!(s.execute("prefs.get", json!({"path": "historyOptions.allowNonLinearHistory"})).unwrap(), json!(true)); + // Saved and restored with the other preferences. + let saved = s.prefs_to_json(); + let mut t = Session::new(); + t.load_prefs_json(&saved).unwrap(); + assert_eq!(current(&t), r); + // prefs.set and prefs.reset reach them too. + t.execute("prefs.set", json!({"path": "historyOptions.allowNonLinearHistory", "value": false})).unwrap(); + assert_eq!(t.execute(CMD, Value::Null).unwrap()["allowNonLinearHistory"], json!(false)); + t.execute("prefs.reset", json!({"path": "historyOptions"})).unwrap(); + assert_eq!(current(&t), current(&Session::new())); + // Older preference files without the section load with the defaults. + t.load_prefs_json("{}").unwrap(); + assert_eq!(current(&t), current(&Session::new())); + } + + #[test] + fn bad_params_are_refused_and_change_nothing() { + let mut s = Session::new(); + let before = current(&s); + for p in [ + json!({"allowNonLinearHistory": "yes"}), + json!({"allowNonLinearHistory": 1}), + json!({"makeLayerVisibilityChangesUndoable": null}), + json!({"allowNonLinearHistory": true, "snapshots": true}), + json!([true]), + json!("x"), + json!(3), + ] { + assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); + assert_eq!(current(&s), before, "{p} changed nothing"); + } + assert!(s.execute("prefs.set", json!({"path": "historyOptions.allowNonLinearHistory", "value": "on"})).is_err()); + assert_eq!(current(&s), before); + } + + #[test] + fn layer_visibility_is_a_history_state_only_when_undoable() { + // On (the default): the eye, Hide/Show Layers and ⌥-click each add a state. + let (mut s, id) = doc(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert_eq!(entries(&s).last().map(String::as_str), Some("Layer Visibility")); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().visible); + + // Off: the document changes (and is modified) but History doesn't. + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + let before = entries(&s); + let rev = s.active().unwrap().revision; + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("layer.showLayers", json!({"layer": id})).unwrap(); + s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); + s.execute("layer.showOnly", json!({"layer": id})).unwrap(); + s.execute("layer.showOnly", json!({"layer": id})).unwrap(); + s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); + assert_eq!(entries(&s), before, "no visibility state was recorded"); + let st = s.active().unwrap(); + assert!(!st.doc.layer(photocraft_doc::LayerId(id)).unwrap().visible, "the change still applies"); + assert!(st.revision > rev && st.is_dirty()); + // Other properties still record a state. + s.execute("layer.setProps", json!({"layer": id, "opacity": 0.5})).unwrap(); + assert_eq!(entries(&s).len(), before.len() + 1); + // An unrecorded change leaves the redo states alone. + s.execute("edit.undo", json!({})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + assert!(s.active().unwrap().history.can_redo()); + } + + #[test] + fn non_linear_history_keeps_later_states_and_delete_removes_only_one() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + for c in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + let filled = entries(&s); + assert_eq!(filled.len(), 4); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let after = entries(&s); + assert_eq!(after.len(), 5, "the two later fills are kept: {after:?}"); + assert_eq!(after[..4], filled[..]); + // Delete the second fill only: the states after it stay. + s.execute("history.deleteState", json!({"state": 2})).unwrap(); + let mut expected = after.clone(); + expected.remove(2); + assert_eq!(entries(&s), expected); + // Deleting the current state steps back to the one before; nothing else goes. + let doc_before = s.active().unwrap().history.state(expected.len() - 2).unwrap(); + s.execute("history.deleteState", json!({})).unwrap(); + assert_eq!(entries(&s), expected[..expected.len() - 1].to_vec()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &doc_before)); + // After stepping back, deleting the current state keeps the later (redo) states. + s.execute("edit.undo", json!({})).unwrap(); + let redo: Vec = s.active().unwrap().history.redo_labels().map(str::to_string).collect(); + s.execute("history.deleteState", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.redo_labels().map(str::to_string).collect::>(), redo); + + // Turning it off applies to open documents: the next edit after stepping back discards. + s.execute(CMD, json!({"allowNonLinearHistory": false})).unwrap(); + assert!(!s.active().unwrap().history.non_linear); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + assert!(!s.active().unwrap().history.can_redo()); + // New documents pick the option up too. + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert!(s.active().unwrap().history.non_linear); + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 1d1c7e0c72..1387b82da7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -19,6 +19,8 @@ pub fn session(s: &Session) -> Value { })).collect::>(), "foreground": s.tools.foreground, "background": s.tools.background, + // History panel › History Options… (`history.options`). + "historyOptions": crate::history_options_cmds::current(s), }) } diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 27424e41ba..74237713fd 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -1293,7 +1293,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul /// Show/hide every selected layer in one step. pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { let sel = selected(s); - s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { + s.edit_visibility(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { for id in &sel { doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1fffd0bdc1..2884b5cd30 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,6 +51,7 @@ pub mod group_view_cmds; pub mod guide_layout; pub mod hidden_target; pub mod history_cmds; +pub mod history_options_cmds; pub mod image_cmds; pub mod inspect; pub mod jobs; @@ -478,6 +479,7 @@ impl Session { let mut st = DocState::new(doc, path); st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); + st.history.non_linear = self.prefs.get().history_options.allow_non_linear_history; self.docs.push(st); let i = self.docs.len() - 1; self.active = Some(i); @@ -576,6 +578,25 @@ impl Session { /// Apply an undoable edit to the active document. pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + self.edit_with(label, true, f) + } + + /// Apply a change of layer visibility (and nothing else): a history state when History + /// Options › Make Layer Visibility Changes Undoable is on (the default, as in Photoshop), + /// otherwise the document changes without one, so the History panel and Undo skip it. + pub fn edit_visibility(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + let record = self.visibility_undoable(); + self.edit_with(label, record, f) + } + + /// History Options › Make Layer Visibility Changes Undoable. + pub fn visibility_undoable(&self) -> bool { + self.prefs().history_options.make_layer_visibility_changes_undoable + } + + /// [`Self::edit`], recording a history state only when `record` is set. An unrecorded change + /// still marks the document modified and leaves the redo states alone. + pub(crate) fn edit_with(&mut self, label: &str, record: bool, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { let restrict = self.color_restrict; let sampler_map = self.sampler_map.take(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; @@ -621,14 +642,18 @@ impl Session { let key = self.coalesce_request.clone(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; let layers = st.layer_target(); - if key.is_none() || st.coalesce != key || !st.history.can_undo() { + if !record { + // Nothing to coalesce with: the next recorded step starts a state of its own. + st.coalesce = None; + } else if key.is_none() || st.coalesce != key || !st.history.can_undo() { st.history.set_current_layers(prior); st.history.record(label, before, layers); st.history.trim(&st.doc); + st.coalesce = key; } else { st.history.set_current_layers(layers); + st.coalesce = key; } - st.coalesce = key; st.revision += 1; st.last_damage = unchanged.then_some(photocraft_geom::Rect::EMPTY); self.samplers_removed += samplers_removed; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index eb8151508f..51cab78f91 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -12,8 +12,9 @@ //! OS config directory; the web shell: browser storage) and restore it with //! [`Session::load_prefs_json`]. //! -//! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit (every -//! open document), the effect-cache memory budget, and units for commands that report lengths. +//! Engine-side values are applied by [`Session::apply_prefs`]: the history state limit and +//! History Options › Allow Non-Linear History (every open document), the effect-cache memory +//! budget, and units for commands that report lengths. //! Colour settings (`colorSettings`) are stored with the colour state //! ([`crate::color_cmds::ColorSettings`]) and persisted in the same document. @@ -892,6 +893,24 @@ impl Default for Integrations { } } +/// The History panel's History Options… (not part of Edit › Preferences in Photoshop either). +/// Photoshop's snapshot options are not here yet: snapshots are not implemented. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct HistoryOptions { + /// Allow Non-Linear History: editing after selecting an earlier state keeps the later + /// states (the new step is appended at the end), and deleting a state deletes only it. + pub allow_non_linear_history: bool, + /// Make Layer Visibility Changes Undoable: showing or hiding a layer is a history state. + pub make_layer_visibility_changes_undoable: bool, +} + +impl Default for HistoryOptions { + fn default() -> Self { + Self { allow_non_linear_history: false, make_layer_visibility_changes_undoable: true } + } +} + /// Edit › Menus: hidden items and item colours, by command id. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -932,6 +951,8 @@ pub struct Preferences { pub enhanced_controls: EnhancedControls, pub raw_defaults: RawDefaults, pub integrations: Integrations, + /// History panel › History Options… (`history.options`). + pub history_options: HistoryOptions, /// Edit › Keyboard Shortcuts: command id → shortcut (`Cmd+Shift+N` notation); an empty /// string removes the default shortcut. pub shortcuts: BTreeMap, @@ -1445,14 +1466,16 @@ impl Session { } /// Push engine-relevant preferences into live state: every document's history limit and - /// the layer-effect cache budget. + /// linearity, and the layer-effect cache budget. pub fn apply_prefs(&mut self) { let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_budget_bytes(); let budget = self.prefs().performance.effect_cache_mb as usize; + let non_linear = self.prefs().history_options.allow_non_linear_history; for st in &mut self.docs { st.history.max_states = n; st.history.max_bytes = bytes; + st.history.non_linear = non_linear; st.history.trim(&st.doc); } photocraft_compose::set_effect_cache_budget(budget << 20); diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 0f29cf8e98..1af3468fb0 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -50,6 +50,10 @@ pub struct History { current_label: String, /// The layers targeted when the current document was created (opened or edited). current_layers: LayerTarget, + /// History Options › Allow Non-Linear History: a step recorded while later states exist + /// (after stepping back) keeps them and goes to the end of the list, instead of discarding + /// them; see [`History::record`] and [`History::remove`]. + pub non_linear: bool, } impl Default for History { @@ -68,11 +72,17 @@ impl History { max_bytes: 0, current_label: "Open".into(), current_layers: LayerTarget::default(), + non_linear: false, } } /// Record that `before` was replaced by a new current document via step `label`, which left /// `layers` targeted. + /// + /// Linear history (the default) discards the redo states, as Photoshop does when you edit + /// after selecting an earlier state. With [`History::non_linear`] they are kept: the list + /// reads `…, before, the former redo states (oldest first), the new step`, so the new step is + /// appended at the end and every earlier state can still be stepped to. pub fn record(&mut self, label: impl Into, before: Arc, layers: LayerTarget) { if self.max_bytes == 0 { self.tiles = None; @@ -83,7 +93,15 @@ impl History { let prev_label = std::mem::replace(&mut self.current_label, label.into()); let prev_layers = std::mem::replace(&mut self.current_layers, layers); self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers }); - self.clear_redo(); + if self.non_linear { + // `redo` holds the next state last; the list order is oldest first. Their tiles stay + // counted: they only move from the redo side to the undo side. + while let Some(state) = self.redo.pop() { + self.undo.push_back(state); + } + } else { + self.clear_redo(); + } while self.undo.len() > self.max_states { if let Some(state) = self.undo.pop_front() && let Some(tiles) = &mut self.tiles @@ -175,6 +193,35 @@ impl History { true } + /// Delete the past state at entry `i` (indexed like [`History::entries`]) and nothing else, + /// as the History panel's Delete does in non-linear history. The current state is not held + /// here (the session steps back first) and the oldest state can't be removed this way + /// either, since every later state would lose its starting point in the list. Returns + /// whether a state was removed. + pub fn remove(&mut self, i: usize) -> bool { + if i == 0 { + return false; + } + let Some(state) = self.undo.remove(i) else { return false }; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&state.doc); + } + true + } + + /// Step back like [`History::undo`] but drop the current document instead of making it + /// redoable: the current state is deleted while the redo states (later states in the + /// list) stay. Returns the document to make current and the layers it targeted. + pub fn drop_current(&mut self) -> Option<(Arc, LayerTarget)> { + let prev = self.undo.pop_back()?; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&prev.doc); + } + self.current_label = prev.label; + self.current_layers = prev.layers.clone(); + Some((prev.doc, prev.layers)) + } + /// Forget the redo states, e.g. after undoing half of a compound step that failed. pub fn clear_redo(&mut self) { if let Some(tiles) = &mut self.tiles { @@ -348,6 +395,95 @@ mod tests { assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); } + /// Open, A, B, C, then two steps back: A is current, B and C are redo states. + fn stepped_back(non_linear: bool) -> (History, Arc) { + let mut h = History { non_linear, ..History::default() }; + let mut cur = Arc::new(base()); + for n in ["A", "B", "C"] { + edit(&mut h, &mut cur, n, |d| d.name = n.to_lowercase()); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.name, "a"); + (h, cur) + } + + #[test] + fn non_linear_history_keeps_later_states_and_appends_the_new_step() { + let (mut h, mut cur) = stepped_back(true); + edit(&mut h, &mut cur, "D", |d| d.name = format!("{}+d", d.name)); + assert_eq!(h.entries(), ["Open", "A", "B", "C", "D"], "B and C are kept, D goes to the end"); + assert!(!h.can_redo()); + assert_eq!(cur.name, "a+d", "D was made from the state selected (A), not from C"); + // Stepping back walks the list: C, B, A, Open, each with its own document. + let mut names = Vec::new(); + while let Some((d, _)) = h.undo(cur.clone()) { + cur = d; + names.push(cur.name.clone()); + } + assert_eq!(names, ["c", "b", "a", "h"]); + // Linear history (the default) discards them. + let (mut h, mut cur) = stepped_back(false); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.entries(), ["Open", "A", "D"]); + } + + #[test] + fn non_linear_steps_respect_the_state_limit_and_the_tile_counter() { + let mut h = History::new(3); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for i in 0..4 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "branch", |d| d.name = "branch".into()); + assert_eq!(h.past_len(), 3, "the oldest states beyond the limit go"); + assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3", "branch"]); + assert_counter(&h, &cur); + } + + #[test] + fn remove_deletes_one_past_state_and_drop_current_keeps_the_redo_states() { + let (mut h, _) = stepped_back(true); + assert!(!h.remove(0), "the oldest state stays"); + assert!(!h.remove(1), "the current state (A) is not held"); + assert!(!h.remove(99)); + let (mut h, mut cur) = stepped_back(true); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert!(h.remove(1)); + assert_eq!(h.entries(), ["Open", "B", "C", "D"]); + assert_eq!(h.state(1).unwrap().name, "b", "each state keeps its own document"); + // Deleting the current state: the one before becomes current, the later ones stay. + let (mut h, _) = stepped_back(true); + let (d, _) = h.drop_current().unwrap(); + assert_eq!(d.name, "h"); + assert_eq!(h.entries(), ["Open"]); + assert_eq!(h.redo_labels().collect::>(), ["B", "C"]); + assert!(h.drop_current().is_none(), "nothing before Open"); + // The tile counter follows both. + let mut h = History::new(50); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for i in 0..4 { + edit(&mut h, &mut cur, "Paint", |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + assert!(h.remove(2)); + assert_counter(&h, &cur); + cur = h.drop_current().unwrap().0; + assert_counter(&h, &cur); + } + #[test] fn max_states_bound() { let mut h = History::new(3); diff --git a/crates/ui-egui/src/history_options_ui.rs b/crates/ui-egui/src/history_options_ui.rs new file mode 100644 index 0000000000..2d4756543b --- /dev/null +++ b/crates/ui-egui/src/history_options_ui.rs @@ -0,0 +1,98 @@ +//! The History Options dialog (History panel menu › History Options…, #2966): a form over the +//! engine's `history.options` with its two checkboxes, filled with the current values. OK runs +//! the command with the dialog's values (the generic command-dialog confirm), Cancel changes +//! nothing. Agents can also run `history.options` with params directly, or `prefs.set +//! historyOptions.*`; a call with params skips the dialog. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::DialogKind; + +pub const COMMAND: &str = "history.options"; + +/// Opens the dialog for a parameterless `history.options`; anything else is not handled here. +pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option> { + if id != COMMAND || params.as_object().is_some_and(|m| m.keys().any(|k| !k.starts_with("__"))) { + return None; + } + Some(Ok(json!({ "dialog": open(app) }))) +} + +/// Open the dialog on the current options; returns its id. +pub fn open(app: &mut PhotocraftApp) -> u64 { + let current = photocraft_engine::history_options_cmds::current(&app.session); + let mut f = Map::new(); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("History Options…")); + f.insert("__form".into(), json!(true)); + f.insert("__choices".into(), json!({})); + // Photoshop's capitalised labels, in the UI language (the form would sentence-case the keys). + f.insert( + "__labels".into(), + json!({ + "allowNonLinearHistory": tl!("Allow Non-Linear History"), + "makeLayerVisibilityChangesUndoable": tl!("Make Layer Visibility Changes Undoable"), + }), + ); + for key in photocraft_engine::history_options_cmds::OPTIONS { + f.insert(key.into(), current.get(key).cloned().unwrap_or(Value::Bool(false))); + } + app.ui.open_dialog(DialogKind::Command, f) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> PhotocraftApp { + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) + } + + #[test] + fn the_command_opens_the_dialog_on_the_current_values_and_ok_applies_them() { + let mut app = app(); + let ctx = egui::Context::default(); + let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap(); + assert_eq!(d.fields["allowNonLinearHistory"], json!(false)); + assert_eq!(d.fields["makeLayerVisibilityChangesUndoable"], json!(true)); + assert_eq!(crate::dialogs::title(d), "History Options"); + // Cancel changes nothing. + app.ui.dialog_mut(id).unwrap().fields.insert("allowNonLinearHistory".into(), json!(true)); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(!app.session.prefs().history_options.allow_non_linear_history); + // OK applies both checkboxes. + let id = open(&mut app); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("allowNonLinearHistory".into(), json!(true)); + fields.insert("makeLayerVisibilityChangesUndoable".into(), json!(false)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let o = &app.session.prefs().history_options; + assert!(o.allow_non_linear_history && !o.make_layer_visibility_changes_undoable); + assert!(app.ui.dialogs.is_empty()); + // Reopened, it shows what was chosen; with params the command runs without a dialog. + let id = open(&mut app); + assert_eq!(app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["allowNonLinearHistory"], json!(true)); + crate::dialogs::cancel(&mut app, id).unwrap(); + let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"allowNonLinearHistory": false})).unwrap(); + assert_eq!(r["allowNonLinearHistory"], json!(false)); + assert!(app.ui.dialogs.is_empty()); + assert!(crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"allowNonLinearHistory": "no"})).is_err()); + } + + #[test] + fn the_dialog_draws_both_checkboxes_with_photoshops_labels() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(700.0, 400.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut()); + h.run_steps(3); + h.get_by_label("History Options"); + h.get_by_label("Allow Non-Linear History"); + h.get_by_label("Make Layer Visibility Changes Undoable"); + h.get_by_label("OK"); + h.get_by_label("Cancel"); + } +} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 93f8fd5956..c13c128785 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2584,3 +2584,8 @@ cameraData Lens Objektiv Click to place · Alt-click or drag off-canvas to remove Kliknutím umístíte · Alt-kliknutím nebo přetažením mimo plátno odeberete No document open Není otevřen žádný dokument {n} of {max} sample points {n} z {max} bodů měření + +# History panel › History Options… (#2966) + History Options… Volby historie… + Allow Non-Linear History Povolit nelineární historii + Make Layer Visibility Changes Undoable Umožnit vrácení změn viditelnosti vrstev diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 26871a1e68..c720a1f4c6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2615,3 +2615,8 @@ cameraData Lens Objektiv Click to place · Alt-click or drag off-canvas to remove Klicken zum Platzieren · Alt-Klick oder Ziehen außerhalb der Arbeitsfläche zum Entfernen No document open Kein Dokument geöffnet {n} of {max} sample points {n} von {max} Messpunkten + +# History panel › History Options… (#2966) + History Options… Protokolloptionen… + Allow Non-Linear History Nicht-lineare Protokolle zulassen + Make Layer Visibility Changes Undoable Änderungen der Ebenensichtbarkeit widerrufbar machen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index dc39a34150..b42c253b27 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3675,3 +3675,8 @@ cameraData Lens Φακός # Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Κλικ για τοποθέτηση · Alt-κλικ ή σύρσιμο εκτός καμβά για αφαίρεση {n} of {max} sample points {n} από {max} σημεία δειγματοληψίας + +# History panel › History Options… (#2966) + History Options… Επιλογές ιστορικού… + Allow Non-Linear History Να επιτρέπεται μη γραμμικό ιστορικό + Make Layer Visibility Changes Undoable Οι αλλαγές ορατότητας επιπέδων να αναιρούνται diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c65d4dd089..e530ae6966 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2656,3 +2656,8 @@ cameraData Lens Objetivo Click to place · Alt-click or drag off-canvas to remove Clic para colocar · Alt-clic o arrastrar fuera del lienzo para quitar No document open Ningún documento abierto {n} of {max} sample points {n} de {max} puntos de muestreo + +# History panel › History Options… (#2966) + History Options… Opciones de historia… + Allow Non-Linear History Permitir historia no lineal + Make Layer Visibility Changes Undoable Permitir deshacer los cambios de visibilidad de capas diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6a20c3521b..c0b26c4170 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2993,3 +2993,8 @@ cameraData Lens Objectif Click to place · Alt-click or drag off-canvas to remove Cliquez pour placer · Alt-clic ou glisser hors du canevas pour supprimer No document open Aucun document ouvert {n} of {max} sample points {n} sur {max} points d'échantillonnage + +# History panel › History Options… (#2966) + History Options… Options d'historique… + Allow Non-Linear History Autoriser l'historique non linéaire + Make Layer Visibility Changes Undoable Permettre d'annuler les changements de visibilité des calques diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9f1b970db2..e97c9155e3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2980,3 +2980,8 @@ cameraData Lens Lensa Click to place · Alt-click or drag off-canvas to remove Klik untuk menempatkan · Alt-klik atau seret ke luar kanvas untuk menghapus No document open Tidak ada dokumen yang terbuka {n} of {max} sample points {n} dari {max} titik sampel + +# History panel › History Options… (#2966) + History Options… Opsi Riwayat… + Allow Non-Linear History Izinkan Riwayat Non-Linier + Make Layer Visibility Changes Undoable Perubahan Visibilitas Layer Dapat Diurungkan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4924ecfc71..d7d5adc00d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2647,3 +2647,8 @@ cameraData Lens Obiettivo Click to place · Alt-click or drag off-canvas to remove Fai clic per posizionare · Alt-clic o trascina fuori dalla tela per rimuovere No document open Nessun documento aperto {n} of {max} sample points {n} di {max} punti di campionamento + +# History panel › History Options… (#2966) + History Options… Opzioni cronologia… + Allow Non-Linear History Consenti cronologia non lineare + Make Layer Visibility Changes Undoable Rendi annullabili le modifiche di visibilità dei livelli diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index be6169e806..896ad7ede8 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3590,3 +3590,8 @@ cameraData Lens レンズ Click to place · Alt-click or drag off-canvas to remove クリックで配置 · Alt キーを押しながらクリック、またはカンバス外へドラッグで削除 No document open ドキュメントが開かれていません {n} of {max} sample points {max} 個中 {n} 個のサンプルポイント + +# History panel › History Options… (#2966) + History Options… ヒストリーオプション… + Allow Non-Linear History 非線形のヒストリーを許可 + Make Layer Visibility Changes Undoable レイヤーの表示/非表示の変更を取り消し可能にする diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index b9ee70a4e1..f608c7f9b1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3159,3 +3159,8 @@ cameraData Lens 렌즈 Click to place · Alt-click or drag off-canvas to remove 클릭하여 배치 · Alt-클릭 또는 캔버스 밖으로 드래그하여 제거 No document open 열린 문서 없음 {n} of {max} sample points {max}개 중 {n}개의 샘플 지점 + +# History panel › History Options… (#2966) + History Options… 작업 내역 옵션… + Allow Non-Linear History 비선형 작업 내역 허용 + Make Layer Visibility Changes Undoable 레이어 표시 여부 변경을 실행 취소할 수 있게 하기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 00d793cbf5..9f1362d2e6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3741,3 +3741,8 @@ cameraData Lens Lens # Color Sampler (added with the i18n coverage repair) Click to place · Alt-click or drag off-canvas to remove Klik om te plaatsen · Alt-klik of sleep buiten het canvas om te verwijderen {n} of {max} sample points {n} van {max} steekproefpunten + +# History panel › History Options… (#2966) + History Options… Geschiedenisopties… + Allow Non-Linear History Niet-lineaire geschiedenis toestaan + Make Layer Visibility Changes Undoable Wijzigingen in laagzichtbaarheid ongedaan kunnen maken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d6018ec9a3..e1bf6b260b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3591,3 +3591,8 @@ cameraData Lens Obiektyw Click to place · Alt-click or drag off-canvas to remove Kliknij, aby umieścić · Alt-kliknij lub przeciągnij poza obszar roboczy, aby usunąć No document open Brak otwartego dokumentu {n} of {max} sample points {n} z {max} punktów próbkowania + +# History panel › History Options… (#2966) + History Options… Opcje historii… + Allow Non-Linear History Zezwalaj na nieliniową historię + Make Layer Visibility Changes Undoable Pozwalaj cofać zmiany widoczności warstw diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1f89561a32..35a7caa8ce 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3000,3 +3000,8 @@ cameraData Lens Lente Click to place · Alt-click or drag off-canvas to remove Clique para posicionar · Alt-clique ou arraste para fora da tela para remover No document open Nenhum documento aberto {n} of {max} sample points {n} de {max} pontos de amostragem + +# History panel › History Options… (#2966) + History Options… Opções do histórico… + Allow Non-Linear History Permitir histórico não linear + Make Layer Visibility Changes Undoable Permitir desfazer alterações de visibilidade das camadas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 25e240377b..448446f8eb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2922,3 +2922,8 @@ cameraData Lens Объектив Click to place · Alt-click or drag off-canvas to remove Щёлкните, чтобы разместить · Alt-щелчок или перетаскивание за пределы холста для удаления No document open Документ не открыт {n} of {max} sample points {n} из {max} точек замера + +# History panel › History Options… (#2966) + History Options… Параметры истории… + Allow Non-Linear History Разрешить нелинейную историю + Make Layer Visibility Changes Undoable Разрешить отмену изменений видимости слоёв diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a28efb4a5f..b6b6589a6f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3678,3 +3678,8 @@ cameraData Lens Об'єктив Click to place · Alt-click or drag off-canvas to remove Клацніть, щоб розмістити · Alt-клацання або перетягування за межі полотна для видалення No document open Документ не відкрито {n} of {max} sample points {n} з {max} точок вимірювання + +# History panel › History Options… (#2966) + History Options… Параметри історії… + Allow Non-Linear History Дозволити нелінійну історію + Make Layer Visibility Changes Undoable Дозволити скасування змін видимості шарів diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5c7caba0f8..444b79422f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2591,3 +2591,8 @@ cameraData Lens 镜头 Click to place · Alt-click or drag off-canvas to remove 单击以放置 · Alt 单击或拖到画布外以移除 No document open 未打开任何文档 {n} of {max} sample points {max} 个取样点中的 {n} 个 + +# History panel › History Options… (#2966) + History Options… 历史记录选项… + Allow Non-Linear History 允许非线性历史记录 + Make Layer Visibility Changes Undoable 允许撤销图层可见性更改 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 08a7c3bee8..689a13523b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2561,3 +2561,8 @@ cameraData Lens 鏡頭 Click to place · Alt-click or drag off-canvas to remove 按一下以放置 · Alt 按一下或拖曳至畫布外以移除 No document open 未開啟任何文件 {n} of {max} sample points {max} 個取樣點中的 {n} 個 + +# History panel › History Options… (#2966) + History Options… 步驟記錄選項… + Allow Non-Linear History 允許非線性步驟記錄 + Make Layer Visibility Changes Undoable 允許復原圖層可見度變更 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 49a0332bcb..3df13a7c95 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -85,6 +85,7 @@ pub mod gpu_canvas; pub mod gpu_status; pub mod gradient_ui; pub mod guide_layout_ui; +pub mod history_options_ui; pub mod hold_keys; pub mod i18n; mod icon_data; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index be88ab8b89..60d5ac8bf1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -214,6 +214,10 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: if let Some(r) = crate::plugin_ui::menu(app, id, ¶ms) { return r; } + // History panel menu › History Options… (without params: its dialog). + if let Some(r) = crate::history_options_ui::menu(app, id, ¶ms) { + return r; + } if id == "window.panel.brushes" { // Window › Brushes opens the Brush Settings window on its presets tab. app.ui.panels.brush_settings = true; diff --git a/docs/scorecard.md b/docs/scorecard.md index 4adb322320..4cb42580bd 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 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 12 | 9 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | | [Tools](#tools) | 25 | 16 | 2 | | -| [Workspace and UI](#workspace-and-ui) | 9 | 8 | 6 | settings that do nothing: 32 of 154 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 9 | 8 | 6 | settings that do nothing: 32 of 156 (target 0) | | [Type](#type) | 1 | 4 | 4 | | | [Automation](#automation) | 3 | 2 | 6 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 32 of 154** (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: 32 of 156** (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`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `file_handling.image_previews`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 8c71af8e6788a844278ab401103748b47db87586 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 13:39:26 +0200 Subject: [PATCH 02/73] Merge fixups: Vietnamese History Options labels main added a complete Vietnamese catalog; the History Options dialog's labels need rows there too. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/i18n/vi.tsv | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6fb20b3d84..a26b6af68e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3531,3 +3531,8 @@ curves Smooth Làm mượt Stroke Path… Đi nét đường dẫn… Apply mask to layer before removing? Áp dụng mặt nạ vào lớp trước khi xóa? Delete the vector mask? Xóa mặt nạ vectơ? + +# History panel › History Options… (#2966) + History Options… Tùy chọn lịch sử… + Allow Non-Linear History Cho phép lịch sử không tuyến tính + Make Layer Visibility Changes Undoable Cho phép hoàn tác thay đổi hiển thị lớp From 86e45715b24d355d86c9c2c6220acecb32200407 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 16:54:46 +0200 Subject: [PATCH 03/73] History Options test: show the layer before Hide Layers, which now toggles (#3710) Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/history_options_cmds.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index b76127f25f..88cec69f6e 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -190,6 +190,8 @@ mod tests { s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); s.execute("layer.showOnly", json!({"layer": id})).unwrap(); s.execute("layer.showOnly", json!({"layer": id})).unwrap(); + // Hide Layers toggles (⌘,), so show the layer first for it to hide. + s.execute("layer.showLayers", json!({"layer": id})).unwrap(); s.execute("layer.hideLayers", json!({"layer": id})).unwrap(); assert_eq!(entries(&s), before, "no visibility state was recorded"); let st = s.active().unwrap(); From 95058977a8e16ec7beac1af7e28e1eb0b5390185 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 19:26:32 +0200 Subject: [PATCH 04/73] Translate the History Options labels into Turkish and Hungarian Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 080e204aaa..37ac57c190 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -574,6 +574,8 @@ High Pass… Felüláteresztő… Histogram Hisztogram History Előzmények + Allow Non-Linear History Nem lineáris előzmények engedélyezése + Make Layer Visibility Changes Undoable A rétegláthatósági változások visszavonhatók Horizontal Vízszintes HSB/HSL HSB/HSL Huge Óriási diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 617ad81fd9..a23981908c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -717,6 +717,8 @@ Gradients Degradeler Histogram Histogram History Tarih + Allow Non-Linear History Doğrusal Olmayan Tarihe İzin Ver + Make Layer Visibility Changes Undoable Katman Görünürlüğü Değişikliklerini Geri Alınabilir Yap Info Bilgi Measurement Log Ölçüm Günlüğü Modifier Keys Değiştirici Tuşlar From 1ad95dd84aa0dcc4af6f6c9115640a6e6dcd0058 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 13:10:14 +0200 Subject: [PATCH 05/73] History Options: Serbian labels Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/i18n/sr.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 7a85f8d58f..ba152269b4 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -2268,6 +2268,9 @@ Automatically Create New Snapshot When Saving Automatski napravi novi snimak stanja pri čuvanju Show New Snapshot Dialog by Default Podrazumevano prikaži dijalog za novi snimak stanja Clear History Obriši istoriju + History Options… Opcije istorije… + Allow Non-Linear History Dozvoli nelinearnu istoriju + Make Layer Visibility Changes Undoable Omogući opozivanje promena vidljivosti slojeva Panel Options… Opcije panela… View menu Meni prikaza Keep view in sync Drži prikaz usklađenim From c09f9d522375ff2a15d069e52c898d3db9ca857e Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 19:36:01 +0200 Subject: [PATCH 06/73] Scorecard: regenerate for the new History Options preferences 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 af13a3f265..5f3f59cf24 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 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 158 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,7 +176,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 156** (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: 26 of 158** (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`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 1e076433dce771aad46d10f4530745acfb5547a7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 00:21:58 +0200 Subject: [PATCH 07/73] PSD save: choose PSB by the encoded size, not the raw estimate (#5285) Root cause: the auto-PSB switch (#212) decided before encoding, from estimate_psd_size: the uncompressed size of every layer, mask and merged plane plus fixed overheads. Channels are then RLE-packed, so documents whose PSD would be far under the 2 GB limit (a 2.02 GB "raw" document written as a 1.75 GB file, or a 35 MB file from 2.2 GB of flat layers) were saved as PSB. The Multichannel writer used the same estimate. Change: the document is encoded as PSD (PSB only when forced or past 30000 px) and the decision is made on the exact length of the file that will be written. PsdFile::encoded_len computes what to_bytes writes without serializing the pixel data. When it is over the limit, PsdFile::promote_to_psb turns the model into the equivalent PSB in place: the packed RLE rows are the same in both versions, so only the row-count tables widen from 2 to 4 bytes (length fields widen on write). Nothing is re-encoded and the result is byte-identical to a PSB written directly (tested). The promotion is atomic: every stream is checked and its room reserved before the first changes. The layer info is re-padded for PSB and kept 8B64 block signatures are resolved after the version is final. A 1 MB headroom covers the image preview the save adds afterwards. The raw-size estimate is removed: the exact length is cheap (only the layer records are serialized to measure them), so it no longer needs a fast path. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/multichannel_map.rs | 11 +- crates/io/src/psd_export.rs | 279 +++++++++++++++--------------- crates/psd/src/compression.rs | 35 ++++ crates/psd/src/file.rs | 138 +++++++++++++++ crates/psd/src/resources.rs | 10 ++ crates/psd/src/tagged.rs | 9 +- 6 files changed, 339 insertions(+), 143 deletions(-) diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index db31e743ef..ef372577fc 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -64,7 +64,8 @@ pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[St } /// Writes a Multichannel document as a mode-7 PSD (no layer section; every channel a plane). -pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec) { +/// A file past `size_limit` bytes is written as PSB (see `psd_export::fit_psd_size`). +pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: u64) -> (PsdFile, Vec) { let mut warnings = Vec::new(); // Photoshop's Multichannel mode is 8 or 16 bits per channel. let sample = match doc.depth { @@ -95,12 +96,9 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< } } let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = !force_psb && !big && crate::psd_export::psd_size_exceeds_limit(doc); - let version = crate::psd_export::psd_version(doc, force_psb, size_exceeds_limit); + let version = crate::psd_export::psd_version(doc, force_psb); if big && !force_psb { warnings.push("document exceeds 30000 px; written as PSB".into()); - } else if size_exceeds_limit && !force_psb { - warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); } let header = Header::new(version, doc.size.width, doc.size.height, channels.len().max(1) as u16, psd_depth(sample), PsdMode::Multichannel); let image_data = ImageData::encode(Compression::Rle, &planes, &header) @@ -155,7 +153,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< .map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data)) .collect(); let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth); - let file = PsdFile { + let mut file = PsdFile { header, color_mode_data, resources, @@ -166,5 +164,6 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< layer_mask_trailing: Vec::new(), image_data, }; + warnings.extend(crate::psd_export::fit_psd_size(&mut file, size_limit)); (file, warnings) } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 9db3d4799f..7024153382 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -20,9 +20,12 @@ use crate::psd_import::REGENERATED; /// A raster layer never writes them, nor adjustment blocks. const RASTER_STALE_KEYS: [&[u8; 4]; 8] = [b"SoCo", b"GdFl", b"PtFl", b"SoLd", b"PlLd", b"SoLE", b"TySh", b"vscg"]; +/// The largest file written as PSD: past it, the document is saved as PSB (Large Document Format), +/// as Photoshop does. const PSD_MAX_FILE_SIZE: u64 = 2 * 1024 * 1024 * 1024; -const PSD_ESTIMATE_FIXED_OVERHEAD: u64 = 1024 * 1024; -const PSD_ESTIMATE_LAYER_OVERHEAD: u64 = 64 * 1024; +/// Room kept under [`PSD_MAX_FILE_SIZE`] for what the save adds after the conversion (the image +/// preview resource, a few KB). +const PSD_SAVE_HEADROOM: u64 = 1024 * 1024; /// Options for [`document_to_psd_with`]. #[derive(Debug, Clone)] @@ -1360,109 +1363,6 @@ const MERGED_WEIGHT: f32 = 2.0; /// rest is compressing its planes. const MERGED_RENDERED: f32 = 0.8; -/// Adds headroom for compressed channel streams and their per-row length tables. -fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { - raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) -} - -fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { - let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; - let plane_rows = height.checked_mul(channels)?; - *raw_bytes = raw_bytes.checked_add(plane_bytes)?; - *rows = rows.checked_add(plane_rows)?; - Some(()) -} - -fn exceeds_psd_size_limit(estimated_size: Option) -> bool { - estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) -} - -fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { - let bounds = surface.content_bounds(); - Some((u64::from(bounds.width()), u64::from(bounds.height()))) -} - -pub(crate) fn estimate_psd_size(doc: &Document) -> Option { - let mut raw_bytes = 0; - let mut rows = 0; - let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; - - let width = u64::from(doc.size.width); - let height = u64::from(doc.size.height); - - if doc.mode == ColorMode::Multichannel { - let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; - let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; - } else { - let format = doc.pixel_format(); - let color_channels = u64::try_from(format.mode.color_channels()).ok()?; - let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; - let layer_channels = color_channels.checked_add(1)?; - - for (_, _, layer) in doc.walk() { - structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; - for (_, data) in &layer.psd_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - let surface = match &layer.content { - LayerContent::Fill(fill) => { - let mut fill_width = width; - let mut fill_height = height; - if let Some(cache) = &layer.fill_cache - && cache.fill == *fill - { - let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; - fill_width = fill_width.max(cache_width); - fill_height = fill_height.max(cache_height); - } - add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; - None - } - _ => layer.surface(), - }; - if let Some(surface) = surface { - let (surface_width, surface_height) = surface_dimensions(surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; - } - if let Some(mask) = &layer.mask { - let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; - } - if let LayerContent::Smart(smart) = &layer.content - && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source - { - structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; - } - } - - let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); - let mut extra_channels = doc.channels.len().min(max_extra_channels); - if doc.quick_mask.is_some() && extra_channels < max_extra_channels { - extra_channels += 1; - } - let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; - for channel in doc.channels.iter().take(extra_channels) { - structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; - } - } - - structural_bytes = structural_bytes - .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? - .checked_add(u64::try_from(doc.metadata.xmp.as_ref().map_or(0, String::len)).ok()?)? - .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; - for (_, name, data) in &doc.metadata.psd_resources { - structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; - } - for (_, _, data) in &doc.metadata.psd_global_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - estimate_encoded_size(raw_bytes, rows, structural_bytes) -} - /// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD /// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by /// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). @@ -1470,26 +1370,57 @@ fn block_signature(sig: [u8; 4], version: Version) -> [u8; 4] { if version == Version::Psd && sig == *b"8B64" { *b"8BIM" } else { sig } } -pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { +/// The version a document is encoded as: PSB when asked for or past PSD's 30000 px; otherwise +/// PSD, which [`fit_psd_size`] turns into PSB once the encoded file proves too large. +pub(crate) fn psd_version(doc: &Document, force_psb: bool) -> Version { let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; - if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } + if force_psb || exceeds_dimensions { Version::Psb } else { Version::Psd } } -pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { - exceeds_psd_size_limit(estimate_psd_size(doc)) +/// Keeps an encoded PSD whose file fits `limit` (less [`PSD_SAVE_HEADROOM`]) and turns a larger +/// one into PSB (#212, #5285). The decision is made on the exact length of the file as it will be +/// written, not on the raw pixel size: RLE usually packs the channels far below it. Promoting +/// re-encodes nothing (only the RLE row-count tables widen, see [`PsdFile::promote_to_psb`]). +/// Returns a warning when the version changed or could not be changed. +pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { + if file.header.version.is_psb() { + return None; + } + // A length that cannot be computed (it overflows) cannot fit either. + if file.encoded_len().is_ok_and(|len| len.saturating_add(PSD_SAVE_HEADROOM) <= limit) { + return None; + } + match file.promote_to_psb() { + Ok(()) => { + // Photoshop pads the layer info to 4 bytes; the padding depends on the version. + if matches!(file.layer_info_placement, LayerInfoPlacement::Section) + && let Some(info) = &mut file.layer_info + && info.padding.is_some() + && info.pad_to(Version::Psb, 4).is_err() + { + info.padding = None; + } + Some("encoded size exceeds 2 GB; written as PSB".into()) + } + Err(e) => Some(format!("encoded size exceeds 2 GB, but the file could not be written as PSB: {e}")), + } } /// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { + document_to_psd_sized(doc, opts, depth, ctl, PSD_MAX_FILE_SIZE) +} + +/// [`document_to_psd_nested`] with the largest file kept as PSD (lowered by tests). +fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt, size_limit: u64) -> (PsdFile, Vec) { if doc.mode == ColorMode::Multichannel { - return crate::multichannel_map::document_to_psd(doc, opts.force_psb); + return crate::multichannel_map::document_to_psd(doc, opts.force_psb, size_limit); } let fmt = doc.pixel_format(); let sample = fmt.sample; let cc = fmt.mode.color_channels(); let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = !opts.force_psb && !big && psd_size_exceeds_limit(doc); - let version = psd_version(doc, opts.force_psb, size_exceeds_limit); + let version = psd_version(doc, opts.force_psb); let mut ex = Ex { fmt, dpi: doc.resolution_dpi, @@ -1513,8 +1444,6 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c }; if big && !opts.force_psb { ex.warnings.push("document exceeds 30000 px; written as PSB".into()); - } else if size_exceeds_limit && !opts.force_psb { - ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); } if fmt.mode != doc.mode { ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); @@ -1704,7 +1633,8 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { continue; } - global_blocks.push(global_block(block_signature(sig, version), key, &data)); + // The signature follows the final version (see `block_signature` below). + global_blocks.push(global_block(sig, key, &data)); } if let Some(txt2) = txt2 { let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); @@ -1766,7 +1696,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not // open a 32-bit file without them (#291). let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth); - let file = PsdFile { + let mut file = PsdFile { header, color_mode_data, resources, @@ -1777,6 +1707,11 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c layer_mask_trailing: Vec::new(), image_data, }; + ex.warnings.extend(fit_psd_size(&mut file, size_limit)); + let version = file.header.version; + for block in &mut file.global_blocks { + block.signature = block_signature(block.signature, version); + } (file, ex.warnings) } @@ -1949,33 +1884,107 @@ mod tests { assert_eq!(density, 0.5); } - #[test] - fn size_limit_boundary_keeps_limit_and_switches_above_it() { - assert!(!exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE))); - assert!(exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE + 1))); - assert!(exceeds_psd_size_limit(None)); + /// A 1024² RGB document with one full-canvas layer: flat colour (packs to a few KB) or noise + /// (RLE can't pack it). Its raw planes (layer RGBA + merged RGB) are 7 MiB either way. + fn sized_document(noise: bool, depth: SampleType) -> Document { + const SIDE: u32 = 1024; + let mut doc = Document::new("size limit", photocraft_geom::Size::new(SIDE, SIDE), ColorMode::Rgb, depth); + let mut layer = Layer::raster("Layer 1", doc.pixel_format()); + let rect = photocraft_geom::Rect::new(0, 0, SIDE as i32, SIDE as i32); + let surface = layer.surface_mut().unwrap(); + if noise { + let mut state = 0x2545_f491_u32; + let data: Vec = (0..SIDE * SIDE * 4) + .map(|i| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + if i % 4 == 3 { 1.0 } else { (state >> 24) as f32 / 255.0 } + }) + .collect(); + surface.write_region(rect, &data); + } else { + surface.fill_rect(rect, &[0.2, 0.4, 0.6, 1.0]); + } + doc.layers.push(layer); + doc } - #[test] - fn encoded_size_estimator_rejects_arithmetic_overflow() { - assert_eq!(estimate_encoded_size(u64::MAX, 0, 0), None); - assert_eq!(estimate_encoded_size(0, u64::MAX, 0), None); - assert_eq!(estimate_encoded_size(0, 0, u64::MAX), Some(u64::MAX)); - assert!(exceeds_psd_size_limit(estimate_psd_size(&document(u32::MAX, u32::MAX)))); + const SIZED_RAW_BYTES: u64 = 1024 * 1024 * (4 + 3); + /// Under the raw size, so only the encoded size can keep a document PSD. + const SIZED_LIMIT: u64 = 4 * 1024 * 1024; + const _: () = assert!(SIZED_RAW_BYTES > SIZED_LIMIT); + + fn export_sized(doc: &Document, limit: u64) -> (PsdFile, Vec) { + document_to_psd_sized(doc, &PsdExportOptions::default(), 0, &Interrupt::NONE, limit) } + /// #5285: a document whose raw pixels are over the PSD limit but whose encoded file fits is + /// saved as PSD (the raw-size estimate used to make it a PSB). #[test] - fn large_encoded_size_selects_psb_without_changing_explicit_choice() { - let large = document(30_000, 30_000); - assert!(estimate_psd_size(&large).is_some_and(|size| size > PSD_MAX_FILE_SIZE)); - let large_size_exceeds_limit = psd_size_exceeds_limit(&large); - assert_eq!(psd_version(&large, false, large_size_exceeds_limit), Version::Psb); + fn a_file_that_fits_after_compression_stays_psd() { + let doc = sized_document(false, SampleType::U8); + let (file, warnings) = export_sized(&doc, SIZED_LIMIT); + assert_eq!(file.header.version, Version::Psd); + assert!(warnings.iter().all(|w| !w.contains("PSB")), "{warnings:?}"); + let bytes = file.to_bytes().unwrap(); + assert!(bytes.len() as u64 + PSD_SAVE_HEADROOM <= SIZED_LIMIT, "{} bytes", bytes.len()); + let (back, _) = crate::psd_to_document(&PsdFile::from_bytes(&bytes).unwrap()); + assert_eq!(back.layers[0].surface().unwrap().pixel(700, 300), doc.layers[0].surface().unwrap().pixel(700, 300)); + } + /// #5285: a document whose encoded file is over the limit becomes a PSB, byte for byte the + /// one a forced PSB save writes, and reads back. 8 bits keep the layers in the layer section, + /// 16 bits in a global `Lr16` block. + #[test] + fn a_file_over_the_limit_after_compression_is_psb() { + for depth in [SampleType::U8, SampleType::U16] { + let doc = sized_document(true, depth); + let (file, warnings) = export_sized(&doc, SIZED_LIMIT); + assert_eq!(file.header.version, Version::Psb, "{depth:?}"); + assert!(warnings.iter().any(|w| w == "encoded size exceeds 2 GB; written as PSB"), "{warnings:?}"); + let bytes = file.to_bytes().unwrap(); + assert!(bytes.len() as u64 > SIZED_LIMIT); + let forced = document_to_psd_with(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }).0; + assert!(bytes == forced.to_bytes().unwrap(), "{depth:?}: the promoted PSB differs from a PSB written directly"); + let (back, _) = crate::psd_to_document(&PsdFile::from_bytes(&bytes).unwrap()); + for (x, y) in [(0, 0), (1023, 0), (511, 777), (1023, 1023)] { + assert_eq!(back.layers[0].surface().unwrap().pixel(x, y), doc.layers[0].surface().unwrap().pixel(x, y), "{depth:?} ({x}, {y})"); + } + } + } + + /// The limit is the exact written length plus the save's headroom: one byte less is a PSB. + #[test] + fn the_size_limit_is_the_exact_encoded_length() { + let doc = sized_document(false, SampleType::U8); + let len = export_sized(&doc, u64::MAX).0.to_bytes().unwrap().len() as u64; + assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM).0.header.version, Version::Psd); + assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM - 1).0.header.version, Version::Psb); + // The real limit: a small document stays PSD, a forced one is PSB. let small = document(1, 1); - let small_size_exceeds_limit = psd_size_exceeds_limit(&small); - assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd); - assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb); + assert_eq!(document_to_psd(&small).header.version, Version::Psd); + assert_eq!(document_to_psd_with(&small, &PsdExportOptions { force_psb: true, ..Default::default() }).0.header.version, Version::Psb); + assert_eq!(psd_version(&document(30_001, 1), false), Version::Psb); } + + /// A Multichannel document follows the same rule. + #[test] + fn a_multichannel_file_over_the_limit_is_psb() { + let mut doc = document(64, 64); + doc.mode = ColorMode::Multichannel; + doc.channels.push(photocraft_doc::AlphaChannel::new("Cyan", photocraft_raster::Surface::new(PixelFormat::GRAY8))); + let (file, _) = export_sized(&doc, u64::MAX); + assert_eq!(file.header.version, Version::Psd); + let len = file.to_bytes().unwrap().len() as u64; + let (file, warnings) = export_sized(&doc, len + PSD_SAVE_HEADROOM - 1); + assert_eq!(file.header.version, Version::Psb); + assert!(warnings.iter().any(|w| w.contains("written as PSB")), "{warnings:?}"); + let back = PsdFile::from_bytes(&file.to_bytes().unwrap()).unwrap(); + assert_eq!(back.header.version, Version::Psb); + assert_eq!(back.decode_merged().unwrap(), PsdFile::from_bytes(&export_sized(&doc, u64::MAX).0.to_bytes().unwrap()).unwrap().decode_merged().unwrap()); + } + #[test] fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 7ad2296fbc..08db197fd0 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -224,6 +224,41 @@ pub fn decode_planes(compression: Compression, data: &[u8], layout: &PlaneLayout } } +/// Checks that `data` starts with a PSD (two-byte) RLE row-count table of `rows` entries and +/// reserves the room [`widen_rle_counts`] needs, so the widening itself cannot fail. +pub(crate) fn reserve_rle_widening(data: &mut Vec, rows: usize) -> Result<()> { + let table = rows.checked_mul(2).ok_or(PsdError::LimitExceeded("row count overflow"))?; + if data.len() < table { + return Err(PsdError::UnexpectedEof { offset: data.len(), needed: table - data.len() }); + } + data.try_reserve_exact(table).map_err(|_| PsdError::LimitExceeded("not enough memory to widen the RLE row counts")) +} + +/// Rewrites a PSD RLE stream (two-byte row counts) as the PSB one (four-byte row counts) in +/// place: the packed rows are identical in both versions, only the count table widens. +pub(crate) fn widen_rle_counts(data: &mut Vec, rows: usize) -> Result<()> { + let table = rows.checked_mul(2).ok_or(PsdError::LimitExceeded("row count overflow"))?; + let old_len = data.len(); + if old_len < table { + return Err(PsdError::UnexpectedEof { offset: old_len, needed: table - old_len }); + } + let new_len = old_len.checked_add(table).ok_or(PsdError::LimitExceeded("RLE stream too large"))?; + data.resize(new_len, 0); + data.copy_within(table..old_len, table * 2); + // Back to front, so no count is overwritten before it is read: count `i` moves from + // `2i..2i + 2` to `4i..4i + 4`, at or after where counts `0..i` still are. + for i in (0..rows).rev() { + let (Some(&hi), Some(&lo)) = (data.get(2 * i), data.get(2 * i + 1)) else { + return Err(PsdError::invalid("RLE row-count table out of range")); + }; + let Some(dst) = data.get_mut(4 * i..4 * i + 4) else { + return Err(PsdError::invalid("RLE row-count table out of range")); + }; + dst.copy_from_slice(&[0, 0, hi, lo]); + } + Ok(()) +} + /// Encodes planar data (excluding the 2-byte compression field). pub fn encode_planes(compression: Compression, decoded: &[u8], layout: &PlaneLayout) -> Result> { let total = layout.decoded_len()?; diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index 1e86665ad8..16801d5da3 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -1,5 +1,6 @@ //! The top-level [`PsdFile`] model, parser and writer. +use crate::compression::{Compression, reserve_rle_widening, widen_rle_counts}; use crate::error::{PsdError, Result}; use crate::header::{ColorMode, Header, Version}; use crate::image_data::ImageData; @@ -214,6 +215,85 @@ impl PsdFile { Ok(out) } + /// The number of bytes [`Self::to_bytes`] writes, computed without serializing the channel + /// data (only the layer records, which are small, are serialized to measure them). Lets a + /// writer check a file against the 2 GB PSD limit before choosing the version. + pub fn encoded_len(&self) -> Result { + let v = self.header.version; + let psb = v.is_psb(); + let len_field = |long: bool| if long { 8u64 } else { 4 }; + let blocks_len = |blocks: &[TaggedBlock]| blocks.iter().fold(0u64, |n, b| n.saturating_add(b.encoded_len_aligned(v, 4) as u64)); + let body_len = |info: &LayerInfo| -> Result { + let unpadded = info.unpadded_len(v)?; + let padding = info.padding.as_ref().map_or(unpadded % 2, |p| p.len() as u64); + Ok(unpadded.saturating_add(padding)) + }; + // Header, colour mode data, resources. + let mut n = 26u64.saturating_add(4).saturating_add(self.color_mode_data.len() as u64).saturating_add(resources::section_len(&self.resources)); + + let in_block = matches!(self.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }); + let section_empty = + self.layer_info.is_none() && self.global_layer_mask.is_none() && self.global_blocks.is_empty() && self.layer_mask_trailing.is_empty(); + n = n.saturating_add(len_field(psb)); + if !section_empty { + n = n.saturating_add(len_field(psb)); + if let (Some(info), false) = (&self.layer_info, in_block) { + n = n.saturating_add(body_len(info)?); + } + let need_mask_field = self.global_layer_mask.is_some() || !self.global_blocks.is_empty() || (in_block && self.layer_info.is_some()); + if need_mask_field { + n = n.saturating_add(4).saturating_add(self.global_layer_mask.as_ref().map_or(0, |g| g.data.len() as u64)); + } + n = n.saturating_add(blocks_len(&self.global_blocks)); + if let (Some(info), LayerInfoPlacement::GlobalBlock { key, padding, .. }) = (&self.layer_info, &self.layer_info_placement) { + let body = body_len(info)?; + let pad = padding.as_ref().map_or((4 - body % 4) % 4, |p| p.len() as u64); + n = n.saturating_add(8).saturating_add(len_field(uses_long_length(v, key))).saturating_add(body).saturating_add(pad); + } + n = n.saturating_add(self.layer_mask_trailing.len() as u64); + } + Ok(n.saturating_add(2).saturating_add(self.image_data.data.len() as u64)) + } + + /// Turns a PSD into the equivalent PSB in place, without re-encoding any pixels: the RLE + /// row-count tables of the layer channels and the merged image widen from two to four bytes + /// per row (the packed rows are the same in both versions), and the length fields widen when + /// the file is written. Raw and ZIP channel data is the same in both. A PSB is left as is. + /// + /// Atomic: every RLE stream is checked (and the room to widen it reserved) before the first + /// is changed, so an error leaves the file untouched. The layer info padding is kept; a + /// writer that pads to an alignment re-pads for the new version. + pub fn promote_to_psb(&mut self) -> Result<()> { + if self.header.version.is_psb() { + return Ok(()); + } + let merged_rows = match self.image_data.compression { + Compression::Rle => Some(ImageData::layout(&self.header).rows()?), + _ => None, + }; + let layers = self.layer_info.as_mut().map_or(&mut [][..], |info| &mut info.layers[..]); + let mut streams: Vec<(&mut Vec, usize)> = Vec::new(); + for layer in layers.iter_mut() { + let rects: Vec<_> = layer.channels.iter().map(|c| layer.channel_rect(c.id)).collect(); + for (c, rect) in layer.channels.iter_mut().zip(rects) { + if c.compression == Some(Compression::Rle) { + streams.push((&mut c.data, rect.size()?.1)); + } + } + } + if let Some(rows) = merged_rows { + streams.push((&mut self.image_data.data, rows)); + } + for (data, rows) in &mut streams { + reserve_rle_widening(data, *rows)?; + } + for (data, rows) in streams { + widen_rle_counts(data, rows)?; + } + self.header.version = Version::Psb; + Ok(()) + } + /// Layer records in file order (bottom-most first); empty if none. pub fn layers(&self) -> &[LayerRecord] { self.layer_info.as_ref().map_or(&[], |i| &i.layers) @@ -317,6 +397,64 @@ mod write_tests { use super::*; use crate::{Compression, testgen}; + /// `encoded_len` is exactly what `to_bytes` writes, for every generated file and both layer + /// info placements, with and without padding (#5285). + #[test] + fn encoded_len_matches_the_written_length() { + for case in testgen::all_cases() { + assert_eq!(case.file.encoded_len().unwrap(), case.file.to_bytes().unwrap().len() as u64, "{}", case.name); + } + for version in [Version::Psd, Version::Psb] { + for key in [*b"Lr16", *b"Layr"] { + for padding in [None, Some(vec![]), Some(vec![1, 2, 3])] { + for body_padding in [None, Some(vec![]), Some(vec![9])] { + let mut file = testgen::small(version, Compression::Rle); + file.global_blocks = vec![TaggedBlock::new(*b"zz01", vec![11]), TaggedBlock::new(*b"lnk2", vec![1; 5])]; + file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 1, signature: *b"8BIM", key, padding: padding.clone() }; + file.layer_info.as_mut().unwrap().padding = body_padding; + file.layer_mask_trailing = vec![0; 3]; + file.resources.push(ImageResource { name: b"odd".to_vec(), ..ImageResource::new(4000, vec![1, 2, 3]) }); + assert_eq!(file.encoded_len().unwrap(), file.to_bytes().unwrap().len() as u64, "{version:?} {key:?}"); + } + } + } + } + let mut empty = testgen::small(Version::Psd, Compression::Raw); + empty.layer_info = None; + empty.global_layer_mask = None; + empty.global_blocks.clear(); + assert_eq!(empty.encoded_len().unwrap(), empty.to_bytes().unwrap().len() as u64); + } + + /// Promoting a PSD gives exactly the PSB written directly from the same pixels: only the RLE + /// row counts (and the length fields, on write) widen (#5285). + #[test] + fn promote_to_psb_equals_the_psb_written_directly() { + let cases = testgen::all_cases(); + let (psd, psb) = cases.split_at(cases.len() / 2); + for (psd, psb) in psd.iter().zip(psb) { + assert_eq!(psd.file.header.version, Version::Psd, "{}", psd.name); + let mut promoted = psd.file.clone(); + promoted.promote_to_psb().unwrap(); + assert_eq!(promoted, psb.file, "{}", psd.name); + assert_eq!(promoted.to_bytes().unwrap(), psb.file.to_bytes().unwrap(), "{}", psd.name); + } + } + + /// A damaged RLE table is refused before anything changes: the file stays a valid PSD. + #[test] + fn promote_to_psb_is_atomic() { + let mut file = testgen::small(Version::Psd, Compression::Rle); + // The last layer with pixels ("b", two rows): its red channel loses its row-count table. + let layers = &mut file.layer_info.as_mut().unwrap().layers; + let red = layers[2].channels.iter_mut().find(|c| c.id == 0).unwrap(); + assert_eq!(red.compression, Some(Compression::Rle)); + red.data.truncate(1); + let before = file.clone(); + assert!(file.promote_to_psb().is_err()); + assert_eq!(file, before); + } + #[test] fn global_blocks_default_to_four_byte_padding() { for version in [Version::Psd, Version::Psb] { diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index c20efbfc9e..be4870de9d 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -242,6 +242,16 @@ pub(crate) fn read_section(r: &mut Reader<'_>) -> Result> { Ok(v) } +/// Serialized size of the resource section [`write_section`] writes, its length field included. +pub(crate) fn section_len(res: &[ImageResource]) -> u64 { + res.iter().fold(4u64, |n, r| { + let name = 1 + r.name.len().min(255); + let name = name + name % 2; + let data = r.data.len().saturating_add(r.data.len() % 2); + n.saturating_add((4 + 2 + name + 4) as u64).saturating_add(data as u64) + }) +} + pub(crate) fn write_section(out: &mut Vec, res: &[ImageResource]) -> Result<()> { let at = out.begin_len(false); for r in res { diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 7d66eae920..cd86122666 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -338,9 +338,14 @@ impl TaggedBlock { /// Serialized size in bytes as a layer block (two-byte alignment). pub fn encoded_len(&self, version: Version) -> usize { + self.encoded_len_aligned(version, 2) + } + + /// Serialized size in bytes as [`Self::write`] writes it with `alignment`. + pub(crate) fn encoded_len_aligned(&self, version: Version, alignment: usize) -> usize { let l = if uses_long_length(version, &self.key) { 8 } else { 4 }; - let p = self.padding.as_ref().map_or(Self::default_padding(self.data.len(), 2), Vec::len); - 8 + l + self.data.len() + p + let p = self.padding.as_ref().map_or(Self::default_padding(self.data.len(), alignment), Vec::len); + (8 + l + p).saturating_add(self.data.len()) } } From e6238ad399f6463ca6ce6b40ced5b5caf3436f8d Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 01:34:23 +0200 Subject: [PATCH 08/73] PSD save: widen RLE row counts while writing a promoted PSB (#5285) promote_to_psb used to rewrite every RLE stream in place (grow the Vec, move the packed rows, widen the count table): a reallocation and a full extra pass over the channel data of a file that is already over 2 GB, right before to_bytes copies it all once more. Now promotion only marks the model: PsdFile gains `write_as_psb`. The model stays a consistent PSD (header version 1, two-byte row counts), so every reader that decodes it with header.version is unaffected. to_bytes and encoded_len write version 2, long length fields and four-byte row counts, widening each table while the stream is copied out (the packed rows are the same in both versions). written_version() reports what will be written; pad_layer_info_to() pads the written body. Promotion checks every count table first, so an error leaves the model unmarked and the write cannot fail on a table later. Tests: a promoted PSD writes exactly the PSB written directly and reads back as it, for every generated case; the promoted model is unchanged apart from the flag and decodes as before; damaged tables fail with an error before and after promotion. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/multichannel_map.rs | 1 + crates/io/src/psd_export.rs | 33 +++--- crates/psd/src/builder.rs | 1 + crates/psd/src/compression.rs | 37 ++---- crates/psd/src/file.rs | 181 ++++++++++++++++++++++-------- crates/psd/src/layer.rs | 57 ++++++++-- crates/psd/src/testgen.rs | 3 + crates/psd/src/tiff.rs | 1 + 8 files changed, 218 insertions(+), 96 deletions(-) diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index ef372577fc..9c42171be5 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -163,6 +163,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: u64) global_blocks, layer_mask_trailing: Vec::new(), image_data, + write_as_psb: false, }; warnings.extend(crate::psd_export::fit_psd_size(&mut file, size_limit)); (file, warnings) diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 7024153382..5a7ee69373 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1383,7 +1383,7 @@ pub(crate) fn psd_version(doc: &Document, force_psb: bool) -> Version { /// re-encodes nothing (only the RLE row-count tables widen, see [`PsdFile::promote_to_psb`]). /// Returns a warning when the version changed or could not be changed. pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { - if file.header.version.is_psb() { + if file.written_version().is_psb() { return None; } // A length that cannot be computed (it overflows) cannot fit either. @@ -1393,10 +1393,11 @@ pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { match file.promote_to_psb() { Ok(()) => { // Photoshop pads the layer info to 4 bytes; the padding depends on the version. + let padded = file.layer_info.as_ref().is_some_and(|info| info.padding.is_some()); if matches!(file.layer_info_placement, LayerInfoPlacement::Section) + && padded + && file.pad_layer_info_to(4).is_err() && let Some(info) = &mut file.layer_info - && info.padding.is_some() - && info.pad_to(Version::Psb, 4).is_err() { info.padding = None; } @@ -1706,9 +1707,10 @@ fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ct global_blocks, layer_mask_trailing: Vec::new(), image_data, + write_as_psb: false, }; ex.warnings.extend(fit_psd_size(&mut file, size_limit)); - let version = file.header.version; + let version = file.written_version(); for block in &mut file.global_blocks { block.signature = block_signature(block.signature, version); } @@ -1925,7 +1927,7 @@ mod tests { fn a_file_that_fits_after_compression_stays_psd() { let doc = sized_document(false, SampleType::U8); let (file, warnings) = export_sized(&doc, SIZED_LIMIT); - assert_eq!(file.header.version, Version::Psd); + assert_eq!(file.written_version(), Version::Psd); assert!(warnings.iter().all(|w| !w.contains("PSB")), "{warnings:?}"); let bytes = file.to_bytes().unwrap(); assert!(bytes.len() as u64 + PSD_SAVE_HEADROOM <= SIZED_LIMIT, "{} bytes", bytes.len()); @@ -1941,12 +1943,17 @@ mod tests { for depth in [SampleType::U8, SampleType::U16] { let doc = sized_document(true, depth); let (file, warnings) = export_sized(&doc, SIZED_LIMIT); - assert_eq!(file.header.version, Version::Psb, "{depth:?}"); + assert_eq!(file.written_version(), Version::Psb, "{depth:?}"); assert!(warnings.iter().any(|w| w == "encoded size exceeds 2 GB; written as PSB"), "{warnings:?}"); let bytes = file.to_bytes().unwrap(); assert!(bytes.len() as u64 > SIZED_LIMIT); let forced = document_to_psd_with(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }).0; - assert!(bytes == forced.to_bytes().unwrap(), "{depth:?}: the promoted PSB differs from a PSB written directly"); + let forced = forced.to_bytes().unwrap(); + assert!(bytes == forced, "{depth:?}: the promoted PSB differs from a PSB written directly"); + assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), PsdFile::from_bytes(&forced).unwrap(), "{depth:?}"); + // The promoted model itself stays a consistent PSD for every reader. + assert_eq!(file.header.version, Version::Psd); + assert_eq!(crate::psd_to_document(&file).0.layers[0].surface().unwrap().pixel(511, 777), doc.layers[0].surface().unwrap().pixel(511, 777)); let (back, _) = crate::psd_to_document(&PsdFile::from_bytes(&bytes).unwrap()); for (x, y) in [(0, 0), (1023, 0), (511, 777), (1023, 1023)] { assert_eq!(back.layers[0].surface().unwrap().pixel(x, y), doc.layers[0].surface().unwrap().pixel(x, y), "{depth:?} ({x}, {y})"); @@ -1959,12 +1966,12 @@ mod tests { fn the_size_limit_is_the_exact_encoded_length() { let doc = sized_document(false, SampleType::U8); let len = export_sized(&doc, u64::MAX).0.to_bytes().unwrap().len() as u64; - assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM).0.header.version, Version::Psd); - assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM - 1).0.header.version, Version::Psb); + assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM).0.written_version(), Version::Psd); + assert_eq!(export_sized(&doc, len + PSD_SAVE_HEADROOM - 1).0.written_version(), Version::Psb); // The real limit: a small document stays PSD, a forced one is PSB. let small = document(1, 1); - assert_eq!(document_to_psd(&small).header.version, Version::Psd); - assert_eq!(document_to_psd_with(&small, &PsdExportOptions { force_psb: true, ..Default::default() }).0.header.version, Version::Psb); + assert_eq!(document_to_psd(&small).written_version(), Version::Psd); + assert_eq!(document_to_psd_with(&small, &PsdExportOptions { force_psb: true, ..Default::default() }).0.written_version(), Version::Psb); assert_eq!(psd_version(&document(30_001, 1), false), Version::Psb); } @@ -1975,10 +1982,10 @@ mod tests { doc.mode = ColorMode::Multichannel; doc.channels.push(photocraft_doc::AlphaChannel::new("Cyan", photocraft_raster::Surface::new(PixelFormat::GRAY8))); let (file, _) = export_sized(&doc, u64::MAX); - assert_eq!(file.header.version, Version::Psd); + assert_eq!(file.written_version(), Version::Psd); let len = file.to_bytes().unwrap().len() as u64; let (file, warnings) = export_sized(&doc, len + PSD_SAVE_HEADROOM - 1); - assert_eq!(file.header.version, Version::Psb); + assert_eq!(file.written_version(), Version::Psb); assert!(warnings.iter().any(|w| w.contains("written as PSB")), "{warnings:?}"); let back = PsdFile::from_bytes(&file.to_bytes().unwrap()).unwrap(); assert_eq!(back.header.version, Version::Psb); diff --git a/crates/psd/src/builder.rs b/crates/psd/src/builder.rs index 04737337ef..3fdf10286f 100644 --- a/crates/psd/src/builder.rs +++ b/crates/psd/src/builder.rs @@ -457,6 +457,7 @@ impl PsdBuilder { global_blocks: Vec::new(), layer_mask_trailing: Vec::new(), image_data, + write_as_psb: false, }) } diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 08db197fd0..a573cd2297 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -224,38 +224,25 @@ pub fn decode_planes(compression: Compression, data: &[u8], layout: &PlaneLayout } } -/// Checks that `data` starts with a PSD (two-byte) RLE row-count table of `rows` entries and -/// reserves the room [`widen_rle_counts`] needs, so the widening itself cannot fail. -pub(crate) fn reserve_rle_widening(data: &mut Vec, rows: usize) -> Result<()> { +/// Bytes a PSD RLE stream (two-byte row counts) of `rows` rows grows by when written as PSB +/// (four-byte row counts); an error when `data` is too short to hold the count table. +pub(crate) fn rle_widening(data: &[u8], rows: usize) -> Result { let table = rows.checked_mul(2).ok_or(PsdError::LimitExceeded("row count overflow"))?; if data.len() < table { return Err(PsdError::UnexpectedEof { offset: data.len(), needed: table - data.len() }); } - data.try_reserve_exact(table).map_err(|_| PsdError::LimitExceeded("not enough memory to widen the RLE row counts")) + Ok(table as u64) } -/// Rewrites a PSD RLE stream (two-byte row counts) as the PSB one (four-byte row counts) in -/// place: the packed rows are identical in both versions, only the count table widens. -pub(crate) fn widen_rle_counts(data: &mut Vec, rows: usize) -> Result<()> { - let table = rows.checked_mul(2).ok_or(PsdError::LimitExceeded("row count overflow"))?; - let old_len = data.len(); - if old_len < table { - return Err(PsdError::UnexpectedEof { offset: old_len, needed: table - old_len }); - } - let new_len = old_len.checked_add(table).ok_or(PsdError::LimitExceeded("RLE stream too large"))?; - data.resize(new_len, 0); - data.copy_within(table..old_len, table * 2); - // Back to front, so no count is overwritten before it is read: count `i` moves from - // `2i..2i + 2` to `4i..4i + 4`, at or after where counts `0..i` still are. - for i in (0..rows).rev() { - let (Some(&hi), Some(&lo)) = (data.get(2 * i), data.get(2 * i + 1)) else { - return Err(PsdError::invalid("RLE row-count table out of range")); - }; - let Some(dst) = data.get_mut(4 * i..4 * i + 4) else { - return Err(PsdError::invalid("RLE row-count table out of range")); - }; - dst.copy_from_slice(&[0, 0, hi, lo]); +/// Writes a PSD RLE stream (two-byte row counts) as the PSB one (four-byte row counts): the packed +/// rows are the same in both versions, only the count table widens. +pub(crate) fn put_widened_rle(out: &mut Vec, data: &[u8], rows: usize) -> Result<()> { + let table_len = usize::try_from(rle_widening(data, rows)?).map_err(|_| PsdError::LimitExceeded("row count overflow"))?; + let (table, packed) = data.split_at_checked(table_len).ok_or_else(|| PsdError::invalid("RLE row-count table out of range"))?; + for count in table.as_chunks::<2>().0 { + out.extend_from_slice(&[0, 0, count[0], count[1]]); } + out.extend_from_slice(packed); Ok(()) } diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index 16801d5da3..bae37c5227 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -1,6 +1,6 @@ //! The top-level [`PsdFile`] model, parser and writer. -use crate::compression::{Compression, reserve_rle_widening, widen_rle_counts}; +use crate::compression::{Compression, put_widened_rle, rle_widening}; use crate::error::{PsdError, Result}; use crate::header::{ColorMode, Header, Version}; use crate::image_data::ImageData; @@ -63,7 +63,8 @@ impl GlobalLayerMask { /// A complete PSD/PSB file. /// /// `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified well-formed -/// files, and `from_bytes(to_bytes(f)) == f` for any model `f`. +/// files, and `from_bytes(to_bytes(f)) == f` for any model `f` not marked +/// [`Self::write_as_psb`] (a marked one reads back as the PSB it was written as). #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct PsdFile { @@ -86,6 +87,12 @@ pub struct PsdFile { pub layer_mask_trailing: Vec, /// Merged image data. pub image_data: ImageData, + /// Write this PSD model as PSB (set by [`Self::promote_to_psb`]). The model itself stays a + /// consistent PSD: its channel data keeps two-byte RLE row counts, so everything that reads + /// it with `header.version` decodes it as before. Only [`Self::to_bytes`] and + /// [`Self::encoded_len`] write version 2, long length fields and four-byte row counts. + #[cfg_attr(feature = "serde", serde(default))] + pub write_as_psb: bool, } impl PsdFile { @@ -148,19 +155,40 @@ impl PsdFile { } } let image_data = ImageData::read(&mut r, &header)?; - Ok(PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, global_layer_mask, global_blocks, layer_mask_trailing, image_data }) + Ok(PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement, + global_layer_mask, + global_blocks, + layer_mask_trailing, + image_data, + write_as_psb: false, + }) } /// Serializes the file. pub fn to_bytes(&self) -> Result> { - let v = self.header.version; + let (v, widen) = self.write_form(); let psb = v.is_psb(); // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies // repeatedly. Everything else (headers, resources, records) is small by comparison. - let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len()); + let widened = if widen { self.rle_widening()? } else { 0 }; + let hint = self + .layer_info + .as_ref() + .map_or(0, LayerInfo::channel_data_len) + .saturating_add(self.image_data.data.len()) + .saturating_add(usize::try_from(widened).unwrap_or(usize::MAX)); let mut out = Vec::new(); out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?; - self.header.write(&mut out); + if widen { + Header { version: v, ..self.header.clone() }.write(&mut out); + } else { + self.header.write(&mut out); + } out.put_len(self.color_mode_data.len() as u64, false)?; out.put(&self.color_mode_data); resources::write_section(&mut out, &self.resources)?; @@ -175,7 +203,7 @@ impl PsdFile { if !section_empty { let li = out.begin_len(psb); if let (Some(info), false) = (&self.layer_info, in_block) { - info.write_body(&mut out, v)?; + info.write_body_as(&mut out, v, widen)?; } out.end_len(li, psb)?; let need_mask_field = self.global_layer_mask.is_some() || !self.global_blocks.is_empty() || (in_block && self.layer_info.is_some()); @@ -195,7 +223,7 @@ impl PsdFile { let long = uses_long_length(v, key); let at = out.begin_len(long); let start = out.len(); - info.write_body(&mut out, v)?; + info.write_body_as(&mut out, v, widen)?; let len = out.len() - start; out.end_len(at, long)?; match padding { @@ -211,20 +239,59 @@ impl PsdFile { out.end_len(at, psb)?; out.put_u16(self.image_data.compression.as_u16()); - out.put(&self.image_data.data); + match self.merged_widened_rows(widen)? { + 0 => out.put(&self.image_data.data), + rows => put_widened_rle(&mut out, &self.image_data.data, rows)?, + } Ok(out) } + /// The version the file is written as, and whether its RLE count tables widen on the way + /// (a PSD model marked [`Self::write_as_psb`]). + fn write_form(&self) -> (Version, bool) { + let widen = self.write_as_psb && !self.header.version.is_psb(); + (if widen { Version::Psb } else { self.header.version }, widen) + } + + /// The version [`Self::to_bytes`] writes: PSB for a PSD model marked [`Self::write_as_psb`], + /// else `header.version`. + pub fn written_version(&self) -> Version { + self.write_form().0 + } + + /// Rows of the merged image's RLE count table that widen on write (0 when nothing widens). + fn merged_widened_rows(&self, widen: bool) -> Result { + if widen && self.image_data.compression == Compression::Rle { ImageData::layout(&self.header).rows() } else { Ok(0) } + } + + /// Bytes every RLE count table of this PSD model grows by when written as PSB; an error + /// when a table is too short for its rows. + fn rle_widening(&self) -> Result { + let mut n = 0u64; + for layer in self.layers() { + for c in &layer.channels { + match layer.widened_rows(c, true)? { + 0 => {} + rows => n = n.saturating_add(rle_widening(&c.data, rows)?), + } + } + } + match self.merged_widened_rows(true)? { + 0 => Ok(n), + rows => Ok(n.saturating_add(rle_widening(&self.image_data.data, rows)?)), + } + } + /// The number of bytes [`Self::to_bytes`] writes, computed without serializing the channel /// data (only the layer records, which are small, are serialized to measure them). Lets a /// writer check a file against the 2 GB PSD limit before choosing the version. pub fn encoded_len(&self) -> Result { - let v = self.header.version; + let (v, widen) = self.write_form(); let psb = v.is_psb(); let len_field = |long: bool| if long { 8u64 } else { 4 }; let blocks_len = |blocks: &[TaggedBlock]| blocks.iter().fold(0u64, |n, b| n.saturating_add(b.encoded_len_aligned(v, 4) as u64)); let body_len = |info: &LayerInfo| -> Result { - let unpadded = info.unpadded_len(v)?; + let unpadded = info.unpadded_len_as(v, widen)?; let padding = info.padding.as_ref().map_or(unpadded % 2, |p| p.len() as u64); Ok(unpadded.saturating_add(padding)) }; @@ -252,45 +319,38 @@ impl PsdFile { } n = n.saturating_add(self.layer_mask_trailing.len() as u64); } - Ok(n.saturating_add(2).saturating_add(self.image_data.data.len() as u64)) + let merged = match self.merged_widened_rows(widen)? { + 0 => 0, + rows => rle_widening(&self.image_data.data, rows)?, + }; + Ok(n.saturating_add(2).saturating_add(self.image_data.data.len() as u64).saturating_add(merged)) } - /// Turns a PSD into the equivalent PSB in place, without re-encoding any pixels: the RLE - /// row-count tables of the layer channels and the merged image widen from two to four bytes - /// per row (the packed rows are the same in both versions), and the length fields widen when - /// the file is written. Raw and ZIP channel data is the same in both. A PSB is left as is. + /// Marks a PSD model to be written as the equivalent PSB ([`Self::write_as_psb`]) without + /// touching or re-encoding any pixels: the packed RLE rows are the same in both versions, so + /// [`Self::to_bytes`] only widens the row-count tables of the layer channels and the merged + /// image (two to four bytes per row) and the length fields while it copies them out. Raw and + /// ZIP channel data is the same in both. A PSB model is left as is. /// - /// Atomic: every RLE stream is checked (and the room to widen it reserved) before the first - /// is changed, so an error leaves the file untouched. The layer info padding is kept; a - /// writer that pads to an alignment re-pads for the new version. + /// Every RLE count table is checked first: an error leaves the model unmarked, and the write + /// cannot fail on a table later. The layer info padding is kept; a writer that pads to an + /// alignment re-pads with [`Self::pad_layer_info_to`]. pub fn promote_to_psb(&mut self) -> Result<()> { - if self.header.version.is_psb() { + if self.header.version.is_psb() || self.write_as_psb { return Ok(()); } - let merged_rows = match self.image_data.compression { - Compression::Rle => Some(ImageData::layout(&self.header).rows()?), - _ => None, - }; - let layers = self.layer_info.as_mut().map_or(&mut [][..], |info| &mut info.layers[..]); - let mut streams: Vec<(&mut Vec, usize)> = Vec::new(); - for layer in layers.iter_mut() { - let rects: Vec<_> = layer.channels.iter().map(|c| layer.channel_rect(c.id)).collect(); - for (c, rect) in layer.channels.iter_mut().zip(rects) { - if c.compression == Some(Compression::Rle) { - streams.push((&mut c.data, rect.size()?.1)); - } - } + self.rle_widening()?; + self.write_as_psb = true; + Ok(()) + } + + /// Pads the layer info body to a multiple of `align` bytes as it will be written (see + /// [`LayerInfo::pad_to`]), RLE count tables widened when [`Self::write_as_psb`] is set. + pub fn pad_layer_info_to(&mut self, align: u64) -> Result<()> { + let (v, widen) = self.write_form(); + if let Some(info) = &mut self.layer_info { + info.padding = Some(vec![0; info.pad_len_as(v, widen, align)?]); } - if let Some(rows) = merged_rows { - streams.push((&mut self.image_data.data, rows)); - } - for (data, rows) in &mut streams { - reserve_rle_widening(data, *rows)?; - } - for (data, rows) in streams { - widen_rle_counts(data, rows)?; - } - self.header.version = Version::Psb; Ok(()) } @@ -426,21 +486,39 @@ mod write_tests { assert_eq!(empty.encoded_len().unwrap(), empty.to_bytes().unwrap().len() as u64); } - /// Promoting a PSD gives exactly the PSB written directly from the same pixels: only the RLE - /// row counts (and the length fields, on write) widen (#5285). + /// A promoted PSD writes exactly the PSB written directly from the same pixels, and reads + /// back as that PSB; the model itself stays a PSD that every reader decodes as before (#5285). #[test] - fn promote_to_psb_equals_the_psb_written_directly() { + fn promote_to_psb_writes_the_psb_written_directly() { let cases = testgen::all_cases(); let (psd, psb) = cases.split_at(cases.len() / 2); for (psd, psb) in psd.iter().zip(psb) { assert_eq!(psd.file.header.version, Version::Psd, "{}", psd.name); let mut promoted = psd.file.clone(); promoted.promote_to_psb().unwrap(); - assert_eq!(promoted, psb.file, "{}", psd.name); - assert_eq!(promoted.to_bytes().unwrap(), psb.file.to_bytes().unwrap(), "{}", psd.name); + assert!(promoted.write_as_psb); + assert_eq!(promoted.written_version(), Version::Psb); + let bytes = promoted.to_bytes().unwrap(); + assert!(bytes == psb.file.to_bytes().unwrap(), "{}", psd.name); + assert_eq!(promoted.encoded_len().unwrap(), bytes.len() as u64, "{}", psd.name); + assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), psb.file, "{}", psd.name); + // Unchanged as a model: same header, same (two-byte) channel data. + assert_eq!(PsdFile { write_as_psb: false, ..promoted.clone() }, psd.file, "{}", psd.name); + assert_eq!(promoted.decode_merged().ok(), psd.file.decode_merged().ok(), "{}", psd.name); } } + /// Re-padding a promoted model pads what is written, as `pad_to` does for a PSB. + #[test] + fn pad_layer_info_to_pads_the_written_body() { + let mut promoted = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + promoted.promote_to_psb().unwrap(); + promoted.pad_layer_info_to(4).unwrap(); + let mut direct = testgen::layered(Version::Psb, ColorMode::Rgb, 8, Compression::Rle); + direct.layer_info.as_mut().unwrap().pad_to(Version::Psb, 4).unwrap(); + assert!(promoted.to_bytes().unwrap() == direct.to_bytes().unwrap()); + } + /// A damaged RLE table is refused before anything changes: the file stays a valid PSD. #[test] fn promote_to_psb_is_atomic() { @@ -453,6 +531,13 @@ mod write_tests { let before = file.clone(); assert!(file.promote_to_psb().is_err()); assert_eq!(file, before); + assert!(!file.write_as_psb); + // A table damaged after promotion fails the write instead of panicking. + let mut file = testgen::small(Version::Psd, Compression::Rle); + file.promote_to_psb().unwrap(); + file.image_data.data.truncate(3); + assert!(file.to_bytes().is_err()); + assert!(file.encoded_len().is_err()); } #[test] diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 5450ed7e67..fb12d09459 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -1,7 +1,7 @@ //! Layer records, layer masks, blending ranges and per-layer channel data. use crate::blend::BlendMode; -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; +use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, put_widened_rle, rle_widening}; use crate::error::{PsdError, Result}; use crate::header::{MAX_DIMENSION, Version}; use crate::io::{Reader, WriteExt, decode_legacy_name, read_pascal, write_pascal}; @@ -586,13 +586,21 @@ impl LayerRecord { Ok((LayerRecord { rect, channels, blend_mode, opacity, clipping, flags, filler, mask, blending_ranges, name, blocks, extra_trailing }, lens)) } - fn write(&self, out: &mut Vec, version: Version) -> Result<()> { + /// Rows of a channel's RLE count table that grow when a PSD model is written as PSB + /// (`widen`, see [`crate::PsdFile::promote_to_psb`]); 0 for other channels. + pub(crate) fn widened_rows(&self, c: &ChannelData, widen: bool) -> Result { + if widen && c.compression == Some(Compression::Rle) { Ok(self.channel_rect(c.id).size()?.1) } else { Ok(0) } + } + + fn write(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { self.rect.write(out); let nch = u16::try_from(self.channels.len()).map_err(|_| PsdError::LimitExceeded("too many channels"))?; out.put_u16(nch); for c in &self.channels { out.put_i16(c.id); - out.put_len(c.stored_len(), version.is_psb())?; + let rows = self.widened_rows(c, widen)?; + let grown = if rows == 0 { 0 } else { rle_widening(&c.data, rows)? }; + out.put_len(c.stored_len().saturating_add(grown), version.is_psb())?; } out.put(b"8BIM"); out.put(&self.blend_mode.key()); @@ -667,14 +675,23 @@ impl LayerInfo { /// Length of the body (layer count, records and channel data) without /// its trailing padding. pub fn unpadded_len(&self, version: Version) -> Result { + self.unpadded_len_as(version, false) + } + + /// [`Self::unpadded_len`] of the body written with its RLE count tables widened (`widen`). + pub(crate) fn unpadded_len_as(&self, version: Version, widen: bool) -> Result { let mut records = Vec::new(); records.put_i16(0); for l in &self.layers { - l.write(&mut records, version)?; + l.write(&mut records, version, widen)?; } let mut n = records.len() as u64; - for c in self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()) { - n = n.saturating_add(2).saturating_add(c.data.len() as u64); + for l in &self.layers { + for c in l.channels.iter().filter(|c| c.compression.is_some()) { + let rows = l.widened_rows(c, widen)?; + let grown = if rows == 0 { 0 } else { rle_widening(&c.data, rows)? }; + n = n.saturating_add(2).saturating_add(c.data.len() as u64).saturating_add(grown); + } } Ok(n) } @@ -690,8 +707,13 @@ impl LayerInfo { /// Number of zero bytes [`Self::pad_to`] would set, without touching `self`. pub(crate) fn pad_len(&self, version: Version, align: u64) -> Result { + self.pad_len_as(version, false, align) + } + + /// [`Self::pad_len`] for the body written with its RLE count tables widened (`widen`). + pub(crate) fn pad_len_as(&self, version: Version, widen: bool, align: u64) -> Result { let align = align.max(1); - let len = self.unpadded_len(version)?; + let len = self.unpadded_len_as(version, widen)?; Ok(((align - len % align) % align) as usize) } @@ -703,16 +725,25 @@ impl LayerInfo { /// Serializes the body without any trailing padding (the padding field is ignored). pub(crate) fn write_unpadded(&self, out: &mut Vec, version: Version) -> Result<()> { + self.write_unpadded_as(out, version, false) + } + + /// [`Self::write_unpadded`], widening the RLE count tables of a PSD model written as PSB + /// (`widen`) on the way out. + fn write_unpadded_as(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?; out.put_i16(if self.merged_alpha { -n } else { n }); for l in &self.layers { - l.write(out, version)?; + l.write(out, version, widen)?; } for l in &self.layers { for c in &l.channels { if let Some(comp) = c.compression { out.put_u16(comp.as_u16()); - out.put(&c.data); + match l.widened_rows(c, widen)? { + 0 => out.put(&c.data), + rows => put_widened_rle(out, &c.data, rows)?, + } } } } @@ -720,9 +751,15 @@ impl LayerInfo { } /// Serializes the body (without a length field). + #[cfg(test)] pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { + self.write_body_as(out, version, false) + } + + /// [`Self::write_body`], widening RLE count tables when `widen` (see [`Self::write_unpadded_as`]). + pub(crate) fn write_body_as(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { let start = out.len(); - self.write_unpadded(out, version)?; + self.write_unpadded_as(out, version, widen)?; match &self.padding { Some(p) => out.put(p), None => { diff --git a/crates/psd/src/testgen.rs b/crates/psd/src/testgen.rs index d2d4784cb9..818c33bae0 100644 --- a/crates/psd/src/testgen.rs +++ b/crates/psd/src/testgen.rs @@ -124,6 +124,7 @@ pub fn merged_only(version: Version, mode: ColorMode, depth: u16, compression: C global_blocks: Vec::new(), layer_mask_trailing: Vec::new(), image_data, + write_as_psb: false, } } @@ -316,6 +317,7 @@ pub fn layered(version: Version, mode: ColorMode, depth: u16, compression: Compr global_blocks: blocks, layer_mask_trailing: Vec::new(), image_data, + write_as_psb: false, } } @@ -351,6 +353,7 @@ pub fn small(version: Version, compression: Compression) -> PsdFile { global_blocks: vec![TaggedBlock::new(*b"Patt", vec![1, 2])], layer_mask_trailing: Vec::new(), image_data: ImageData::encode(compression, &planes, &header).expect("encode"), + write_as_psb: false, } } diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs index 7c8b1940d5..acf4887c9c 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -221,6 +221,7 @@ impl ImageSourceData { global_blocks: self.global_blocks, layer_mask_trailing: self.trailing, image_data, + write_as_psb: false, } } } From d5056fc5bfee9ac2159d95e93095620cccb3b594 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 23:15:20 +0200 Subject: [PATCH 09/73] Channels: CMYK channels duplicate, load, split and merge as tone, not ink (#5787) CMYK pixels are stored as ink (1 = full ink), but the Channels panel and Photoshop show a CMYK channel as its tone (white = no ink). The engine copied raw ink, so on a white CMYK document Duplicate Channel of Cyan made a black alpha, Load Selection from Cyan selected nothing, Split Channels made black grayscale documents, Merge Channels of white documents made a black CMYK image, and channel copy/paste was inverted. A small `tone(mode, v)` helper (1 - v for CMYK, its own inverse) now reads a CMYK colour channel as tone in ref_planes (Duplicate, Load Selection, Calculations, Apply Image sources), Split Channels and channel copy, and writes tone back as ink in Merge Channels, channel paste and Apply Image of a single plane onto a CMYK layer. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/channel_clip.rs | 8 ++- crates/engine/src/channel_clip/tests.rs | 25 ++++++++ crates/engine/src/channel_cmds.rs | 19 ++++-- crates/engine/src/channel_cmds/tests.rs | 77 +++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs index 86a49b0be6..a23608f328 100644 --- a/crates/engine/src/channel_clip.rs +++ b/crates/engine/src/channel_clip.rs @@ -59,12 +59,14 @@ pub(crate) fn copy(s: &mut Session) -> Result> { return Err(EngineError::Other("Could not copy: the selected area is empty".into())); } let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, true); + let mode = src.format().mode; let values = crate::allocation::read_region(src, area, "copying a channel")?; let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?; let mut px = crate::allocation::capacity(len, "copying a channel")?; for (i, p) in values.chunks_exact(n).enumerate() { - px.push(p.get(k).copied().unwrap_or(0.0)); + // A CMYK channel copies as its tone (#5787). + px.push(p.get(k).map_or(0.0, |&v| crate::channel_cmds::tone(mode, v))); px.push(cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0))); } let mut surface = Surface::new(fmt); @@ -91,7 +93,7 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit: let area = src.content_bounds().intersect(&canvas); s.edit(label, |doc, _| { let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - let n = surf.format().channels(); + let (n, mode) = (surf.format().channels(), surf.format().mode); if k >= n { return Err(EngineError::Other(format!("no colour channel {k} in this layer"))); } @@ -105,7 +107,7 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit: let mut px = crate::allocation::read_region(surf, area, "pasting into a channel")?; for (i, (dst, s)) in px.chunks_exact_mut(n).zip(&rgba).enumerate() { let w = s[3] * weight.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); - let v = photocraft_color::convert::rgb_to_gray([s[0], s[1], s[2]]); + let v = crate::channel_cmds::tone(mode, photocraft_color::convert::rgb_to_gray([s[0], s[1], s[2]])); if let Some(c) = dst.get_mut(k) { *c += (v - *c) * w.clamp(0.0, 1.0); } diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs index 3d89c8f647..cf35bef93e 100644 --- a/crates/engine/src/channel_clip/tests.rs +++ b/crates/engine/src/channel_clip/tests.rs @@ -72,6 +72,31 @@ fn alpha_channels_copy_and_paste_into_colour_channels() { assert!(near(&px(&s, 30, 15), &[0.0, 0.0, 0.0, 1.0])); } +#[test] +fn cmyk_channels_copy_and_paste_as_tone() { + // #5787: copying a CMYK channel gives its tone (white where there is no ink), and pasting a + // tone into a CMYK channel writes it back as ink. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let clip = &s.clipboard.as_ref().unwrap().surface; + assert!((clip.pixel(30, 5)[0] - 1.0).abs() < 1e-3, "depth {depth}: no ink copies as white"); + assert!((clip.pixel(5, 5)[0] - (1.0 - left[0])).abs() < 1e-3, "depth {depth}: ink copies dark"); + // Cyan pasted into Black: black gets cyan's ink, and white stays white. + s.execute("channel.target", json!({"channel": "black"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: no ink stays no ink, {:?}", px(&s, 30, 5)); + let p = px(&s, 5, 5); + assert!((p[3] - left[0]).abs() < 2e-3 && near(&p[..3], &left[..3]), "depth {depth}: black = old cyan, {p:?} vs {left:?}"); + } +} + #[test] fn copy_an_alpha_channel_without_a_pixel_layer() { let mut s = session(8); diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index 00f3ec4e31..5956bccdfc 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -226,6 +226,13 @@ fn materialize(s: &mut Surface, r: Rect) { s.write_region(r, &v); } +/// A colour channel sample as the Channels panel shows it: CMYK stores ink (1 = full ink) but a +/// CMYK channel reads as its tone (white = no ink), as in Photoshop. Its own inverse, so it also +/// turns a tone back into ink. Other modes are unchanged. +pub(crate) fn tone(mode: ColorMode, v: f32) -> f32 { + if mode == ColorMode::Cmyk { 1.0 - v } else { v } +} + fn luminosity(rgba: [f32; 4]) -> f32 { 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2] } @@ -355,7 +362,10 @@ fn ref_planes(doc: &Document, layer: Option, active: Option, r let (px, n) = native_pixels(doc, layer)?; let planes: Vec> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect(); match r { - ChanRef::Color(k) => vec![planes.get(k).cloned().ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?], + ChanRef::Color(k) => { + let plane = planes.get(k).ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?; + vec![plane.iter().map(|&v| tone(edit_mode(doc), v)).collect()] + } _ => planes, } } @@ -1484,7 +1494,7 @@ fn split(s: &mut Session, p: &Value) -> Result { let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default(); let mut docs: Vec = Vec::new(); for (c, name) in names.iter().enumerate() { - let plane: Vec = px.chunks_exact(n).map(|p| p[c]).collect(); + let plane: Vec = px.chunks_exact(n).map(|p| tone(mode, p[c])).collect(); docs.push(gray_document(&format!("{}_{}", doc.name, short(name)), &doc, &plane)); } for ch in &doc.channels { @@ -1551,7 +1561,7 @@ fn merge(s: &mut Session, p: &Value) -> Result { let mut data = Vec::with_capacity(npx * fmt.channels()); for i in 0..npx { for pl in &planes[..cc] { - data.push(pl[i].clamp(0.0, 1.0)); + data.push(tone(mode, pl[i]).clamp(0.0, 1.0)); } data.push(1.0); } @@ -1627,7 +1637,8 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // source-over, so applying to an empty layer copies the source in any mode. let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; for (c, b) in px[..colors].iter_mut().enumerate() { - let top = src.get(c).unwrap_or(&src[0])[i]; + // One plane is a tone (a channel, a mask): a CMYK layer takes it as ink. + let top = if src.len() > 1 { src.get(c).unwrap_or(&src[0])[i] } else { tone(sf.mode, src[0][i]) }; let blended = top + (blending.apply(*b, top) - top) * base_a; *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; } diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 1d721ee5c5..673f8e45c4 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -120,6 +120,38 @@ fn load_transparency_mask_and_composite() { assert_eq!(sel_at(&s, 10, 5), 1.0); } +/// A white CMYK document (no ink anywhere) whose left half carries some cyan ink. +fn cmyk_session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + rect(&mut s, 0, 0, 20, 20, "replace"); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +#[test] +fn cmyk_channels_duplicate_and_load_as_tone_not_ink() { + // #5787: a CMYK channel is its tone, as the Channels panel draws it: white where there is no ink. + // (The merged image goes through RGB, so inked pixels may drift a few levels.) + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let ink = px(&s, 5, 5)[0]; + assert!(ink > 0.5 && px(&s, 30, 5)[0] == 0.0, "depth {depth}: cyan ink on the left only, {ink}"); + s.execute("channel.duplicate", json!({"channel": "cyan"})).unwrap(); + assert_eq!(doc(&s).channels[0].name, "Cyan copy"); + assert!((chan(&s, 0, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: no ink duplicates as white"); + assert!((chan(&s, 0, 5, 5) - (1.0 - ink)).abs() < 0.02, "depth {depth}: ink duplicates dark"); + s.execute("select.loadSelection", json!({"channel": "cyan"})).unwrap(); + assert!((sel_at(&s, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: no ink is selected"); + assert!((sel_at(&s, 5, 5) - (1.0 - ink)).abs() < 0.02, "depth {depth}"); + // Calculations read the same tone. + let r = s.execute("image.calculations", json!({"source1": {"channel": "cyan"}, "source2": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + let i = r["channel"].as_u64().unwrap() as usize; + assert!((chan(&s, i, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}"); + } +} + #[test] fn channel_management_and_view_state() { let mut s = session(); @@ -592,6 +624,27 @@ fn apply_image_into_alpha_channel() { assert!(chan(&s, 0, 3, 3) < 0.01); } +#[test] +fn cmyk_apply_image_of_a_colour_channel_keeps_ink_and_tone_apart() { + // #5787: the Cyan channel is read as tone and written back as ink, so applying it onto its own + // CMYK layer leaves cyan as it was, and into an alpha channel it lands as tone. (The merged + // image goes through RGB, so a few levels of drift are allowed.) + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let before = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + let after = px(&s, 5, 5); + assert!((after[0] - before.0[0]).abs() < 0.02, "depth {depth}: cyan unchanged, {after:?} vs {:?}", before.0); + assert!(px(&s, 30, 5).iter().zip(&before.1).all(|(a, b)| (a - b).abs() < 1e-3), "depth {depth}: no ink stays no ink"); + s.undo(); + s.execute("image.applyImage", json!({"blending": "normal"})).unwrap(); + assert!(px(&s, 5, 5).iter().zip(&before.0).all(|(a, b)| (a - b).abs() < 0.02), "depth {depth}: CMYK onto itself is a no-op"); + s.execute("channel.new", json!({"fill": "black"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + assert!((chan(&s, 0, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: tone into an alpha channel"); + } +} + #[test] fn calculations_results() { let mut s = session(); @@ -652,6 +705,30 @@ fn split_and_merge_channels() { assert!(s.execute("channel.merge", json!({"mode": "cmyk"})).is_err()); } +#[test] +fn cmyk_split_and_merge_use_tone() { + // #5787: Split Channels of a white CMYK image gives white grayscale documents, and merging + // them back gives the same CMYK pixels (within the few levels the merged image's trip + // through RGB costs). + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("channel.split", json!({})).unwrap(); + assert_eq!(s.documents().len(), 4); + let v = |s: &Session, i: usize, x: i32| s.documents()[i].doc.layers[0].surface().unwrap().pixel(x, 5)[0]; + for i in 0..4 { + assert!((v(&s, i, 30) - 1.0).abs() < 1e-3, "depth {depth}: channel {i} of white is white"); + } + assert!((v(&s, 0, 5) - (1.0 - left[0])).abs() < 0.02, "depth {depth}: cyan ink splits dark"); + s.set_active(0); + s.execute("channel.merge", json!({"mode": "cmyk", "documents": [0, 1, 2, 3]})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Cmyk); + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.02); + assert!(near(&px(&s, 5, 5), &left), "depth {depth}: round trip {:?} vs {left:?}", px(&s, 5, 5)); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: white stays white {:?}", px(&s, 30, 5)); + } +} + #[test] fn merge_rejects_a_repeated_source_and_keeps_unrelated_documents() { // #934: `documents: [0, 0, 1]` passed validation, then the close loop ran `close(1)`, From aa988058771e5337720e4e343ca5454efc201dbe Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 01:30:16 +0200 Subject: [PATCH 10/73] WIP: PSD: Frame layers keep their stroke (#4381) From 1fa18cb4475b229132268b83c5fefd28164beee7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 03:04:25 +0200 Subject: [PATCH 11/73] Compose: Transparency Shapes Layer off blends a layer's alpha as Fill in the special eight (#5692) With Transparency Shapes Layer off, Photoshop composites a pixel of alpha a at Fill f in Color Burn/Dodge, Linear Burn/Dodge, Vivid/Linear Light, Hard Mix and Difference as an opaque pixel at Fill a x f: the alpha pulls the source toward the mode's neutral colour inside the blend, and only Opacity x masks cover the backdrop. Masks keep acting as coverage, and the other modes look the same either way. Measured in Photoshop on generated documents (12 modes, Opacity 100/53, Fill 100/50, alpha 10-100 %, a 10-100 % mask, a half-transparent backdrop and an isolated group): the model is within 2 levels everywhere (Hard Mix near full alpha within 4, from 8-bit rounding). The CPU compositor folds the content alpha (masks divided out) into Fill for such layers; the GPU compositor has no pass for it, so advanced_active sends those documents to the CPU. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/compose/src/advanced.rs | 12 ++- crates/compose/src/advanced_tests.rs | 117 +++++++++++++++++++++++++++ crates/compose/src/lib.rs | 28 ++++++- crates/gpu/tests/parity.rs | 19 +++++ 4 files changed, 172 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 6809c9e865..db32eff036 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -12,7 +12,9 @@ //! composites onto the result in its own mode, kept inside the base's shape (its alpha with //! masks, times its opacity). //! - **Transparency Shapes Layer off.** The layer's effects and knockout cover the whole layer -//! (its masks still apply) instead of following its transparency. +//! (its masks still apply) instead of following its transparency. In the special eight +//! ([`crate::psblend::fill_is_special`]) the layer's own transparency then blends as Fill does +//! (`blend_layer_into` in the crate root; measured in Photoshop, #5692). //! - **Layer / Vector Mask Hides Effects.** The effects are built from the layer without that //! mask, and the mask is applied to the finished layer and effects. //! @@ -75,7 +77,13 @@ pub fn advanced_active(layer: &Layer, clipped: &[Layer]) -> bool { return false; } let fx = effects::has_effects(layer); - a.knockout != Knockout::None || clips_individually(layer, clipped) || (a.blend_interior && fx) || (!a.transparency_shapes && fx) || hides_effects(layer) + // Transparency Shapes Layer off changes the special eight's blend itself (#5692). + let shapeless_blend = crate::psblend::fill_is_special(layer.blend) && !matches!(layer.content, LayerContent::Adjustment(_)); + a.knockout != Knockout::None + || clips_individually(layer, clipped) + || (a.blend_interior && fx) + || (!a.transparency_shapes && (fx || shapeless_blend)) + || hides_effects(layer) } /// Whether the layer's effects (or knockout) cover the whole layer: Transparency Shapes Layer diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index c19b0dc92f..601912901c 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -500,3 +500,120 @@ fn deep_knockout_reveals_a_localized_background() { check(&d, 2, 2, [0.0; 4], "an unlocked layer named Background"); } } + +/// Transparency Shapes Layer off in the special eight: the layer's own transparency blends as +/// Fill does (#5692). Measured in Photoshop: Background (90, 110, 130), a layer (200, 150, 80) at +/// alpha 30 % (77) and 70 % (179) in columns 0–5 and 6–11, read from the flattened 8-bit PNG. +#[test] +fn transparency_shapes_off_blends_alpha_as_fill() { + const A30: f32 = 77.0 / 255.0; + const A70: f32 = 179.0 / 255.0; + let c8 = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0]; + let px = |c: [u8; 3], a: f32| { + let c = c8(c); + [c[0], c[1], c[2], a] + }; + let make = |depth: SampleType, mode: BlendMode, opacity: f32, fill: f32, tsl: bool| { + let b = c8([90, 110, 130]); + let mut d = Document::with_background("t", Size::new(12, 8), ColorMode::Rgb, depth, Color::rgb(b[0], b[1], b[2])); + let mut l = solid(&d, "a30", Rect::new(0, 0, 6, 8), px([200, 150, 80], A30)); + l.surface_mut().unwrap().fill_rect(Rect::new(6, 0, 12, 8), &photocraft_raster::from_rgba(&d.pixel_format(), px([200, 150, 80], A70))); + l.blend = mode; + l.opacity = opacity; + l.fill_opacity = fill; + l.advanced.transparency_shapes = tsl; + d.layers.push(l); + d + }; + let (o53, f50) = (135.0 / 255.0, 128.0 / 255.0); + // (mode, opacity, fill, off at 30 %, off at 70 %, on at 30 %, on at 70 %) + type Rgb = [u8; 3]; + let measured: [(BlendMode, f32, f32, Rgb, Rgb, Rgb, Rgb); 7] = [ + (BlendMode::ColorDodge, o53, 1.0, [105, 123, 137], [148, 151, 150], [117, 133, 139], [151, 164, 152]), + (BlendMode::ColorBurn, o53, 1.0, [84, 99, 113], [74, 79, 69], [83, 94, 109], [73, 72, 82]), + (BlendMode::LinearDodge, o53, 1.0, [122, 134, 143], [164, 166, 160], [117, 133, 143], [151, 164, 160]), + (BlendMode::HardMix, o53, 1.0, [98, 111, 119], [133, 117, 75], [117, 133, 109], [151, 164, 82]), + (BlendMode::Difference, o53, 1.0, [58, 86, 117], [69, 54, 100], [93, 99, 117], [97, 84, 100]), + (BlendMode::ColorDodge, 1.0, f50, [102, 121, 136], [125, 139, 146], [108, 124, 137], [131, 142, 147]), + (BlendMode::Difference, 1.0, f50, [59, 87, 118], [19, 57, 102], [66, 87, 118], [34, 57, 102]), + ]; + for depth in DEPTHS { + for (mode, opacity, fill, off30, off70, on30, on70) in measured { + // A 32-bit document's Linear Dodge doesn't clip at 1 (psblend::HDR). + if depth == SampleType::F32 && mode == BlendMode::LinearDodge { + continue; + } + let what = format!("{mode:?} opacity {opacity} fill {fill}"); + let off = make(depth, mode, opacity, fill, false); + check(&off, 2, 4, px(off30, 1.0), &format!("{what}, off, alpha 30 %")); + check(&off, 9, 4, px(off70, 1.0), &format!("{what}, off, alpha 70 %")); + let on = make(depth, mode, opacity, fill, true); + check(&on, 2, 4, px(on30, 1.0), &format!("{what}, on, alpha 30 %")); + check(&on, 9, 4, px(on70, 1.0), &format!("{what}, on, alpha 70 %")); + assert!(advanced_active(&off.layers[1], &[]), "{what}: the GPU leaves it to the CPU"); + } + // Modes outside the special eight look the same either way, and stay on the plain path. + for mode in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Overlay] { + let (off, on) = (make(depth, mode, o53, f50, false), make(depth, mode, o53, f50, true)); + assert_eq!(render(&off, off.bounds()).px, render(&on, on.bounds()).px, "{mode:?}"); + assert!(!advanced_active(&off.layers[1], &[]), "{mode:?}"); + } + } +} + +/// A mask is not the layer's transparency: Photoshop draws an opaque layer under a 30 % mask the +/// same with the option on or off (measured: Color Dodge, Hard Mix, Difference and the rest of +/// the special eight, every Opacity and Fill tried). Over a half-transparent backdrop and for an +/// isolated group the alpha still blends as Fill (measured: Color Dodge at 53 %). +#[test] +fn transparency_shapes_off_ignores_masks_and_reaches_groups() { + let c8 = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0]; + let px = |c: [u8; 3], a: f32| { + let c = c8(c); + [c[0], c[1], c[2], a] + }; + let o53 = 135.0 / 255.0; + for depth in DEPTHS { + for mode in [BlendMode::ColorDodge, BlendMode::HardMix, BlendMode::Difference] { + let render_with = |tsl: bool| { + let b = c8([90, 110, 130]); + let mut d = Document::with_background("t", Size::new(12, 8), ColorMode::Rgb, depth, Color::rgb(b[0], b[1], b[2])); + let mut l = solid(&d, "l", full(&d), px([200, 150, 80], 1.0)); + l.blend = mode; + l.opacity = o53; + l.mask = Some(LayerMask { surface: photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[77.0 / 255.0]), ..LayerMask::reveal_all() }); + l.advanced.transparency_shapes = tsl; + d.layers.push(l); + render(&d, d.bounds()).px + }; + let (off, on) = (render_with(false), render_with(true)); + assert!(off.iter().zip(&on).all(|(a, b)| close(*a, *b)), "{mode:?} ({depth:?}): a mask isn't the layer's transparency"); + } + // Color Dodge at 53 % over a backdrop of alpha 50 % (128): (118, 127, 129, 148) at + // alpha 30 %, (162, 151, 131, 175) at 70 %. + let mut d = doc(depth, false); + d.layers.push(solid(&d, "under", full(&d), px([90, 110, 130], 128.0 / 255.0))); + let mut l = solid(&d, "a30", Rect::new(0, 0, 6, 8), px([200, 150, 80], 77.0 / 255.0)); + l.surface_mut().unwrap().fill_rect(Rect::new(6, 0, 12, 8), &photocraft_raster::from_rgba(&d.pixel_format(), px([200, 150, 80], 179.0 / 255.0))); + l.blend = BlendMode::ColorDodge; + l.opacity = o53; + l.advanced.transparency_shapes = false; + d.layers.push(l.clone()); + check(&d, 2, 4, px([118, 127, 129], 148.0 / 255.0), "half-transparent backdrop, alpha 30 %"); + check(&d, 9, 4, px([162, 151, 131], 175.0 / 255.0), "half-transparent backdrop, alpha 70 %"); + // An isolated Color Dodge group at 53 % holding the Normal layer: the group's alpha blends + // as Fill, as a layer's does. + let b = c8([90, 110, 130]); + let mut d = Document::with_background("t", Size::new(12, 8), ColorMode::Rgb, depth, Color::rgb(b[0], b[1], b[2])); + l.blend = BlendMode::Normal; + l.opacity = 1.0; + l.advanced.transparency_shapes = true; + let mut g = Layer::group("g", vec![l]); + g.blend = BlendMode::ColorDodge; + g.opacity = o53; + g.advanced.transparency_shapes = false; + d.layers.push(g); + check(&d, 2, 4, px([105, 123, 137], 1.0), "group, alpha 30 %"); + check(&d, 9, 4, px([148, 151, 150], 1.0), "group, alpha 70 %"); + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b742540b95..2dad388405 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1464,12 +1464,12 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); p[3] *= mask_k(&mask, i); } - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0); + blend_layer_into(backdrop, &content, layer, cx, 1.0); return; } let Some(mut content) = render_content(layer, rect, cx) else { return }; advanced::composite_clipped(clipped, &mut content, cx); - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer)); + blend_layer_into(backdrop, &content, layer, cx, text_gamma(layer)); } /// A layer with effects (and its clipping group) onto `backdrop`. @@ -1842,6 +1842,30 @@ fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32 blend_into_g(backdrop, src, mode, opacity, 1.0); } +/// `layer`'s masked content `src` blended into the backdrop with its own mode, Opacity and Fill +/// ([`blend_into_fill`]). With Transparency Shapes Layer off, the special eight +/// ([`psblend::fill_is_special`]) take the layer's own transparency (its content's alpha, not its +/// masks) inside the blend, as Fill: Photoshop composites a pixel of alpha `a` at Fill `f` as +/// an opaque one at Fill `a × f`, covering the backdrop with Opacity × masks only. Other modes +/// look the same either way (#5692). +fn blend_layer_into(backdrop: &mut Buffer, src: &Buffer, layer: &Layer, cx: &Ctx, gamma: f32) { + let (mode, opacity, fill) = (layer.blend, layer.opacity, layer.fill_opacity); + if layer.advanced.transparency_shapes || !psblend::fill_is_special(mode) { + return blend_into_fill(backdrop, src, mode, opacity, fill, gamma); + } + let mv = mask_vals(layer, backdrop.rect, cx); + let fill = fill.clamp(0.0, 1.0); + for (i, (b, s)) in backdrop.px.iter_mut().zip(&src.px).enumerate() { + // `src` carries alpha × masks; split them again. + let m = mv.as_ref().map_or(1.0, |v| v.get(i).copied().unwrap_or(1.0)); + if s[3] <= 0.0 || m <= 0.0 { + continue; + } + let alpha = (s[3] / m).clamp(0.0, 1.0); + *b = psblend::composite_fill(mode, *b, [s[0], s[1], s[2], m], opacity, fill * alpha, gamma); + } +} + /// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for /// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise. fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs index 84d3d0e937..80489b46f5 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/parity.rs @@ -2618,3 +2618,22 @@ fn pass_through_clipping_base_with_an_adjustment() { d.layers.push(clip); check(&mut g, &d, "pass-through clipping base with an adjustment"); } + +/// Transparency Shapes Layer off changes the special eight's blend (the layer's alpha blends as +/// Fill, #5692); the GPU has no pass for it and leaves such documents to the CPU. Other modes look +/// the same either way and stay on the GPU. +#[test] +fn transparency_shapes_off_special_blend_falls_back_to_the_cpu() { + let Some(mut g) = gpu() else { return }; + let mut d = base_doc(64, 48); + let mut l = noise_layer("top", PixelFormat::RGBA8, Rect::new(4, 3, 60, 45), 2, 0.0); + l.blend = BlendMode::ColorDodge; + l.opacity = 0.53; + l.advanced.transparency_shapes = false; + d.layers.push(l); + assert!(render_to_vec(&mut g.comp, &g.device, &g.queue, &d, d.bounds()).is_err(), "Color Dodge with Transparency Shapes Layer off"); + if let Some(l) = d.layers.last_mut() { + l.blend = BlendMode::Multiply; + } + check(&mut g, &d, "Multiply with Transparency Shapes Layer off"); +} From f8e6d9666a2f9cb94a0564fec6f50cbb21ce95b7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 11:42:40 +0200 Subject: [PATCH 12/73] PSD: Frame layers keep their stroke (#4381) A Photoshop Frame is a group whose record carries the frame outline as a vector mask and its Properties > Stroke as a shape-style `vstk`. We dropped that `vstk`, so frames lost their stroke. `Group::frame_stroke` now holds it: read from and written back to PSD (byte-identical while unchanged), saved in .pcraft, and drawn along the vector mask above the frame's content by the CPU compositor and the GPU planner. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/compose/src/lib.rs | 20 +++- crates/compose/src/shape_split.rs | 17 +++ crates/doc/src/lib.rs | 8 +- crates/engine/src/layer_menu_cmds/tests.rs | 2 +- crates/engine/src/smart_cmds/unpack.rs | 2 +- crates/engine/src/web_cmds/tests.rs | 7 +- crates/format/src/convert.rs | 13 ++- crates/format/src/manifest.rs | 3 + crates/format/tests/frame_stroke.rs | 37 +++++++ crates/gpu/src/plan.rs | 21 +++- crates/gpu/tests/parity.rs | 30 ++++++ crates/io/src/affinity.rs | 4 +- crates/io/src/psd_export.rs | 18 +++- crates/io/src/psd_import.rs | 4 +- crates/io/src/svg.rs | 4 +- crates/io/tests/psd_frame_stroke.rs | 117 +++++++++++++++++++++ 16 files changed, 286 insertions(+), 21 deletions(-) create mode 100644 crates/format/tests/frame_stroke.rs create mode 100644 crates/io/tests/psd_frame_stroke.rs diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b742540b95..c2bab4d8d5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -741,7 +741,7 @@ pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { } match &layer.content { LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(frame_stroke_bounds(layer, canvas), |acc, c| { let b = layer_bounds(c, canvas); if b.is_empty() { acc @@ -777,6 +777,12 @@ pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { } } +/// Where a Photoshop Frame's stroke ([`shape_split::frame_shape`]) draws, within `canvas`; empty +/// for other layers. +fn frame_stroke_bounds(layer: &Layer, canvas: Rect) -> Rect { + shape_split::frame_shape(layer).and_then(|sh| shape_bounds(&sh)).map_or(Rect::EMPTY, |r| r.intersect(&canvas)) +} + /// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's /// children count with their own effects (a child's outside stroke shapes the group's drop /// shadow and must not be cut off at the child's pixels, #3274). @@ -937,6 +943,10 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { p[3] *= k; } } + // A Frame's stroke lies over its masked content; the frame doesn't clip it. + if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) { + blend_into(&mut buf, &surface_to_buffer(&stroke, rect), BlendMode::Normal, 1.0); + } Some(buf) } @@ -1129,7 +1139,7 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { } let own = match &layer.content { LayerContent::Group(g) if g.artboard.is_none() => { - let mut acc = Rect::EMPTY; + let mut acc = frame_stroke_bounds(layer, canvas); for c in g.children.iter().filter(|c| c.visible) { let b = composite_bounds(c, canvas)?; if !b.is_empty() { @@ -1395,6 +1405,10 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer }; } } + // A Frame's stroke over the frame's content, at the group's opacity. + if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) { + blend_into(backdrop, &surface_to_buffer(&stroke, rect), BlendMode::Normal, opacity); + } // Layers clipped to a pass-through group sit atop the group's // isolated rendering; their effect (isolated result with vs. without // them, each placed over the original backdrop) is added to the @@ -1565,7 +1579,7 @@ fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHash format!("{:?}", c.blend).hash(h); layer_identity(c, h); } - format!("{:?}", g.artboard).hash(h); + format!("{:?}{:?}", g.artboard, g.frame_stroke).hash(h); } LayerContent::Fill(f) => { format!("{f:?}").hash(h); diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index 9f0143f889..3380975d0f 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -8,6 +8,7 @@ use std::sync::{Mutex, OnceLock}; use photocraft_color::{PixelFormat, SampleType}; use photocraft_doc::vector::ShapeLayer; +use photocraft_doc::{Layer, LayerContent}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -96,6 +97,22 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac Some(parts) } +/// The stroke-only shape a Photoshop Frame's stroke draws: `Group::frame_stroke` along the +/// group's enabled vector mask (the frame outline). `None` for other layers and for a frame +/// without a visible stroke or a vector mask. +pub fn frame_shape(layer: &Layer) -> Option { + let LayerContent::Group(g) = &layer.content else { return None }; + let stroke = g.frame_stroke.as_ref().filter(|s| s.width.is_finite() && s.width > 0.0 && s.opacity > 0.0)?; + let vm = layer.vector_mask.as_ref().filter(|m| m.enabled && !m.path.is_empty())?; + Some(ShapeLayer { path: vm.path.clone(), fill: None, stroke: Some(stroke.clone()), ..ShapeLayer::default() }) +} + +/// A Photoshop Frame's stroke ([`frame_shape`]) rendered over `canvas` in RGBA at `depth`, from +/// the same cache as the shape strokes. It goes above the frame's (masked) content. +pub fn frame_stroke(layer: &Layer, canvas: Rect, depth: SampleType) -> Option { + split(&frame_shape(layer)?, canvas, depth).map(|(_, stroke)| stroke) +} + /// Fits the stroke part to the shape's own pixels: where they reach past the fill, the stroke /// covers what the fill doesn't (`(pixels - fill) / (1 - fill)`), in the pixels' colour where we /// drew no stroke, and elsewhere in the colour that, drawn over the fill, gives back the pixels' diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c4f7f523d1..938e23637c 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -318,6 +318,10 @@ pub struct Group { pub expanded: bool, /// Set when this (top-level) group is an artboard: children are clipped to its rect. pub artboard: Option, + /// A Photoshop Frame's stroke (Properties › Stroke; PSD `vstk` on the frame group): drawn + /// along the group's enabled vector mask (the frame outline), above the framed content and + /// not clipped by the frame. Ignored without a vector mask. + pub frame_stroke: Option, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -698,7 +702,7 @@ impl Layer { Self::new(name, LayerContent::Raster(Surface::new(format))) } pub fn group(name: impl Into, children: Vec) -> Self { - let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true, artboard: None })); + let mut l = Self::new(name, LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None })); l.blend = BlendMode::PassThrough; l } @@ -1496,7 +1500,7 @@ mod tests { assert_eq!(LayerContent::Adjustment(Adjustment::Invert).article(), "an"); assert_eq!(LayerContent::Adjustment(Adjustment::Invert).kind_name(), "Adjustment"); assert_eq!(LayerContent::Raster(Surface::new(PixelFormat::RGBA8)).article(), "a"); - assert_eq!(LayerContent::Group(Group { children: Vec::new(), expanded: true, artboard: None }).article(), "a"); + assert_eq!(LayerContent::Group(Group { children: Vec::new(), expanded: true, artboard: None, frame_stroke: None }).article(), "a"); } } diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/layer_menu_cmds/tests.rs index 46688500b1..7e37e7d5c0 100644 --- a/crates/engine/src/layer_menu_cmds/tests.rs +++ b/crates/engine/src/layer_menu_cmds/tests.rs @@ -400,7 +400,7 @@ fn stack_modes_render_from_the_nested_layers() { surf.write_region(Rect::new(3, 3, 4, 4), &photocraft_raster::from_rgba(&fmt, [v, v, v, 1.0])); kids.push(l); } - let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None })); + let g = Layer::new("stack", LayerContent::Group(photocraft_doc::Group { children: kids, expanded: true, artboard: None, frame_stroke: None })); let smart = crate::smart_cmds::layer_to_smart(doc, &g)?; let id = smart.id; doc.layers = vec![smart]; diff --git a/crates/engine/src/smart_cmds/unpack.rs b/crates/engine/src/smart_cmds/unpack.rs index 0fdf3ac3fa..af7510da8d 100644 --- a/crates/engine/src/smart_cmds/unpack.rs +++ b/crates/engine/src/smart_cmds/unpack.rs @@ -161,7 +161,7 @@ fn unpacked(so: &Layer, mut layers: Vec) -> Layer { g.id = LayerId::fresh(); g.psd_id = None; g.blend = blend; - g.content = LayerContent::Group(Group { children: layers, expanded: true, artboard: None }); + g.content = LayerContent::Group(Group { children: layers, expanded: true, artboard: None, frame_stroke: None }); detach_psd(&mut g); g } diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs index c3ffe6edce..f51b01bb9b 100644 --- a/crates/engine/src/web_cmds/tests.rs +++ b/crates/engine/src/web_cmds/tests.rs @@ -537,7 +537,10 @@ fn image_assets_are_generated_now_and_on_save() { let s2 = session(8); let doc = s2.active().unwrap().doc.clone(); let mut d = (*doc).clone(); - d.layers.push(Layer::new("default 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }))); + d.layers.push(Layer::new( + "default 200% @2x", + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), + )); let lid = d.layers[1].id; d.layer_mut(lid).unwrap().name = "icon.png".into(); let (files, errors) = generate_assets(&d, &dir); @@ -566,7 +569,7 @@ fn image_assets_reject_traversal_from_names_and_defaults() { d.layer_mut(id).unwrap().name = "safe.png".into(); d.layers.push(Layer::new( "default ../ + /outside/ + ..\\bad/ + C:\\drive/ + 50% nested/", - LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }), + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), )); let (files, errors) = generate_assets(&d, &dir); assert_eq!( diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 95d45fafb9..fd531ef502 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -125,9 +125,12 @@ fn video_m(v: &photocraft_doc::VideoData, sink: &mut dyn Sink) -> crate::manifes fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { let content = match &l.content { LayerContent::Raster(s) => ContentM::Raster { surface: surface_m(s, sink) }, - LayerContent::Group(g) => { - ContentM::Group { children: g.children.iter().map(|c| layer_m(c, sink)).collect(), expanded: g.expanded, artboard: g.artboard.clone() } - } + LayerContent::Group(g) => ContentM::Group { + children: g.children.iter().map(|c| layer_m(c, sink)).collect(), + expanded: g.expanded, + artboard: g.artboard.clone(), + frame_stroke: g.frame_stroke.clone(), + }, LayerContent::Adjustment(a) => ContentM::Adjustment { adjustment: a.clone() }, LayerContent::Fill(f) => ContentM::Fill { fill: f.clone() }, LayerContent::Text(t) => ContentM::Text { @@ -446,7 +449,9 @@ impl Loader<'_> { fn layer_with(&mut self, m: &LayerM, children: Vec) -> Result { let content = match &m.content { ContentM::Raster { surface } => LayerContent::Raster(self.surface(surface)?), - ContentM::Group { expanded, artboard, .. } => LayerContent::Group(Group { artboard: artboard.clone(), children, expanded: *expanded }), + ContentM::Group { expanded, artboard, frame_stroke, .. } => { + LayerContent::Group(Group { artboard: artboard.clone(), children, expanded: *expanded, frame_stroke: frame_stroke.clone() }) + } ContentM::Adjustment { adjustment } => LayerContent::Adjustment(adjustment.clone()), ContentM::Fill { fill } => LayerContent::Fill(fill.clone()), ContentM::Text { text, font_family, size_pt, color, transform, cache, psd_raw, runs, paragraphs, shape, orientation, antialias, warp } => { diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 82480e05c0..af818e7be2 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -256,6 +256,9 @@ pub enum ContentM { /// Artboard (Layer › New › Artboard). #[serde(default)] artboard: Option, + /// A Photoshop Frame's stroke, drawn along the group's vector mask. + #[serde(default, skip_serializing_if = "Option::is_none")] + frame_stroke: Option, }, Adjustment { adjustment: Adjustment, diff --git a/crates/format/tests/frame_stroke.rs b/crates/format/tests/frame_stroke.rs new file mode 100644 index 0000000000..89567ee7f0 --- /dev/null +++ b/crates/format/tests/frame_stroke.rs @@ -0,0 +1,37 @@ +//! A Photoshop Frame's stroke (`Group::frame_stroke`) survives a `.pcraft` round trip; older +//! manifests, written before it existed, load without one (#4381). + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Fill, Layer, LayerContent, ShapeStroke, Size, StrokeAlign}; +use photocraft_format::*; + +fn stroke_of(d: &Document) -> Option { + match &d.layers.first()?.content { + LayerContent::Group(g) => g.frame_stroke.clone(), + _ => None, + } +} + +#[test] +fn frame_stroke_roundtrips_and_defaults_when_absent() { + let mut doc = Document::new("a", Size::new(40, 30), ColorMode::Rgb, SampleType::U8); + let stroke = + ShapeStroke { width: 8.0, align: StrokeAlign::Inside, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), dashes: vec![2.0, 1.0], ..ShapeStroke::default() }; + let mut g = Layer::group("Frame 1", vec![]); + if let LayerContent::Group(gr) = &mut g.content { + gr.frame_stroke = Some(stroke.clone()); + } + doc.layers.push(g); + let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(stroke_of(&load_from_bytes(&bytes).unwrap()), Some(stroke)); + + // A manifest without the key (older files) loads with no stroke. + let m = read_manifest(&bytes).unwrap(); + let mut v = serde_json::to_value(&m.document).unwrap(); + let content = &mut v["layers"][0]["content"]; + assert!(content.get("frame_stroke").is_some()); + content.as_object_mut().unwrap().remove("frame_stroke"); + let old: photocraft_format::manifest::DocM = serde_json::from_value(v).unwrap(); + let photocraft_format::manifest::ContentM::Group { frame_stroke, .. } = &old.layers[0].content else { panic!("not a group") }; + assert!(frame_stroke.is_none()); +} diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 58ce6e4299..2a444540ba 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -672,6 +672,15 @@ impl<'a> Planner<'a> { p.mask = self.mask_use(layer); after = self.emit(p); } + // A Frame's stroke over the frame's content, at the group's opacity (compose). + if let Some(stroke) = photocraft_compose::shape_split::frame_stroke(layer, self.cx.canvas, self.cx.depth) { + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(after); + p.b = Some(stroke); + p.opacity = opacity; + after = self.emit(p); + } if visible_clipped.is_empty() { self.release(before); return Ok(after); @@ -837,12 +846,20 @@ impl<'a> Planner<'a> { match &layer.content { LayerContent::Group(g) => { let empty = self.clear(); - let s = self.stack(&g.children, empty)?; + let mut s = self.stack(&g.children, empty)?; if layer.mask.is_some() || layer.vector_mask.is_some() { let mut p = Pass::new(Kernel::Mask, 0); p.a = Some(s); p.mask = self.mask_use(layer); - return Ok(self.emit(p)); + s = self.emit(p); + } + // A Frame's stroke over its masked content (compose::render_content). + if let Some(stroke) = photocraft_compose::shape_split::frame_stroke(layer, self.cx.canvas, self.cx.depth) { + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(s); + p.b = Some(stroke); + s = self.emit(p); } Ok(s) } diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs index 84d3d0e937..63c3480dc1 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/parity.rs @@ -2170,6 +2170,36 @@ fn stroked_shapes_with_clipped_layers() { } } +/// A Photoshop Frame's stroke (#4381): along the group's vector mask, above its masked content, +/// for an empty frame and one holding a layer, pass-through and isolated. +#[test] +fn frame_strokes() { + let Some(mut g) = gpu() else { return }; + use photocraft_doc::vector::{Path, ShapeStroke, StrokeAlign, Subpath, VectorMask}; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (blend, align, content) in [ + (BlendMode::PassThrough, StrokeAlign::Inside, false), + (BlendMode::PassThrough, StrokeAlign::Outside, true), + (BlendMode::Multiply, StrokeAlign::Center, true), + ] { + let mut d = Document::new("t", Size::new(80, 64), ColorMode::Rgb, depth); + d.layers.push(noise_layer("bg", d.pixel_format(), Rect::from_xywh(0, 0, 80, 64), 1, 0.3)); + let kids = if content { vec![noise_layer("c", d.pixel_format(), Rect::from_xywh(0, 0, 80, 64), 7, 0.4)] } else { vec![] }; + let mut l = Layer::group("Frame 1", kids); + l.blend = blend; + l.opacity = 0.8; + l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(10.3, 8.6), (66.2, 12.1), (58.7, 54.4), (16.9, 48.2)])]))); + if let LayerContent::Group(gr) = &mut l.content { + gr.frame_stroke = Some(ShapeStroke { width: 5.0, align, paint: Fill::Solid(Color::rgb(0.9, 0.1, 0.1)), ..Default::default() }); + } + d.layers.push(l); + let st = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, &d, d.bounds()); + assert!(st.is_ok(), "planned on the GPU"); + check(&mut g, &d, &format!("{depth:?} frame stroke {blend:?} {align:?} content {content}")); + } + } +} + #[test] fn artboards() { let Some(mut g) = gpu() else { return }; diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index efba868be0..31c03abec3 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -131,7 +131,7 @@ impl Builder { let r = self.bbox(to_doc, page); let mut g = Layer::new( format!("Page {}", i + 1), - LayerContent::Group(Group { children: std::mem::take(&mut children), expanded: true, artboard: None }), + LayerContent::Group(Group { children: std::mem::take(&mut children), expanded: true, artboard: None, frame_stroke: None }), ); if let LayerContent::Group(gr) = &mut g.content { gr.artboard = Some(Artboard { rect: r, background: ArtboardBackground::White, preset: String::new() }); @@ -226,7 +226,7 @@ impl Builder { fn group(&mut self, n: &af::Node, children: Vec) -> Layer { // Pass-through and Normal (isolated) groups map one to one. - self.base(n, LayerContent::Group(Group { children, expanded: false, artboard: None })) + self.base(n, LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None })) } /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas. diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4fb952ba25..4bf9326086 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -658,7 +658,23 @@ impl Ex { let masked = l.vector_mask.is_some(); raw.retain(|(k, _)| !(RASTER_STALE_KEYS.contains(&k) || adjust_map::ADJUSTMENT_KEYS.contains(&k) || k == b"CgEd" || (k == b"vstk" && masked))); } - LayerContent::Group(_) => {} + // A Frame's stroke (`vstk`), kept byte-identical while it still decodes to the model. + LayerContent::Group(g) => { + let pos = raw.iter().position(|(k, _)| k == b"vstk"); + let old = pos.and_then(|i| raw.get(i)).and_then(|(_, d)| crate::vector_map::parse_vstk(d, self.dpi)); + // One we can't decode stays as it was unless the model has a stroke to write. + let stale = match &old { + Some(v) => v.stroke != g.frame_stroke, + None => g.frame_stroke.is_some(), + }; + if stale { + let data = crate::vector_map::vstk_bytes(g.frame_stroke.as_ref(), old.is_none_or(|v| v.fill_enabled), self.dpi); + match pos.and_then(|i| raw.get_mut(i)) { + Some(e) => e.1 = data, + None => raw.push((*b"vstk", data)), + } + } + } } // Effects reference point: written from the field (in place, keeping block order). match l.effects.reference { diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 94c4ea9932..59d915721a 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -521,7 +521,9 @@ impl Ctx<'_> { let sd = rec.section_divider(); let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder); let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data)); - let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard })); + // A Photoshop Frame's stroke: `vstk` on the frame group, in a shape's layout. + let frame_stroke = rec.block(b"vstk").and_then(|b| crate::vector_map::parse_vstk(&b.data, self.dpi)).and_then(|v| v.stroke); + let mut l = Layer::new(rec.name(), LayerContent::Group(Group { children, expanded, artboard, frame_stroke })); l.psd_blocks = preserved_blocks(rec); self.apply_common(&mut l, rec, sd.and_then(|s| s.blend_mode)); self.apply_vector_mask(&mut l, rec); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 04fc4bee3a..8f5b94e7fa 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -391,7 +391,7 @@ impl Conv { } return; } - let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None })); + let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None })); l.opacity = g.opacity().get(); l.blend = blend(g.blend_mode()); l.vector_mask = clip; @@ -416,7 +416,7 @@ impl Conv { } else { t.id().to_string() }; - out.push(Layer::new(name, LayerContent::Group(Group { children, expanded: false, artboard: None }))); + out.push(Layer::new(name, LayerContent::Group(Group { children, expanded: false, artboard: None, frame_stroke: None }))); } } } diff --git a/crates/io/tests/psd_frame_stroke.rs b/crates/io/tests/psd_frame_stroke.rs new file mode 100644 index 0000000000..3ae2284543 --- /dev/null +++ b/crates/io/tests/psd_frame_stroke.rs @@ -0,0 +1,117 @@ +//! A Photoshop Frame (Frame tool, K) is a layer group whose record carries the frame outline as a +//! vector mask (`vsms`) and its Properties › Stroke as a shape-style `vstk`. The stroke draws +//! along the outline even when nothing is placed in the frame (#4381). + +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Fill, Group, Layer, LayerContent, Path, ShapeStroke, Size, StrokeAlign, Subpath, VectorMask}; +use photocraft_io::vector_map::{parse_vstk, vstk_bytes}; +use photocraft_io::*; +use photocraft_psd::{PsdFile, SectionType, TaggedBlock}; + +fn red_inside(width: f32) -> ShapeStroke { + ShapeStroke { width, align: StrokeAlign::Inside, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..ShapeStroke::default() } +} + +/// An 80 × 60 white document with an empty rectangular frame over (20, 10)–(60, 50). +fn frame_doc(depth: SampleType, stroke: Option) -> Document { + let mut d = Document::with_background("f", Size::new(80, 60), ColorMode::Rgb, depth, Color::WHITE); + let mut g = Layer::group("Frame 1", vec![]); + if let LayerContent::Group(Group { frame_stroke, .. }) = &mut g.content { + *frame_stroke = stroke; + } + g.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(&[(20.0, 10.0), (60.0, 10.0), (60.0, 50.0), (20.0, 50.0)])]))); + d.layers.push(g); + d +} + +fn frame_stroke(d: &Document) -> Option { + d.layers.iter().find_map(|l| match &l.content { + LayerContent::Group(g) => Some(g.frame_stroke.clone()), + _ => None, + })? +} + +fn px(d: &Document, x: i32, y: i32) -> [f32; 4] { + photocraft_compose::flatten_to_surface(d, PixelFormat::RGBA8.with_sample(SampleType::F32), None).rgba(x, y) +} + +/// The group's own record (its top, `lsct` 1 or 2) in a PSD file. +fn frame_record(f: &mut PsdFile) -> &mut photocraft_psd::LayerRecord { + f.layers_mut() + .iter_mut() + .find(|r| r.section_divider().is_some_and(|s| matches!(s.kind, SectionType::OpenFolder | SectionType::ClosedFolder))) + .expect("the frame's group record") +} + +#[test] +fn a_photoshop_frames_vstk_draws_its_stroke_along_the_outline() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // A file shaped like Photoshop's: the group record carries `vsms` and a `vstk`. + let mut f = document_to_psd(&frame_doc(depth, None)); + frame_record(&mut f).blocks.push(TaggedBlock::new(*b"vstk", vstk_bytes(Some(&red_inside(4.0)), true, 72.0))); + let (d, _) = psd_to_document(&f); + assert_eq!(frame_stroke(&d), Some(red_inside(4.0)), "{depth:?}"); + // Inside the outline, 4 px wide: red on the frame's edge band, white in the middle and + // outside it. + let close = |a: [f32; 4], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 0.02); + for (x, y) in [(21, 30), (58, 30), (40, 11), (40, 48)] { + assert!(close(px(&d, x, y), [1.0, 0.0, 0.0]), "{depth:?} ({x}, {y}): {:?}", px(&d, x, y)); + } + for (x, y) in [(40, 30), (18, 30), (62, 30), (40, 8)] { + assert!(close(px(&d, x, y), [1.0, 1.0, 1.0]), "{depth:?} ({x}, {y}): {:?}", px(&d, x, y)); + } + } +} + +#[test] +fn a_frame_stroke_round_trips_through_psd() { + let stroke = ShapeStroke { dashes: vec![2.0, 1.0], opacity: 0.5, align: StrokeAlign::Outside, ..red_inside(3.0) }; + let d = frame_doc(SampleType::U8, Some(stroke.clone())); + let bytes = export(&d, "f.psd", &ExportOptions::default()).unwrap().bytes; + let back = import("f.psd", &bytes).unwrap().document; + assert_eq!(frame_stroke(&back), Some(stroke.clone())); + // Outside the outline at half opacity: pink just outside the edge. + let p = px(&back, 18, 30); + assert!((p[1] - 0.5).abs() < 0.05 && p[0] > 0.98, "{p:?}"); + + // Saved again unchanged, the imported `vstk` stays byte for byte. + let mut f = PsdFile::from_bytes(&bytes).unwrap(); + let first = frame_record(&mut f).block(b"vstk").unwrap().data.clone(); + let again = export(&back, "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f2 = PsdFile::from_bytes(&again).unwrap(); + assert_eq!(frame_record(&mut f2).block(b"vstk").unwrap().data, first); + + // Removing the stroke writes it disabled; no stroke at all writes no `vstk`. + let mut cleared = back.clone(); + if let Some(LayerContent::Group(g)) = cleared.layers.iter_mut().map(|l| &mut l.content).find(|c| matches!(c, LayerContent::Group(_))) { + g.frame_stroke = None; + } + let out = export(&cleared, "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f3 = PsdFile::from_bytes(&out).unwrap(); + assert_eq!(parse_vstk(&frame_record(&mut f3).block(b"vstk").unwrap().data, 72.0).unwrap().stroke, None); + let plain = export(&frame_doc(SampleType::U8, None), "f.psd", &ExportOptions::default()).unwrap().bytes; + let mut f4 = PsdFile::from_bytes(&plain).unwrap(); + assert!(frame_record(&mut f4).block(b"vstk").is_none()); +} + +#[test] +fn a_frame_stroke_without_a_vector_mask_or_width_draws_nothing() { + let mut d = frame_doc(SampleType::U8, Some(red_inside(4.0))); + d.layers[1].vector_mask = None; + assert_eq!(px(&d, 21, 30), [1.0, 1.0, 1.0, 1.0]); + let d = frame_doc(SampleType::U8, Some(ShapeStroke { width: 0.0, ..red_inside(4.0) })); + assert_eq!(px(&d, 21, 30), [1.0, 1.0, 1.0, 1.0]); + // Hostile widths from a file render without panicking. + for width in [f32::NAN, f32::INFINITY, -5.0, 1e9] { + let _ = px(&frame_doc(SampleType::U8, Some(ShapeStroke { width, ..red_inside(4.0) })), 21, 30); + } +} + +#[test] +fn an_isolated_frame_draws_its_outside_stroke_past_the_outline() { + let mut d = frame_doc(SampleType::U8, Some(ShapeStroke { align: StrokeAlign::Outside, ..red_inside(3.0) })); + d.layers[1].blend = photocraft_color::BlendMode::Normal; + let p = px(&d, 18, 30); + assert!(p[0] > 0.98 && p[1] < 0.02, "{p:?}"); + assert!(px(&d, 22, 30)[1] > 0.98, "inside stays white"); +} From ad273614f8b1c3d3a700ae57beedc16b1b00d10d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 15 Oct 2026 14:02:57 +0200 Subject: [PATCH 13/73] History Options: keep unrecorded visibility, roll back exactly in non-linear history - With Make Layer Visibility Changes Undoable off, Undo, Redo, a History row and non-linear Delete keep every layer's visibility as the user left it. - History::rollback takes the last record back exactly (also the later states it moved in non-linear history); Transform Again on a copy, New Frame from Layers, the Free Transform take-back and an abandoned Alt-drag copy use it via Session::rollback. The Alt-drag fold keeps the moved later states. - Non-linear Delete reaches a later (dimmed) state; the History panel lets those rows be dragged onto the trash. - Reword the snapshot-option comments: they come with #3634. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/edit_cmds.rs | 30 ++++- crates/engine/src/frame_cmds.rs | 5 +- crates/engine/src/history_cmds.rs | 22 ++-- crates/engine/src/history_options_cmds.rs | 97 +++++++++++++-- crates/engine/src/history_select_cmds.rs | 5 + crates/engine/src/lib.rs | 59 +++++++++ crates/engine/src/prefs.rs | 2 +- crates/ops/src/lib.rs | 140 ++++++++++++++++++++++ crates/ui-egui/src/move_mods.rs | 23 +++- crates/ui-egui/src/panels.rs | 6 +- crates/ui-egui/src/transform_tool.rs | 13 +- docs/scorecard.md | 4 +- 12 files changed, 371 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index dcb89aa980..d82d24f4e9 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -732,11 +732,8 @@ fn transform_again_copy(s: &mut Session) -> Result { Err(e) => { // The copy (e.g. of a layer whose position is locked) couldn't be transformed: take // it back, leaving nothing to redo and no Duplicate step to record. - s.undo(); + s.rollback(); s.journal.truncate(journal); - if let Some(st) = s.active_mut() { - st.history.clear_redo(); - } Err(e) } } @@ -1988,6 +1985,31 @@ mod tests { assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); } + /// History Options › Allow Non-Linear History: the Duplicate step of a refused Transform + /// Again on a copy moved the later states in front of it; taking it back must restore the + /// document before the command and the History list as it was, not land on a later state. + #[test] + fn a_refused_transform_again_on_a_copy_rolls_back_exactly_in_non_linear_history() { + let mut s = session(); + s.execute("history.options", json!({"allowNonLinearHistory": true})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "opacity": 0.5})).unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "opacity": 0.25})).unwrap(); + s.undo(); + s.undo(); + let st = s.active().unwrap(); + let (doc, entries) = (st.doc.clone(), st.history.entries()); + let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); + assert_eq!(redo.len(), 2); + assert!(s.execute("edit.transform.againCopy", json!({})).unwrap_err().to_string().contains("locked")); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the document before the command"); + assert_eq!(st.history.entries(), entries); + assert_eq!(st.history.redo_labels().map(str::to_string).collect::>(), redo); + } + #[test] fn toggle_last_state_and_transform_again() { let mut s = session(); diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/frame_cmds.rs index 7a401594fd..5650d8286b 100644 --- a/crates/engine/src/frame_cmds.rs +++ b/crates/engine/src/frame_cmds.rs @@ -54,11 +54,8 @@ fn frame_from_layers(s: &mut Session, p: &Value) -> Result { Err(e) => { // The group couldn't be framed: take the grouping back, leaving nothing to redo and // no grouping step to record. - s.undo(); + s.rollback(); s.journal.truncate(journal); - if let Some(st) = s.active_mut() { - st.history.clear_redo(); - } Err(e) } } diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index a72544dcd1..9e9362a626 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -39,29 +39,37 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { /// The `state` param as an index into the active document's history entries, defaulting to the /// current state. fn state_index(s: &Session, cmd: &str, p: &Value) -> Result<(usize, usize)> { + state_index_upto(s, cmd, p, false) +} + +/// [`state_index`], also accepting the later (dimmed, redo) states with `later`. +fn state_index_upto(s: &Session, cmd: &str, p: &Value, later: bool) -> Result<(usize, usize)> { let st = s.active().ok_or(EngineError::NoDocument)?; let current = st.history.past_len(); + let last = if later { current.saturating_add(st.history.redo_labels().count()) } else { current }; let i = match p.get("state") { None | Some(Value::Null) => current, Some(_) => { let v = int(p, "state").ok_or_else(|| bad(cmd, "`state` must be a number"))?; - usize::try_from(v).ok().filter(|i| *i <= current).ok_or_else(|| bad(cmd, format!("`state` = {v} is not a state (0..={current})")))? + usize::try_from(v).ok().filter(|i| *i <= last).ok_or_else(|| bad(cmd, format!("`state` = {v} is not a state (0..={last})")))? } }; Ok((i, current)) } /// History panel › Delete: drop the state and every state after it, as Photoshop does in linear -/// history (in non-linear history only that state, `history_options_cmds::delete_state`). The document returns to the state before it, and the deleted steps can't be redone. -/// The oldest state (the document as opened) can't be deleted. +/// history (in non-linear history only that state, also a later one: +/// `history_options_cmds::delete_state`). The document returns to the state before it, and the +/// deleted steps can't be redone. The oldest state (the document as opened) can't be deleted. fn delete_state(s: &mut Session, p: &Value) -> Result { const CMD: &str = "history.deleteState"; - let (i, current) = state_index(s, CMD, p)?; + // History Options › Allow Non-Linear History: only that state goes, a later (dimmed) one too. + let non_linear = s.active().is_some_and(|st| st.history.non_linear); + let (i, current) = state_index_upto(s, CMD, p, non_linear)?; if i == 0 { return Err(bad(CMD, "the oldest state can't be deleted")); } - // History Options › Allow Non-Linear History: only that state goes. - if s.active().is_some_and(|st| st.history.non_linear) { + if non_linear { crate::history_options_cmds::delete_state(s, i, current)?; let entries = s.active().ok_or(EngineError::NoDocument)?.history.entries(); return Ok(json!({ "states": entries.len(), "current": entries.last() })); @@ -245,7 +253,7 @@ pub fn specs() -> Vec { label: "Delete State", menu: &[], shortcut: None, - params: r##"{"state":index?} (History entry, 0 = oldest; default the current state) → {states,current}: removes the state and every later one"##, + params: r##"{"state":index?} (History entry, 0 = oldest; default the current state) → {states,current}: removes the state and every later one (with Allow Non-Linear History only that state, a later dimmed one too)"##, enabled: can_delete, run: delete_state, journal: true, diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index 88cec69f6e..bdd6e75eac 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -4,8 +4,8 @@ //! reports them; the GUI opens its dialog instead and runs it with the dialog's values on OK. //! //! Photoshop's three snapshot options (Automatically Create First Snapshot, Automatically -//! Create New Snapshot When Saving, Show New Snapshot Dialog by Default) are not here: snapshots -//! are not implemented, and a checkbox that does nothing is worse than a missing one. +//! Create New Snapshot When Saving, Show New Snapshot Dialog by Default) come with #3634, which +//! makes the snapshots act on them. use serde_json::{Map, Value}; @@ -58,9 +58,10 @@ fn options(s: &mut Session, p: &Value) -> Result { Ok(current(s)) } -/// History panel › Delete in non-linear history: delete state `i` (indexed like -/// [`photocraft_ops::History::entries`], `current` = the current state's index) and nothing -/// else. Deleting the current state steps back to the one before it; the later states stay. +/// History panel › Delete in non-linear history: delete state `i` (numbered as the History panel +/// lists them, `current` = the current state's index, the later dimmed states after it) and +/// nothing else. Deleting the current state steps back to the one before it; the later states +/// stay. pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result<()> { if i == 0 { return Err(EngineError::BadParams { cmd: "history.deleteState".into(), msg: "the oldest state can't be deleted".into() }); @@ -69,10 +70,15 @@ pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result< if s.active_job().is_some() { return Err(EngineError::Other("the history can't step back right now".into())); } + let keep_visibility = !s.visibility_undoable(); let st = s.active_mut().ok_or(EngineError::NoDocument)?; st.coalesce = None; - if i < current { - if !st.history.remove(i) { + if i != current { + let removed = match i.checked_sub(current.saturating_add(1)) { + Some(j) => st.history.remove_later(j), + None => st.history.remove(i), + }; + if !removed { return Err(EngineError::Other(format!("state {i} is not held"))); } // The document is unchanged, but the History panel's rows are not. @@ -85,6 +91,9 @@ pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result< if d.name != st.doc.name { std::sync::Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } + if keep_visibility { + crate::carry_visibility(&st.doc, &mut d); + } let damage = crate::layer_multi_cmds::step_damage(&d, &st.doc); st.doc = d; crate::restore_target(st, layers); @@ -206,6 +215,49 @@ mod tests { assert!(s.active().unwrap().history.can_redo()); } + fn visible(s: &Session, id: u64) -> bool { + s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().visible + } + + fn red(s: &Session, id: u64) -> bool { + let st = s.active().unwrap(); + st.doc.layer(photocraft_doc::LayerId(id)).unwrap().surface().unwrap().pixel(1, 1)[0] > 0.5 + } + + /// Off, showing or hiding a layer is not a state, so stepping through history (Undo, Redo, a + /// History row) leaves the visibility as the user set it, as Photoshop does; history states + /// hold whole documents and would otherwise bring the old visibility back. + #[test] + fn stepping_through_history_keeps_unrecorded_visibility() { + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert!(s.execute("edit.undo", json!({})).unwrap().as_bool().unwrap()); + assert!(!red(&s, id), "the fill is undone"); + assert!(!visible(&s, id), "the layer stays hidden"); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert!(red(&s, id) && visible(&s, id), "redo brings the fill back, not the hidden layer"); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + // History rows: New, New Layer, Fill. + s.execute("history.selectState", json!({"state": 1})).unwrap(); + assert!(!red(&s, id) && !visible(&s, id)); + s.execute("history.selectState", json!({"state": 2})).unwrap(); + assert!(red(&s, id) && !visible(&s, id)); + + // On (the default): Undo takes the hide back first, then the fill. + let (mut s, id) = doc(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(red(&s, id) && visible(&s, id)); + s.execute("edit.undo", json!({})).unwrap(); + assert!(!red(&s, id) && visible(&s, id)); + s.execute("history.selectState", json!({"state": 3})).unwrap(); + assert!(red(&s, id) && !visible(&s, id), "the hide is a state of its own"); + } + #[test] fn non_linear_history_keeps_later_states_and_delete_removes_only_one() { let mut s = Session::new(); @@ -248,4 +300,35 @@ mod tests { s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); assert!(s.active().unwrap().history.non_linear); } + + /// Non-linear Delete reaches a later (dimmed) state too, and deletes only it; linear history + /// still refuses one past the current state. + #[test] + fn non_linear_delete_removes_a_later_state() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + for c in ["#ff0000", "#00ff00", "#0000ff"] { + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.execute("history.deleteState", json!({"state": 2})).is_err(), "linear: not a deletable state"); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let mut expected = entries(&s); + let mut redo: Vec = s.active().unwrap().history.redo_labels().map(str::to_string).collect(); + // Entries: New, Fill (current), then the dimmed Fill 2 (state 2) and Fill 3 (state 3). + s.execute("history.deleteState", json!({"state": 2})).unwrap(); + redo.remove(0); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the document is unchanged"); + assert_eq!(st.history.redo_labels().map(str::to_string).collect::>(), redo); + assert_eq!(entries(&s), expected); + assert!(s.execute("history.deleteState", json!({"state": 4})).is_err(), "past the last state"); + s.execute("edit.redo", json!({})).unwrap(); + expected.push(redo[0].clone()); + assert_eq!(entries(&s), expected); + let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); + assert!(px[2] > 0.5 && px[1] < 0.5, "redo reaches the blue fill: {px:?}"); + } } diff --git a/crates/engine/src/history_select_cmds.rs b/crates/engine/src/history_select_cmds.rs index e05a859a5a..2b4adc21d7 100644 --- a/crates/engine/src/history_select_cmds.rs +++ b/crates/engine/src/history_select_cmds.rs @@ -32,6 +32,7 @@ fn select_state(s: &mut Session, p: &Value) -> Result { if s.active_job().is_some() { return Err(EngineError::Other("the history can't move while a command is still running on this document".into())); } + let keep_visibility = !s.visibility_undoable(); let st = s.active_mut().ok_or(EngineError::NoDocument)?; if target == past { return Ok(json!({ "state": target, "changed": false })); @@ -57,6 +58,10 @@ fn select_state(s: &mut Session, p: &Value) -> Result { if doc.name != start.name { std::sync::Arc::make_mut(&mut doc).name.clone_from(&start.name); } + // Visibility changes that are not history states stay as they are (History Options). + if keep_visibility { + crate::carry_visibility(&start, &mut doc); + } let damage = crate::layer_multi_cmds::step_damage(&start, &doc); st.doc = doc; crate::restore_target(st, layers); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b0ebf2defe..db083f5821 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -865,6 +865,7 @@ impl Session { if self.active_job().is_some() { return false; } + let keep_visibility = !self.visibility_undoable(); let Some(st) = self.active_mut() else { return false }; st.coalesce = None; match st.history.undo(st.doc.clone()) { @@ -873,6 +874,9 @@ impl Session { if d.name != st.doc.name { Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } + if keep_visibility { + carry_visibility(&st.doc, &mut d); + } // Pixels this step can have touched, so the canvas recomposites only that // (it recomposited everything before). let damage = layer_multi_cmds::step_damage(&d, &st.doc); @@ -890,6 +894,7 @@ impl Session { if self.active_job().is_some() { return false; } + let keep_visibility = !self.visibility_undoable(); let Some(st) = self.active_mut() else { return false }; st.coalesce = None; match st.history.redo(st.doc.clone()) { @@ -897,6 +902,9 @@ impl Session { if d.name != st.doc.name { Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } + if keep_visibility { + carry_visibility(&st.doc, &mut d); + } let damage = layer_multi_cmds::step_damage(&st.doc, &d); st.doc = d; restore_target(st, layers); @@ -909,6 +917,57 @@ impl Session { } } +impl Session { + /// Take back the step a compound command just recorded, after its later part failed: the + /// document before the command is current again, nothing is left to redo, and in non-linear + /// history the later states that step moved stay where they were (an undo would land on the + /// last of them). Falls back to Undo plus forgetting the redo states when the history + /// changed since that step. Returns whether a step was taken back. + pub fn rollback(&mut self) -> bool { + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + let Some((mut d, layers)) = st.history.rollback() else { + let undone = self.undo(); + if undone && let Some(st) = self.active_mut() { + st.history.clear_redo(); + } + return undone; + }; + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = layer_multi_cmds::step_damage(&d, &st.doc); + st.doc = d; + restore_target(st, layers); + st.revision += 1; + st.last_damage = damage; + true + } +} + +/// History Options › Make Layer Visibility Changes Undoable off: showing or hiding a layer is not +/// a history state, so stepping through history must not bring the old visibility back either +/// (history states hold whole documents). Gives every layer of `to` that `from` also has the +/// visibility it has in `from`; layers only one of them has keep theirs. Copies `to` only when +/// something differs. +pub(crate) fn carry_visibility(from: &Document, to: &mut Arc) { + let visible: std::collections::HashMap = from.walk().into_iter().map(|(_, _, l)| (l.id, l.visible)).collect(); + let changes: Vec<(LayerId, bool)> = + to.walk().into_iter().filter_map(|(_, _, l)| visible.get(&l.id).filter(|v| **v != l.visible).map(|v| (l.id, *v))).collect(); + if changes.is_empty() { + return; + } + let d = Arc::make_mut(to); + for (id, v) in changes { + if let Some(l) = d.layer_mut(id) { + l.visible = v; + } + } +} + /// Undo / redo: target the layers the restored state targeted, as far as they still exist. fn restore_target(st: &mut DocState, layers: LayerTarget) { // Deselect Layers is a valid history target, not a missing layer to replace with the top diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 498827cead..4e382f877a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -878,7 +878,7 @@ impl Default for Integrations { } /// The History panel's History Options… (not part of Edit › Preferences in Photoshop either). -/// Photoshop's snapshot options are not here yet: snapshots are not implemented. +/// Photoshop's snapshot options come with #3634. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct HistoryOptions { diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index bba6973f12..c4da888e5a 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -54,6 +54,11 @@ pub struct History { /// (after stepping back) keeps them and goes to the end of the list, instead of discarding /// them; see [`History::record`] and [`History::remove`]. pub non_linear: bool, + /// How many former redo states the most recent [`History::record`] moved onto the undo side + /// (always 0 in linear history), while that record is still the latest change to the list; + /// `None` once anything else changed it. [`History::rollback`] needs it to take the step back + /// exactly. + last_moved: Option, } impl Default for History { @@ -73,6 +78,7 @@ impl History { current_label: "Open".into(), current_layers: LayerTarget::default(), non_linear: false, + last_moved: None, } } @@ -93,15 +99,18 @@ impl History { let prev_label = std::mem::replace(&mut self.current_label, label.into()); let prev_layers = std::mem::replace(&mut self.current_layers, layers); self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers }); + let mut moved = 0; if self.non_linear { // `redo` holds the next state last; the list order is oldest first. Their tiles stay // counted: they only move from the redo side to the undo side. while let Some(state) = self.redo.pop() { self.undo.push_back(state); + moved += 1; } } else { self.clear_redo(); } + self.last_moved = Some(moved); while self.undo.len() > self.max_states { if let Some(state) = self.undo.pop_front() && let Some(tiles) = &mut self.tiles @@ -138,6 +147,7 @@ impl History { /// targeted when it was created. pub fn undo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { let prev = self.undo.pop_back()?; + self.last_moved = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&prev.doc); tiles.add(¤t); @@ -151,6 +161,7 @@ impl History { /// Redo: the mirror of [`Self::undo`]. pub fn redo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { let next = self.redo.pop()?; + self.last_moved = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&next.doc); tiles.add(¤t); @@ -186,6 +197,7 @@ impl History { /// last step can no longer be undone and its pixels are released. pub fn purge_last(&mut self) -> bool { self.clear_redo(); + self.last_moved = None; let Some(state) = self.undo.pop_back() else { return false }; if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); @@ -203,6 +215,20 @@ impl History { return false; } let Some(state) = self.undo.remove(i) else { return false }; + self.last_moved = None; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&state.doc); + } + true + } + + /// Delete the later (redo) state `j` (0 = the next redo, as [`History::redo_labels`] lists + /// them) and nothing else: the History panel's Delete on a dimmed state in non-linear + /// history. Returns whether a state was removed. + pub fn remove_later(&mut self, j: usize) -> bool { + let Some(k) = self.redo.len().checked_sub(j.saturating_add(1)) else { return false }; + let state = self.redo.remove(k); + self.last_moved = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } @@ -214,6 +240,7 @@ impl History { /// list) stay. Returns the document to make current and the layers it targeted. pub fn drop_current(&mut self) -> Option<(Arc, LayerTarget)> { let prev = self.undo.pop_back()?; + self.last_moved = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&prev.doc); } @@ -222,8 +249,46 @@ impl History { Some((prev.doc, prev.layers)) } + /// Take back the most recent [`History::record`] exactly, for a compound command whose later + /// part failed: the document it replaced becomes current again, the current document is + /// dropped (nothing to redo), and in non-linear history the states that record moved from + /// the redo side go back there, so the list reads as before the command. Returns `None` + /// (changing nothing) when something else changed the list since that record, e.g. an undo; + /// the caller then falls back to [`History::undo`]. + pub fn rollback(&mut self) -> Option<(Arc, LayerTarget)> { + let moved = self.last_moved?; + if self.undo.len() <= moved { + // The state it replaced went with the state limit. + return None; + } + self.last_moved = None; + for _ in 0..moved { + // Tiles stay counted: they only move back to the redo side. + let state = self.undo.pop_back()?; + self.redo.push(state); + } + let prev = self.undo.pop_back()?; + if let Some(tiles) = &mut self.tiles { + tiles.remove(&prev.doc); + } + self.current_label = prev.label; + self.current_layers = prev.layers.clone(); + Some((prev.doc, prev.layers)) + } + + /// The document the most recent [`History::record`] replaced, while [`History::rollback`] + /// can still take that record back. + pub fn recorded_before(&self) -> Option> { + let moved = self.last_moved?; + let i = self.undo.len().checked_sub(moved.checked_add(1)?)?; + self.undo.get(i).map(|s| s.doc.clone()) + } + /// Forget the redo states, e.g. after undoing half of a compound step that failed. pub fn clear_redo(&mut self) { + if !self.redo.is_empty() { + self.last_moved = None; + } if let Some(tiles) = &mut self.tiles { for state in &self.redo { tiles.remove(&state.doc); @@ -233,6 +298,7 @@ impl History { } pub fn clear(&mut self) { + self.last_moved = None; self.undo.clear(); self.redo.clear(); self.tiles = None; @@ -528,6 +594,80 @@ mod tests { assert_counter(&h, &cur); } + #[test] + fn remove_later_deletes_one_redo_state() { + let mut h = History::new(50); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for (i, n) in ["A", "B", "C"].into_iter().enumerate() { + edit(&mut h, &mut cur, n, |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + assert!(!h.remove_later(2) && !h.remove_later(usize::MAX)); + assert!(h.remove_later(0), "B"); + assert_eq!(h.redo_labels().collect::>(), ["C"]); + assert_counter(&h, &cur); + let (c, _) = h.redo(cur).unwrap(); + assert_eq!(h.entries(), ["Open", "A", "C"]); + assert_counter(&h, &c); + } + + #[test] + fn rollback_takes_the_last_record_back_exactly_in_both_modes() { + // Non-linear, with redo states: the moved states go back to the redo side and the + // document the step replaced (A) is current again, not the last former redo state (C). + let (mut h, mut cur) = stepped_back(true); + let a = cur.clone(); + let entries = h.entries(); + let redo: Vec = h.redo_labels().map(str::to_string).collect(); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.recorded_before().map(|d| d.name.clone()).as_deref(), Some("a")); + let (d, _) = h.rollback().unwrap(); + assert!(Arc::ptr_eq(&d, &a)); + assert_eq!(h.entries(), entries); + assert_eq!(h.redo_labels().map(str::to_string).collect::>(), redo); + assert!(h.rollback().is_none(), "only once"); + // Redoing still walks the kept states. + let (b, _) = h.redo(d).unwrap(); + assert_eq!(b.name, "b"); + // Linear: the same as an undo whose redo state is dropped. + let (mut h, mut cur) = stepped_back(false); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.rollback().unwrap().0.name, "a"); + assert_eq!(h.entries(), ["Open", "A"]); + assert!(!h.can_redo()); + // Anything else since the record: no rollback (the caller undoes instead). + let (mut h, mut cur) = stepped_back(true); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + cur = h.undo(cur).unwrap().0; + assert!(h.recorded_before().is_none() && h.rollback().is_none()); + h.redo(cur).unwrap(); + assert!(h.rollback().is_none()); + // The tile counter follows. + let mut h = History::new(50); + h.non_linear = true; + h.max_bytes = usize::MAX; + let mut cur = Arc::new(base()); + for i in 0..3 { + edit(&mut h, &mut cur, "Paint", |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "Paint", |d| { + d.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[1.0, 0.0, 0.0, 1.0]); + }); + cur = h.rollback().unwrap().0; + assert_counter(&h, &cur); + } + #[test] fn max_states_bound() { let mut h = History::new(3); diff --git a/crates/ui-egui/src/move_mods.rs b/crates/ui-egui/src/move_mods.rs index 64b3a65603..609b40fd3d 100644 --- a/crates/ui-egui/src/move_mods.rs +++ b/crates/ui-egui/src/move_mods.rs @@ -90,7 +90,9 @@ fn duplicate(app: &mut PhotocraftApp) -> Option { let before = past_len(app)?; // In place: the copy follows the pointer from the original, artboards too (#1531). match app.run("layer.duplicate", json!({"inPlace": true})) { - Ok(_) => Some(before), + // The state just before the copy's: in non-linear history the copy's step also moved + // the later states in front of it (`History::record`), and those must stay. + Ok(_) => Some(past_len(app).and_then(|n| n.checked_sub(1)).unwrap_or(before).max(before)), Err(e) => { app.ui.status = e; None @@ -164,7 +166,8 @@ pub fn finish(app: &mut PhotocraftApp) { /// ⌥-drag's copy is taken back. pub fn abandon(app: &mut PhotocraftApp) { if std::mem::take(&mut app.move_mods).dup_from.is_some() { - app.session.undo(); + // Exactly, also in non-linear history (where an undo would land on a later state). + app.session.rollback(); } } @@ -398,6 +401,22 @@ mod tests { assert_eq!(bounds(&app, st.active_layer.unwrap()), photocraft_geom::Rect::new(22, 8, 38, 24)); } + /// Allow Non-Linear History: the copy's step moves the later states in front of it, and + /// folding the copy and the move into one step must keep them. + #[test] + fn alt_drag_keeps_the_later_states_in_non_linear_history() { + let mut app = app_with_layer(); + app.session.execute("history.options", json!({"allowNonLinearHistory": true})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.setProps", json!({"layer": id.0, "opacity": 0.5})).unwrap(); + assert!(app.session.undo()); + let mut expected = app.session.active().unwrap().history.entries(); + expected.extend(app.session.active().unwrap().history.redo_labels().map(str::to_string)); + expected.push(DUPLICATE_MOVE_LABEL.into()); + drag(&mut app, &[[16.0, 16.0], [20.0, 16.0], [26.0, 21.0]], egui::Modifiers::ALT); + assert_eq!(app.session.active().unwrap().history.entries(), expected, "the later state stays"); + } + #[test] fn alt_drag_duplicates_every_selected_layer() { let mut app = app_with_layer(); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 522c74dc15..8d3716bdc6 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3091,6 +3091,7 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let entries = st.history.entries(); let current = entries.len() - 1; let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); + let non_linear = st.history.non_linear; let selected_snap = selected_snapshot(ui.ctx(), st); let ctx = ui.ctx().clone(); // A row dragged onto the trash (#5324); a drag that never saw its release must not outlive it. @@ -3125,8 +3126,9 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { for (i, (e, is_redo)) in all.enumerate() { // The current state shows selected unless a snapshot is (Photoshop highlights one row). let selected = i == current && selected_snap.is_none(); - // Past states can be dragged onto the trash; the oldest one can't be deleted. - let sense = if is_redo || i == 0 { Sense::click() } else { Sense::click_and_drag() }; + // Past states can be dragged onto the trash; the oldest one can't be deleted. With + // Allow Non-Linear History a later (dimmed) state can be deleted too. + let sense = if (is_redo && !non_linear) || i == 0 { Sense::click() } else { Sense::click_and_drag() }; let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), sense); resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &e)); if resp.drag_started() { diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index d46ef189bc..4bd88dd8a4 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -393,17 +393,18 @@ fn take_back_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId) { let Some(index) = app.session.documents().iter().position(|st| { st.doc.id == document && st.doc.layer(layer).is_some() - && st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).is_some_and(|before| before.layer(layer).is_none()) + && st + .history + .recorded_before() + .or_else(|| st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i))) + .is_some_and(|before| before.layer(layer).is_none()) }) else { return; }; let active = app.session.active_index(); app.session.set_active(index); - if app.session.undo() - && let Some(st) = app.session.active_mut() - { - st.history.clear_redo(); - } + // Exactly, also in non-linear history (where an undo would land on a later state). + app.session.rollback(); if let Some(active) = active { app.session.set_active(active); } diff --git a/docs/scorecard.md b/docs/scorecard.md index 1e0576ba02..52bb6adf59 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 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 166 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 168 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present | @@ -177,7 +177,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 166** (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: 26 of 168** (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`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 873a7a2d1982077e4e1dc371b26d1e7743f06d18 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 16 Oct 2026 00:45:31 +0200 Subject: [PATCH 14/73] Paths: making a selection from a path deselects the path (#6079) With the Pen or Path Selection tool, Ctrl/Cmd+Enter and the canvas menu's Make Selection... now deselect the loaded path in the Paths panel, as in Photoshop, and the canvas stops drawing (and editing) that Work Path until a path is selected again or the Work Path changes (a new Pen path, Make Work Path, path.set...). The path stays in the document. A shape layer's path or vector mask stays the active path; the Paths panel's own Load path as selection button is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/canvas_tool_menu.rs | 8 +++ crates/ui-egui/src/dialogs.rs | 7 ++ crates/ui-egui/src/direct_select.rs | 2 +- crates/ui-egui/src/path_selection_tests.rs | 3 + crates/ui-egui/src/state.rs | 6 ++ crates/ui-egui/src/vector_ui.rs | 78 +++++++++++++++++++++- 6 files changed, 101 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs index da835a786f..f18f5d43a7 100644 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas_tool_menu.rs @@ -783,6 +783,10 @@ fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) { } else { fields.insert("name".into(), json!(name)); } + if command == "path.toSelection" { + // OK deselects and hides the path, as ⌘↩ does (#6079). + fields.insert("__deselectPath".into(), json!(true)); + } if command == "path.fill" { let fg = app.session.tools.foreground; let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; @@ -1471,6 +1475,10 @@ mod tests { crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); assert!(h.state().session.active().unwrap().doc.selection.is_some()); assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); + // Like ⌘↩, it deselects and hides the work path, which stays in the document (#6079). + assert_eq!(h.state().ui.selected_path, None); + assert!(h.state().session.active().unwrap().doc.work_path.is_some()); + assert!(!crate::vector_ui::work_path_shown(h.state())); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 013c79e825..0a1d7f3f69 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -646,6 +646,13 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { Some(p) if result.is_ok() && running => p.committing = true, _ => app.filter_preview = None, } + if result.is_ok() + && cmd == "path.toSelection" + && d.fields.contains_key("__deselectPath") + && let Some(name) = params.get("name").and_then(Value::as_str) + { + crate::vector_ui::deselect_loaded_path(app, name); + } if result.is_ok() && cmd == "view.newGuideLayout" { app.ui.view.guide_layout = params; } diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index b27d9ea466..b4047c2055 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -167,7 +167,7 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool { /// the work path. The Pen's Auto Add/Delete edits these (`anchor_tools::pen_auto`). pub(crate) fn active_paths(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app)); - let work = app.session.active().and_then(|st| st.doc.work_path.clone()); + let work = app.session.active().and_then(|st| st.doc.work_path.clone()).filter(|_| crate::vector_ui::work_path_shown(app)); layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect() } diff --git a/crates/ui-egui/src/path_selection_tests.rs b/crates/ui-egui/src/path_selection_tests.rs index b4aaa9e503..a42dac39f8 100644 --- a/crates/ui-egui/src/path_selection_tests.rs +++ b/crates/ui-egui/src/path_selection_tests.rs @@ -74,6 +74,9 @@ fn cmd_enter_while_drawing_finishes_the_path_and_loads_it() { assert!(app.ui.pen.is_none(), "the pen path was finished"); assert!(app.session.active().unwrap().doc.work_path.is_some(), "into the work path"); assert!(app.session.active().unwrap().doc.selection.is_some(), "and loaded as a selection: {}", app.ui.status); + // Then deselected and no longer drawn, as in Photoshop; the work path stays (#6079). + assert_eq!(app.ui.selected_path, None); + assert!(!crate::vector_ui::work_path_shown(app)); // Plain ↩ still only finishes a path. let mut h = harness(); h.state_mut().ui.tool = Tool::Pen; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5cbda434e7..59c0358210 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1161,6 +1161,11 @@ pub struct UiState { /// Selected row in the Paths panel ("work" or a saved path name). #[serde(default)] pub selected_path: Option, + /// The document and Work Path deselected by making a selection from it with the Pen or Path + /// Selection tool (#6079): the canvas hides that path until a path is selected again or the + /// Work Path changes. + #[serde(default)] + pub hidden_work_path: Option<(u64, photocraft_doc::Path)>, /// Layers panel kind filter ("pixel", "adjustment", "type", "shape", "smart"); empty = all. #[serde(default)] pub layer_filter: Vec, @@ -1350,6 +1355,7 @@ impl Default for UiState { direct_selection: Default::default(), corner_radius: None, selected_path: None, + hidden_work_path: None, panels: Panels::default(), views: Vec::new(), dialogs: Vec::new(), diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 8b5e914af2..f17593c58a 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -705,7 +705,34 @@ pub fn path_to_selection(app: &mut PhotocraftApp, params: Value) -> Result bool { + if app.ui.selected_path.is_some() { + return true; + } + let Some((doc, hidden)) = &app.ui.hidden_work_path else { return true }; + app.session.active().is_none_or(|st| st.doc.id.0 != *doc || st.doc.work_path.as_ref() != Some(hidden)) } // --------------------------------------------------------------------------------------------- @@ -760,6 +787,9 @@ fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { if let Some((id, p)) = active_shape_path(app) { return Some((PathTarget::Shape(id), p)); } + if !work_path_shown(app) { + return None; + } app.session.active()?.doc.work_path.clone().map(|p| (PathTarget::Work, p)) } @@ -1003,7 +1033,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } else if paths { // Paths remain visible as outlines with any tool. Path Selection adds anchor squares; Direct // Selection has its own overlay above. - if let Some(wp) = &doc.work_path { + if let Some(wp) = doc.work_path.as_ref().filter(|_| work_path_shown(app)) { draw_path(wp, tool == Tool::PathSelection); } let st = app.session.active(); @@ -2072,6 +2102,50 @@ mod tests { assert!(overlay_shapes(&app, &ctx) > 0, "the pen path in progress is still drawn"); } + #[test] + fn making_a_selection_from_the_pen_path_deselects_and_hides_it() { + // #6079: after ⌘↩ the work path's outline stayed on the canvas; Photoshop deselects it. + let ctx = egui::Context::default(); + let mut app = app(); + app.ui.tool = Tool::Pen; + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], ..Default::default() }); + path_to_selection(&mut app, json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.doc.selection.is_some(), "the selection is made"); + assert!(st.doc.work_path.is_some(), "the work path is kept"); + assert_eq!(app.ui.selected_path, None, "and deselected in the Paths panel"); + assert_eq!(overlay_shapes(&app, &ctx), 0, "so the canvas no longer draws it"); + assert!(target_path(&app).is_none() && !delete_key_deletes_work_path(&app), "nor edits or deletes it"); + // Undo removes the selection; the path stays. + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert!(app.session.active().unwrap().doc.selection.is_none()); + assert_eq!(overlay_shapes(&app, &ctx), 0, "still hidden"); + // Another Work Path made any other way (Make Work Path, `path.set` over the control + // channel…) is a different path: it shows without being selected. + let other = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [5, 5]}, {"anchor": [50, 5]}, {"anchor": [50, 50]}]}]}); + app.run("path.set", json!({"name": "work", "path": other})).unwrap(); + assert_eq!(app.ui.selected_path, None); + assert!(work_path_shown(&app) && overlay_shapes(&app, &ctx) > 0, "a changed Work Path is shown"); + // Selecting it in the Paths panel shows it again. + app.ui.selected_path = Some("work".into()); + assert!(overlay_shapes(&app, &ctx) > 0); + // A new path drawn after the deselect replaces the work path and is shown. + path_to_selection(&mut app, json!({})).unwrap(); + assert_eq!(overlay_shapes(&app, &ctx), 0); + app.ui.pen = Some(PenPath { knots: vec![[[10.0, 10.0]; 3], [[40.0, 10.0]; 3]], ..Default::default() }); + pen_commit(&mut app, false); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); + assert_eq!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths.len(), 1, "replaced, not combined"); + assert!(overlay_shapes(&app, &ctx) > 0); + // A shape layer's path stays the active path: layer targeting is unchanged. + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[120.0, 20.0]; 3], [[120.0, 80.0]; 3]], ..Default::default() }); + path_to_selection(&mut app, json!({})).unwrap(); + assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); + assert!(active_shape_path(&app).is_some()); + } + #[test] fn shape_drag_creates_layers_with_modifiers() { let mut app = app(); From 750a91c8b2a852be2b37e89194d700e80d565cfd Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 16 Oct 2026 20:59:24 +0200 Subject: [PATCH 15/73] Color Lookup: PSD save keeps a .3dl/.look LUT file as loaded (#6544) A Color Lookup layer embeds its LUT file in the PSD (LUT3DFileData, LUTFormat, LUT3DFileName). Photoshop stores the file as loaded and tags its format; it never converts it. PhotoCraft kept only the parsed table, so every save re-encoded it as .cube with LUTFormatCUBE while keeping the original name: a layer loaded from "Film.3dl" was saved as .cube data under a .3dl name. The layer now keeps the file it was loaded from (its format and bytes, `ColorLookup::source`), set when a PSD is read and when the colorLookup command loads `data`/`file`, and cleared when a built-in look or "none" replaces the table. A PSD save writes those bytes and format back unchanged, but only while they still parse to the layer's table, so the stored file can never go stale. Otherwise (a table made in PhotoCraft, or one that no longer matches) it falls back to .cube as before and swaps a .3dl/.look extension in the name for .cube. The new field is `#[serde(default)]` and skipped when empty, so older .pcraft files load unchanged. lutfile gains Format::detect/parse_as so the recorded format is exactly the one the parser used. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/cms/src/lutfile.rs | 59 ++++++- crates/compose/src/adjust.rs | 9 +- crates/doc/src/adjust.rs | 23 +++ crates/engine/src/adjust_cmds.rs | 34 ++-- crates/engine/src/adjust_cmds/tests.rs | 49 +++++- crates/format/tests/roundtrip.rs | 19 +++ crates/gpu/src/plan.rs | 9 +- crates/gpu/tests/parity.rs | 2 +- crates/io/src/adjust_map.rs | 186 +++++++++++++++++++--- crates/io/tests/adjust_blend_roundtrip.rs | 18 ++- crates/io/tests/adjust_warnings.rs | 3 +- crates/ui-egui/src/adjust_ui.rs | 2 +- 12 files changed, 369 insertions(+), 44 deletions(-) diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 0a68ef8bce..22dcca4dc0 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -87,16 +87,50 @@ impl LutFile { } } +/// A LUT file format. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Cube, + ThreeDl, + Look, +} + +impl Format { + /// The format [`parse`] reads `bytes` as: from `file_name`'s extension, else sniffed + /// (XML is `.look`, anything else `.cube`). + pub fn detect(file_name: &str, bytes: &[u8]) -> Self { + let lower = file_name.to_ascii_lowercase(); + if lower.ends_with(".3dl") { + Format::ThreeDl + } else if lower.ends_with(".look") || String::from_utf8_lossy(bytes).trim_start().starts_with('<') { + Format::Look + } else { + Format::Cube + } + } + + /// The file extension, without the dot. + pub fn extension(self) -> &'static str { + match self { + Format::Cube => "cube", + Format::ThreeDl => "3dl", + Format::Look => "look", + } + } +} + /// Parses a LUT, picking the format from `file_name`'s extension (falls back to sniffing). pub fn parse(file_name: &str, bytes: &[u8]) -> Result { - let lower = file_name.to_ascii_lowercase(); + parse_as(Format::detect(file_name, bytes), bytes) +} + +/// Parses a LUT in a known format. +pub fn parse_as(format: Format, bytes: &[u8]) -> Result { let text = String::from_utf8_lossy(bytes); - if lower.ends_with(".3dl") { - parse_3dl(&text) - } else if lower.ends_with(".look") || text.trim_start().starts_with('<') { - parse_look(&text) - } else { - parse_cube(&text) + match format { + Format::Cube => parse_cube(&text), + Format::ThreeDl => parse_3dl(&text), + Format::Look => parse_look(&text), } } @@ -425,6 +459,17 @@ DOMAIN_MAX 0.5 1 1 assert!(parse_look(&text).is_err()); } + #[test] + fn format_detection_matches_parse() { + assert_eq!(Format::detect("a.3DL", b""), Format::ThreeDl); + assert_eq!(Format::detect("a.Look", b""), Format::Look); + assert_eq!(Format::detect("a.cube", b" "), Format::Look, "XML is sniffed as .look"); + assert_eq!(Format::detect("a.txt", b"LUT_3D_SIZE 2"), Format::Cube); + assert_eq!(Format::ThreeDl.extension(), "3dl"); + let text = write_cube(&LutFile::identity(2)); + assert_eq!(parse_as(Format::Cube, text.as_bytes()), parse("a.cube", text.as_bytes())); + } + #[test] fn malformed_rejected() { assert!(parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err()); diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index f91e7779d1..71de02af43 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -1590,7 +1590,14 @@ mod tone_tests { // A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past // the table-length guard and indexed out of bounds. for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let a = Adjustment::ColorLookup { + name: "x".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size, + tetrahedral: false, + dither: false, + source: None, + }; let mut b = ramp(); apply(&a, &mut b); assert_eq!(b.px, ramp().px, "size {size}"); diff --git a/crates/doc/src/adjust.rs b/crates/doc/src/adjust.rs index 855cd1f399..98e61f72aa 100644 --- a/crates/doc/src/adjust.rs +++ b/crates/doc/src/adjust.rs @@ -17,6 +17,24 @@ pub fn is_identity_curve(points: &[CurvePoint]) -> bool { } } +/// A 3D LUT file format (Photoshop's `LUTFormat`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum LutFormat { + #[serde(rename = "cube")] + Cube, + #[serde(rename = "3dl")] + ThreeDl, + #[serde(rename = "look")] + Look, +} + +/// A Color Lookup's LUT file as loaded: its format and bytes. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LutSource { + pub format: LutFormat, + pub bytes: Arc>, +} + /// Entries in a pencil-drawn Curves map (one per 8-bit level, as in PSD `curv` maps). pub const CURVE_MAP_LEN: usize = 256; @@ -260,6 +278,11 @@ pub enum Adjustment { /// Ordered dither of ±½ an 8-bit step to hide banding (Photoshop's "Dither"). #[serde(default)] dither: bool, + /// The LUT file `lut` was read from, embedded unchanged on PSD save as Photoshop does. + /// None for a table made in PhotoCraft (a built-in look); a save also ignores it when + /// it no longer parses to `lut`. + #[serde(default, skip_serializing_if = "Option::is_none")] + source: Option, }, Invert, Posterize { diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index c1393bb94c..a04bfb62a7 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -10,6 +10,7 @@ //! result through the selection like the other Image › Adjustments commands. use photocraft_algo::tone::{self, HdrToning, MatchColor, ShadowsHighlights}; +use photocraft_doc::adjust::{LutFormat, LutSource}; use photocraft_doc::{Adjustment, Document, Layer, LayerContent, Rect}; use photocraft_raster::{Surface, to_rgba}; use serde_json::{Value, json}; @@ -104,34 +105,38 @@ pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result) -> Result { const CMD: &str = "colorLookup"; - let (mut name, mut lut, mut size, mut tetrahedral, mut dither) = match base { - Some(Adjustment::ColorLookup { name, lut, size, tetrahedral, dither }) => (name.clone(), lut.clone(), *size, *tetrahedral, *dither), - _ => (String::new(), None, 0, false, false), + let (mut name, mut lut, mut size, mut tetrahedral, mut dither, mut source) = match base { + Some(Adjustment::ColorLookup { name, lut, size, tetrahedral, dither, source }) => { + (name.clone(), lut.clone(), *size, *tetrahedral, *dither, source.clone()) + } + _ => (String::new(), None, 0, false, false, None), }; - let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String)> = None; + // The parsed table, its label and (for a file) the file as loaded, which a PSD save embeds. + let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String, Option)> = None; if let Some(id) = opt_str(CMD, p, "lut")? { if id == "none" || id.is_empty() { name.clear(); lut = None; size = 0; + source = None; } else { let f = photocraft_cms::lutfile::builtin(id).ok_or_else(|| bad(CMD, format!("unknown look `{id}` (built-ins: {})", builtin_ids())))?; let label = f.title.clone(); - loaded = Some((f, label)); + loaded = Some((f, label, None)); } } let file_name = opt_str(CMD, p, "fileName")?; if let Some(text) = opt_str(CMD, p, "data")? { let file_name = file_name.unwrap_or("lut.cube"); let f = photocraft_cms::lutfile::parse(file_name, text.as_bytes()).map_err(|e| bad(CMD, e.0))?; - loaded = Some((f, base_name(file_name))); + loaded = Some((f, base_name(file_name), Some(lut_source(file_name, text.as_bytes().to_vec())))); } if let Some(path) = opt_str(CMD, p, "file")?.filter(|s| !s.is_empty()) { let bytes = read_file(path).ok_or_else(|| bad(CMD, format!("can't read {path}")))?; let f = photocraft_cms::lutfile::parse(path, &bytes).map_err(|e| bad(CMD, format!("{path}: {}", e.0)))?; - loaded = Some((f, base_name(path))); + loaded = Some((f, base_name(path), Some(lut_source(path, bytes)))); } - if let Some((f, label)) = loaded { + if let Some((f, label, src)) = loaded { if !f.domain_is_default() { return Err(bad( CMD, @@ -144,6 +149,7 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result {} @@ -157,7 +163,17 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result) -> LutSource { + let format = match photocraft_cms::lutfile::Format::detect(file_name, &bytes) { + photocraft_cms::lutfile::Format::Cube => LutFormat::Cube, + photocraft_cms::lutfile::Format::ThreeDl => LutFormat::ThreeDl, + photocraft_cms::lutfile::Format::Look => LutFormat::Look, + }; + LutSource { format, bytes: std::sync::Arc::new(bytes) } } fn builtin_ids() -> String { diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index d831fbf448..ca1fa99a63 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -170,7 +170,7 @@ fn color_lookup_builtin_data_and_errors() { // Switching interpolation keeps the table. s.execute("layer.setAdjustment", json!({"layer": id.0, "interpolation": "tetrahedral", "dither": true})).unwrap(); match &doc(&s).layer(id).unwrap().content { - LayerContent::Adjustment(Adjustment::ColorLookup { lut: Some(_), size: 33, tetrahedral: true, dither: true, name }) => { + LayerContent::Adjustment(Adjustment::ColorLookup { lut: Some(_), size: 33, tetrahedral: true, dither: true, name, .. }) => { assert_eq!(name, "Day for Night") } other => panic!("{other:?}"), @@ -220,6 +220,53 @@ LUT_3D_SIZE 2 } /// The kind's parameters, read back from the model (Color Lookup with its table name and size). +#[test] +fn color_lookup_file_round_trips_psd_in_its_own_format() { + use photocraft_doc::adjust::{LutFormat, LutSource}; + // #6544: a .3dl / .look file is kept as loaded and embedded unchanged in a PSD. + let mut threedl = String::from("0 1023\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + threedl.push_str(&format!("{} {} {}\n", (1 - r) * 4095, (1 - g) * 4095, (1 - b) * 4095)); + } + } + } + let hex: String = photocraft_cms::lutfile::LutFile::identity(2).data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect(); + let look = format!("2{hex}"); + for (text, file_name, format, psd_format) in + [(threedl.as_str(), "Invert.3dl", LutFormat::ThreeDl, "LUTFormat3DL"), (look.as_str(), "Grade.look", LutFormat::Look, "LUTFormatLOOK")] + { + let mut s = session(8, "rgb"); + let r = s.execute("layer.newAdjustmentLayer.colorLookup", json!({"data": text, "fileName": file_name})).unwrap(); + let id = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); + let want = LutSource { format, bytes: std::sync::Arc::new(text.as_bytes().to_vec()) }; + let source_of = |s: &Session| match adjustment_of(s, id) { + Adjustment::ColorLookup { source, .. } => source, + other => panic!("{other:?}"), + }; + assert_eq!(source_of(&s), Some(want.clone()), "{file_name}"); + // Settings that don't touch the table keep the file. + s.execute("layer.setAdjustment", json!({"layer": id.0, "interpolation": "tetrahedral", "dither": true})).unwrap(); + assert_eq!(source_of(&s), Some(want.clone()), "{file_name}"); + // Saved as PSD and reopened: same format tag, same bytes, same name. + let psd = photocraft_io::export(doc(&s), "psd", &photocraft_io::ExportOptions::default()).unwrap().bytes; + let back = photocraft_io::import("x.psd", &psd).unwrap().document; + let layer = back.walk().into_iter().map(|(_, _, l)| l).find(|l| matches!(l.content, LayerContent::Adjustment(Adjustment::ColorLookup { .. }))).unwrap(); + let LayerContent::Adjustment(Adjustment::ColorLookup { name, source, .. }) = &layer.content else { panic!("not a Color Lookup") }; + assert_eq!((name.as_str(), source.as_ref()), (file_name, Some(&want)), "{psd_format}"); + // Choosing a built-in look replaces the table, so the file goes too. + s.execute("layer.setAdjustment", json!({"layer": id.0, "lut": "dayForNight"})).unwrap(); + assert_eq!(source_of(&s), None); + } + // "none" drops it as well. + let mut s = session(8, "rgb"); + let r = s.execute("layer.newAdjustmentLayer.colorLookup", json!({"data": threedl, "fileName": "Invert.3dl"})).unwrap(); + let id = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); + s.execute("layer.setAdjustment", json!({"layer": id.0, "lut": "none"})).unwrap(); + assert!(matches!(adjustment_of(&s, id), Adjustment::ColorLookup { source: None, lut: None, .. })); +} + fn adjustment_of(s: &Session, id: photocraft_doc::LayerId) -> Adjustment { match &doc(s).layer(id).unwrap().content { LayerContent::Adjustment(a) => a.clone(), diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs index f78e93947e..3717678cb8 100644 --- a/crates/format/tests/roundtrip.rs +++ b/crates/format/tests/roundtrip.rs @@ -751,3 +751,22 @@ fn variables_follow_layer_id_remapping() { let gone = defs.iter().find(|d| d.name == "gone").unwrap().layer; assert!(back.walk().into_iter().all(|(_, _, l)| l.id != gone), "dangling target must not address a live layer"); } + +#[test] +fn color_lookup_lut_file_round_trips_and_old_files_load() { + use photocraft_doc::Adjustment; + use photocraft_doc::adjust::{LutFormat, LutSource}; + let lut = Some(std::sync::Arc::new(vec![0.5f32; 24])); + let source = Some(LutSource { format: LutFormat::ThreeDl, bytes: std::sync::Arc::new(b"0 1023\n0 0 0\n".to_vec()) }); + let adj = Adjustment::ColorLookup { name: "Film.3dl".into(), lut, size: 2, tetrahedral: false, dither: false, source }; + let mut doc = Document::new("d", photocraft_doc::Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + doc.insert_above(None, Layer::new("lookup", LayerContent::Adjustment(adj.clone()))); + let back = load_from_bytes(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap(); + assert_eq!(back, doc, "the LUT file survives a .pcraft round trip (#6544)"); + // A .pcraft written before the field existed has no `source`: it loads as None. + let mut v = serde_json::to_value(&adj).unwrap(); + let removed = v.as_object_mut().and_then(|o| o.values_mut().next()).and_then(|f| f.as_object_mut()).and_then(|f| f.remove("source")); + assert!(removed.is_some(), "{v}"); + let Adjustment::ColorLookup { source: None, name, .. } = serde_json::from_value(v).unwrap() else { panic!("old lookup must load") }; + assert_eq!(name, "Film.3dl"); +} diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 58ce6e4299..16e351b4e3 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -1903,7 +1903,14 @@ mod tests { #[test] fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() { for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let a = Adjustment::ColorLookup { + name: "x".into(), + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + size, + tetrahedral: false, + dither: false, + source: None, + }; let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8); assert_eq!((kind, rows.is_none()), (0, true), "size {size}"); } diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs index 84d3d0e937..d430147292 100644 --- a/crates/gpu/tests/parity.rs +++ b/crates/gpu/tests/parity.rs @@ -649,7 +649,7 @@ fn lookup(n: usize, tetrahedral: bool, dither: bool) -> Adjustment { } } } - Adjustment::ColorLookup { name: "test".into(), lut: Some(std::sync::Arc::new(t)), size: n as u32, tetrahedral, dither } + Adjustment::ColorLookup { name: "test".into(), lut: Some(std::sync::Arc::new(t)), size: n as u32, tetrahedral, dither, source: None } } #[test] diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index d4bc312690..00ec0f5597 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -11,7 +11,7 @@ //! stay [`Adjustment::Unsupported`] and are written back verbatim. use photocraft_doc::Adjustment; -use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map, curve_map_outputs}; +use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, LutFormat, LutSource, ToneSpace, curve_map, curve_map_outputs}; use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; /// All PSD adjustment keys recognized as adjustment layers. @@ -424,12 +424,12 @@ fn read_lookup(d: &[u8]) -> Result { Some(_) => return Err("its LUT data is empty".into()), None => return Err("it uses a colour profile (abstract or device link), not a LUT file, which isn't supported yet".into()), }; - let (ext, format) = match desc_enum(&desc, "LUTFormat") { - Some(b"LUTFormat3DL") => ("x.3dl", "3DL"), - Some(b"LUTFormatLOOK") => ("x.look", "LOOK"), - _ => ("x.cube", "CUBE"), + let format = match desc_enum(&desc, "LUTFormat") { + Some(b"LUTFormat3DL") => LutFormat::ThreeDl, + Some(b"LUTFormatLOOK") => LutFormat::Look, + _ => LutFormat::Cube, }; - let lut = photocraft_cms::lutfile::parse(ext, bytes).map_err(|e| format!("its {format} LUT can't be read ({e})"))?; + let lut = parse_lut_source(format, bytes).map_err(|e| format!("its {} LUT can't be read ({e})", psd_lut_format(format).trim_start_matches("LUTFormat")))?; let name = desc_text(&desc, "LUT3DFileName").or_else(|| desc_text(&desc, "NM ")).unwrap_or_default(); Ok(Adjustment::ColorLookup { name, @@ -437,9 +437,47 @@ fn read_lookup(d: &[u8]) -> Result { lut: Some(std::sync::Arc::new(lut.data)), tetrahedral: false, dither: desc_bool(&desc, "Dthr").unwrap_or(false), + // Kept so a save embeds the file as loaded (Photoshop never converts it). + source: Some(LutSource { format, bytes: std::sync::Arc::new(bytes.clone()) }), }) } +/// A LUT file's table, read the way a PSD read does (an XML file tagged `.cube` is sniffed as `.look`). +fn parse_lut_source(format: LutFormat, bytes: &[u8]) -> Result { + let format = match format { + LutFormat::Cube => photocraft_cms::lutfile::Format::Cube, + LutFormat::ThreeDl => photocraft_cms::lutfile::Format::ThreeDl, + LutFormat::Look => photocraft_cms::lutfile::Format::Look, + }; + photocraft_cms::lutfile::parse(&format!("x.{}", format.extension()), bytes) +} + +/// Photoshop's `LUTFormatType` value for a format. +fn psd_lut_format(format: LutFormat) -> &'static str { + match format { + LutFormat::Cube => "LUTFormatCUBE", + LutFormat::ThreeDl => "LUTFormat3DL", + LutFormat::Look => "LUTFormatLOOK", + } +} + +/// The source file of a Color Lookup to embed as is: only while it still parses to the +/// layer's table, so an edited table is never saved with stale bytes. +fn lut_source_for<'a>(source: Option<&'a LutSource>, table: &[f32], size: usize) -> Option<&'a LutSource> { + let source = source?; + let file = parse_lut_source(source.format, &source.bytes).ok()?; + (file.size == size && file.data == table).then_some(source) +} + +/// `name` with a `.3dl` / `.look` extension swapped for `.cube`, for a table saved as `.cube`. +fn cube_file_name(name: &str) -> String { + let lower = name.to_ascii_lowercase(); + match [".3dl", ".look"].iter().find(|ext| lower.ends_with(*ext)) { + Some(ext) => format!("{}.cube", name.get(..name.len() - ext.len()).unwrap_or(name)), + None => name.to_string(), + } +} + /// The descriptor of a `vibA` / `blwh` block: a 4-byte descriptor version (16), then the descriptor. fn versioned(d: &[u8]) -> Option { VersionedDescriptor::parse_prefix(d).ok().map(|(v, _)| v.descriptor) @@ -688,31 +726,40 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec)> { } return vec![(*b"selc", v)]; } - Adjustment::ColorLookup { name, lut, size, dither, .. } => { + Adjustment::ColorLookup { name, lut, size, dither, source, .. } => { // A lookup without a usable table (none chosen yet, or a bad size) renders as the // identity, so it is written as a 2³ identity cube rather than dropped. let n = *size as usize; let cube = lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)).and_then(|(table, len)| table.get(..len)).filter(|_| n <= 256); - let (file, dither) = match cube { - Some(cube) => ( - photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec(), domain_min: [0.0; 3], domain_max: [1.0; 3] }, - *dither, - ), - _ => (photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }, false), + // Like Photoshop, embed the LUT file as loaded, in its own format; a table made or + // changed in PhotoCraft is written as `.cube`, named to match. + let (format, data, name, dither) = match cube { + Some(cube) => match lut_source_for(source.as_ref(), cube, n) { + Some(src) => (src.format, src.bytes.to_vec(), name.clone(), *dither), + None => { + let file = + photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec(), domain_min: [0.0; 3], domain_max: [1.0; 3] }; + (LutFormat::Cube, photocraft_cms::lutfile::write_cube(&file).into_bytes(), cube_file_name(name), *dither) + } + }, + _ => { + let file = photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }; + (LutFormat::Cube, photocraft_cms::lutfile::write_cube(&file).into_bytes(), cube_file_name(name), false) + } }; let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; let text = |t: &str| Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(t)); let d = Descriptor::new("null") .with("lookupType", en("colorLookupType", "3DLUT")) - .with("NM ", text(name)) + .with("NM ", text(&name)) .with("Dthr", Value::Boolean(dither)) .with("profile", Value::RawData(Vec::new())) - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("LUTFormat", en("LUTFormatType", psd_lut_format(format))) .with("dataOrder", en("colorLookupOrder", "rgbOrder")) .with("tableOrder", en("colorLookupOrder", "bgrOrder")) - .with("LUT3DFileData", Value::RawData(photocraft_cms::lutfile::write_cube(&file).into_bytes())) - .with("LUT3DFileName", text(name)); + .with("LUT3DFileData", Value::RawData(data)) + .with("LUT3DFileName", text(&name)); put16(&mut v, 1); v.extend_from_slice(&VersionedDescriptor::new(d).to_bytes()); return vec![(*b"clrL", v)]; @@ -1007,7 +1054,9 @@ mod tests { rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }); rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true }); let id = photocraft_cms::lutfile::LutFile::identity(5); - rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true }); + let cube = photocraft_cms::lutfile::write_cube(&id).into_bytes(); + let source = Some(LutSource { format: LutFormat::Cube, bytes: std::sync::Arc::new(cube) }); + rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true, source }); } #[test] @@ -1034,6 +1083,105 @@ mod tests { assert_eq!(write(&a)[0].1, d); } + /// A 2³ Lustre `.3dl` (12-bit, blue fastest) that inverts every colour. + fn inverting_3dl() -> Vec { + let mut text = String::from("# made by hand\n0 1023\n"); + for r in 0..2 { + for g in 0..2 { + for b in 0..2 { + text.push_str(&format!("{} {} {}\n", (1 - r) * 4095, (1 - g) * 4095, (1 - b) * 4095)); + } + } + } + text.into_bytes() + } + + /// A 2³ SpeedGrade `.look` holding the identity. + fn identity_look() -> Vec { + let hex: String = photocraft_cms::lutfile::LutFile::identity(2).data.iter().flat_map(|v| v.to_le_bytes()).map(|b| format!("{b:02X}")).collect(); + format!("\n\"2\"\"{hex}\"\n").into_bytes() + } + + /// A `clrL` block as Photoshop writes one for a loaded LUT file. + fn clrl_block(format: &str, bytes: &[u8], name: &str) -> Vec { + let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let text = |t: &str| Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(t)); + let desc = Descriptor::new("null") + .with("lookupType", en("colorLookupType", "3DLUT")) + .with("NM ", text(name)) + .with("LUTFormat", en("LUTFormatType", format)) + .with("LUT3DFileData", Value::RawData(bytes.to_vec())) + .with("LUT3DFileName", text(name)); + let mut d = vec![0, 1]; + d.extend(VersionedDescriptor::new(desc).to_bytes()); + d + } + + /// The descriptor of the `clrL` block `a` is written as. + fn written_clrl(a: &Adjustment) -> Descriptor { + let b = write(a); + assert_eq!(&b[0].0, b"clrL"); + VersionedDescriptor::parse_prefix(&b[0].1[2..]).unwrap().0.descriptor + } + + fn raw<'a>(d: &'a Descriptor, key: &str) -> &'a [u8] { + let Some(Value::RawData(b)) = d.get(key) else { panic!("{key} missing") }; + b + } + + #[test] + fn color_lookup_keeps_a_3dl_or_look_file_as_loaded() { + // #6544: Photoshop embeds the LUT file as loaded and tags its format; it never converts it. + for (format, kind, bytes, name) in + [("LUTFormat3DL", LutFormat::ThreeDl, inverting_3dl(), "Invert.3DL"), ("LUTFormatLOOK", LutFormat::Look, identity_look(), "Grade.look")] + { + let a = parse(b"clrL", &clrl_block(format, &bytes, name), None, Channels::Rgb); + let Adjustment::ColorLookup { name: n, lut: Some(_), size: 2, source: Some(src), .. } = &a else { panic!("{a:?}") }; + assert_eq!((n.as_str(), src.format, src.bytes.as_slice()), (name, kind, bytes.as_slice())); + let d = written_clrl(&a); + assert_eq!(desc_enum(&d, "LUTFormat"), Some(format.as_bytes()), "{name}"); + assert_eq!(raw(&d, "LUT3DFileData"), bytes.as_slice(), "{name}: the file's bytes, unchanged"); + assert_eq!(desc_text(&d, "LUT3DFileName").as_deref(), Some(name)); + assert_eq!(desc_text(&d, "NM ").as_deref(), Some(name)); + // And it reads back as the same layer. + let b = write(&a); + assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Rgb), a); + } + } + + #[test] + fn color_lookup_table_without_matching_file_is_saved_as_cube_named_to_match() { + let a = parse(b"clrL", &clrl_block("LUTFormat3DL", &inverting_3dl(), "Invert.3DL"), None, Channels::Rgb); + let Adjustment::ColorLookup { name, size, tetrahedral, dither, source, .. } = a else { panic!("{a:?}") }; + // The table no longer matches the stored file (changed in PhotoCraft): the bytes are stale. + let id = photocraft_cms::lutfile::LutFile::identity(2).data; + let edited = Adjustment::ColorLookup { name, lut: Some(std::sync::Arc::new(id.clone())), size, tetrahedral, dither, source }; + let d = written_clrl(&edited); + assert_eq!(desc_enum(&d, "LUTFormat"), Some(&b"LUTFormatCUBE"[..])); + assert_eq!(desc_text(&d, "LUT3DFileName").as_deref(), Some("Invert.cube")); + assert_eq!(photocraft_cms::lutfile::parse("x.cube", raw(&d, "LUT3DFileData")).unwrap().data, id); + // A table made in PhotoCraft (no file) named like another format is also renamed. + let made = + Adjustment::ColorLookup { name: "Grade.look".into(), lut: Some(std::sync::Arc::new(id)), size: 2, tetrahedral: false, dither: false, source: None }; + let d = written_clrl(&made); + assert_eq!(desc_enum(&d, "LUTFormat"), Some(&b"LUTFormatCUBE"[..])); + assert_eq!(desc_text(&d, "LUT3DFileName").as_deref(), Some("Grade.cube")); + assert_eq!(desc_text(&d, "NM ").as_deref(), Some("Grade.cube")); + // An unreadable stored file falls back the same way instead of failing the save. + let junk = Adjustment::ColorLookup { + name: "Junk.3dl".into(), + lut: Some(std::sync::Arc::new(photocraft_cms::lutfile::LutFile::identity(2).data)), + size: 2, + tetrahedral: false, + dither: false, + source: Some(LutSource { format: LutFormat::ThreeDl, bytes: std::sync::Arc::new(b"\xFF not a lut".to_vec()) }), + }; + assert_eq!(desc_text(&written_clrl(&junk), "LUT3DFileName").as_deref(), Some("Junk.cube")); + assert_eq!(cube_file_name("a.b.3dl"), "a.b.cube"); + assert_eq!(cube_file_name("Day for Night"), "Day for Night"); + assert_eq!(cube_file_name("x.cube"), "x.cube"); + } + #[test] fn color_lookup_synthetic_block() { let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; @@ -1297,7 +1445,7 @@ mod tests { } // A colour lookup without a (usable) table becomes an identity cube, without dither. for lut in [None, Some(std::sync::Arc::new(vec![0.5; 7]))] { - let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true }); + let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true, source: None }); let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); let Adjustment::ColorLookup { lut: Some(t), size: 2, dither: false, name, .. } = back else { panic!("{back:?}") }; assert_eq!(name, "L"); diff --git a/crates/io/tests/adjust_blend_roundtrip.rs b/crates/io/tests/adjust_blend_roundtrip.rs index 4e8b727af2..97160c6f32 100644 --- a/crates/io/tests/adjust_blend_roundtrip.rs +++ b/crates/io/tests/adjust_blend_roundtrip.rs @@ -80,9 +80,20 @@ fn adjustments() -> Vec<(Adjustment, bool)> { (Adjustment::PhotoFilter { color: [q16(0), q16(39321), q16(65535)], density: 0.3, preserve_luminosity: false }, true), (Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }, true), (Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: true }, true), - (Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(Arc::new(lut.data)), size: 5, tetrahedral: false, dither: false }, true), + // The LUT file is embedded as loaded (here a .cube), so it reads back with its source. + ( + Adjustment::ColorLookup { + name: "Look.cube".into(), + source: Some(adjust::LutSource { format: adjust::LutFormat::Cube, bytes: Arc::new(photocraft_cms::lutfile::write_cube(&lut).into_bytes()) }), + lut: Some(Arc::new(lut.data)), + size: 5, + tetrahedral: false, + dither: false, + }, + true, + ), // No table chosen: written as an identity cube (renders the same, comes back with a table). - (Adjustment::ColorLookup { name: String::new(), lut: None, size: 0, tetrahedral: false, dither: false }, false), + (Adjustment::ColorLookup { name: String::new(), lut: None, size: 0, tetrahedral: false, dither: false, source: None }, false), (Adjustment::Invert, true), (Adjustment::Posterize { levels: 4 }, true), (Adjustment::Threshold { level: g(140) }, true), @@ -207,7 +218,8 @@ fn every_adjustment_kind_round_trips_16bit() { fn color_lookup_tetrahedral_warns_on_psd_save() { let lut = photocraft_cms::lutfile::LutFile::from_fn("t", 2, |c| if c == [1.0; 3] { [1.0; 3] } else { [0.0; 3] }); for tetrahedral in [true, false] { - let adj = Adjustment::ColorLookup { name: "test.cube".into(), lut: Some(Arc::new(lut.data.clone())), size: 2, tetrahedral, dither: false }; + let adj = + Adjustment::ColorLookup { name: "test.cube".into(), lut: Some(Arc::new(lut.data.clone())), size: 2, tetrahedral, dither: false, source: None }; let mut d = Document::new("lut", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8); let fmt = d.pixel_format(); d.layers.push(raster("Background", fmt, d.bounds(), 1, false)); diff --git a/crates/io/tests/adjust_warnings.rs b/crates/io/tests/adjust_warnings.rs index 9b91f40bcf..330f7ebb13 100644 --- a/crates/io/tests/adjust_warnings.rs +++ b/crates/io/tests/adjust_warnings.rs @@ -33,7 +33,8 @@ fn unreadable_adjustments_warn_on_open() { #[test] fn readable_adjustments_open_without_warnings() { let lut: Vec = (0..8).flat_map(|i| [(i & 1) as f32, ((i >> 1) & 1) as f32, ((i >> 2) & 1) as f32]).collect(); - let lookup = Adjustment::ColorLookup { name: "id.cube".into(), size: 2, lut: Some(std::sync::Arc::new(lut)), tetrahedral: false, dither: false }; + let lookup = + Adjustment::ColorLookup { name: "id.cube".into(), size: 2, lut: Some(std::sync::Arc::new(lut)), tetrahedral: false, dither: false, source: None }; for adj in [lookup, Adjustment::Invert] { let (doc, warnings) = reopen(adj, "x.psd", &ExportOptions::default()); assert!(!matches!(&doc.layers[0].content, LayerContent::Adjustment(Adjustment::Unsupported { .. }))); diff --git a/crates/ui-egui/src/adjust_ui.rs b/crates/ui-egui/src/adjust_ui.rs index b713e9104e..f4541599fb 100644 --- a/crates/ui-egui/src/adjust_ui.rs +++ b/crates/ui-egui/src/adjust_ui.rs @@ -92,7 +92,7 @@ fn browse_color_lookup(app: &mut PhotocraftApp, layer: LayerId) -> Result Date: Sat, 17 Oct 2026 18:45:33 +0200 Subject: [PATCH 16/73] Crop: X with a ratio preset turns the frame instead of shrinking it (#7057) With a ratio preset, X fitted the swapped ratio inside the unswapped frame, so every X shrank it. The frame now turns first and the ratio is then applied to it, so X twice brings the frame back. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/crop_ui.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index f1df63ff14..1736ac15f9 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -660,10 +660,11 @@ pub fn swap_orientation(app: &mut PhotocraftApp) -> bool { { app.ui.tool_options.crop_ratio = k; } + // The frame turns first: fitting the swapped ratio inside the old frame would shrink it. + keyed(app, swapped(r)); if preset_ratio(app).is_some() { apply_ratio(app); } else { - keyed(app, swapped(r)); crate::crop_mode::sync_frame(app); crate::crop_mode::auto_center(app); } @@ -1949,6 +1950,17 @@ mod tests { app.ui.tool_options.crop_ratio = String::new(); assert!(swap_orientation(&mut app)); assert_eq!(app.ui.tool_options.crop_ratio, "", "no ratio stays none"); + // With a ratio preset X turns the frame too, keeping its size, and X again brings it back. + let near = |a: Option<[f64; 4]>, b: [f64; 4]| a.is_some_and(|a| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)); + app.ui.tool_options.crop_ratio = "16:9".into(); + app.ui.crop_rect = Some([60.0, 27.5, 140.0, 72.5]); + key(&mut app, Key::X, NONE); + assert_eq!(app.ui.tool_options.crop_ratio, "9:16"); + assert!(near(app.ui.crop_rect, [77.5, 10.0, 122.5, 90.0]), "45 x 80, not shrunk: {:?}", app.ui.crop_rect); + key(&mut app, Key::X, NONE); + assert_eq!(app.ui.tool_options.crop_ratio, "16:9"); + assert!(near(app.ui.crop_rect, [60.0, 27.5, 140.0, 72.5]), "and back: {:?}", app.ui.crop_rect); + app.ui.tool_options.crop_ratio = String::new(); assert_eq!(swapped_ratio("1.414:1", 1.0, 1.0).as_deref(), Some("1:1.414"), "decimals survive the swap (#6487)"); assert_eq!(swapped_ratio("0:5", 1.0, 1.0), None); assert_eq!(swapped_ratio("nonsense", 1.0, 1.0), None); From b06a02a3fa781f245e972cf1dc568b3d5f9297ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 17 Oct 2026 09:48:40 -0700 Subject: [PATCH 17/73] Paste: a drawing copied as SVG markup pastes its pixels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit › Paste, Paste in Place, File › New from Clipboard and New Document's Clipboard preset read only images from the OS clipboard: copied image files, then the clipboard's image, then on Wayland the other image/* types. When the clipboard held a drawing as SVG markup in plain text, the paste found nothing and the status bar read "Nothing to paste: the clipboard holds no image". On macOS and Linux, VectorCraft's Copy leaves only that markup on the clipboard while Include SVG Code is on, which is its default, so art copied there did not paste. When the clipboard holds no copied image file and no image, the reader now reads its text. Text that photocraft_io::svg::is_svg accepts is rendered at one pixel per SVG unit, scaled down to fit the SVG import's limits (16,384 px a side and 24,000,000 px in all), and pastes as a copied image does, with its transparency. An image on the clipboard still comes first. Other text, markup that does not parse and markup longer than 128 MiB paste nothing, as before. The render runs inside the crash guard that file import uses. The new photocraft_io::svg::rasterize_rgba8 renders a drawing at its own size within those limits and shares its render code with rasterize. The read order moved into clipboard_image, which takes the three clipboard reads as closures. Tests cover the SVG text paste, the scaling, the text that pastes nothing and the read order. --- apps/photocraft/src/services.rs | 172 +++++++++++++++++++++++++++++--- crates/io/src/svg.rs | 65 +++++++++++- 2 files changed, 220 insertions(+), 17 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index d4e7a01553..794bf0d982 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -443,6 +443,40 @@ fn image_from_offers(offers: &[String], mut fetch: impl FnMut(&str) -> Option Option<(u32, u32, Vec)> { + if u64::try_from(text.len()).ok()? > MAX_CLIPBOARD_SVG_BYTES || !photocraft_io::svg::is_svg(text.as_bytes()) { + return None; + } + crate::crash_guard::guard("Paste", || photocraft_io::svg::rasterize_rgba8(text.as_bytes()).map_err(|e| e.to_string())).ok() +} + +/// What a paste reads from the OS clipboard, in this order: the first copied file that is an +/// image (Finder also puts the file's icon on the clipboard as an image, which would otherwise +/// paste instead of the file), the clipboard's image, then a drawing copied as SVG markup. Each +/// read runs only when the ones before it found nothing. +fn clipboard_image( + clipboard: &mut C, + files: impl FnOnce(&mut C) -> Option>, + image: impl FnOnce(&mut C) -> Option<(u32, u32, Vec)>, + text: impl FnOnce(&mut C) -> Option, +) -> Option<(u32, u32, Vec)> { + if let Some(img) = files(clipboard).and_then(|paths| image_from_files(&paths)) { + return Some(img); + } + if let Some(img) = image(clipboard) { + return Some(img); + } + text(clipboard).and_then(|text| image_from_svg_text(&text)) +} + /// The shell command that starts this install under XWayland, where winit delivers file drops /// (winit 0.30 has none on Wayland, #386). A Flatpak gets the X11 socket only without the Wayland /// one, an AppImage relaunches by its own path, and anything else is `photocraft` on the PATH. @@ -543,18 +577,20 @@ pub fn native(automation: Option) -> Some(c) => c, None => slot.insert(arboard::Clipboard::new().ok()?), }; - // Copied files first: Finder also puts the file's icon on the clipboard as an - // image, which would otherwise paste instead of the file. - if let Some(img) = cb.get().file_list().ok().and_then(|paths| image_from_files(&paths)) { - return Some(img); - } - if let Ok(img) = cb.get_image() { - return Some((img.width as u32, img.height as u32, img.bytes.into_owned())); - } - #[cfg(target_os = "linux")] - return wayland_clipboard_image(); - #[cfg(not(target_os = "linux"))] - None + clipboard_image( + cb, + |cb| cb.get().file_list().ok(), + |cb| { + if let Ok(img) = cb.get_image() { + return Some((img.width as u32, img.height as u32, img.bytes.into_owned())); + } + #[cfg(target_os = "linux")] + return wayland_clipboard_image(); + #[cfg(not(target_os = "linux"))] + None + }, + |cb| cb.get_text().ok(), + ) }) }), load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())), @@ -1165,4 +1201,116 @@ mod tests { assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); assert!(image_from_files(&[bin]).is_none()); } + + /// A 121 × 81 white rectangle with a 1-unit black stroke, written as markup the way a vector + /// app's Copy puts it on the clipboard as text. + const COPIED_RECTANGLE: &str = r##" + + + +"##; + + /// A 40 × 20 drawing whose left half is a red square; the right half has no art. + const HALF_RED: &str = r##""##; + + /// The clipboard as `clipboard_image` reads it when it holds only `text`. + fn from_text(text: &str) -> Option<(u32, u32, Vec)> { + clipboard_image(&mut (), |_| None, |_| None, |_| Some(text.to_string())) + } + + fn pixel(img: &(u32, u32, Vec), x: u32, y: u32) -> [u8; 4] { + let at = ((y * img.0 + x) * 4) as usize; + img.2[at..at + 4].try_into().unwrap() + } + + #[test] + fn svg_markup_copied_as_text_pastes_its_pixels() { + let img = from_text(COPIED_RECTANGLE).expect("the drawing's pixels"); + assert_eq!((img.0, img.1, img.2.len()), (121, 81, 121 * 81 * 4), "one pixel per SVG unit"); + assert_eq!(pixel(&img, 60, 40), [255, 255, 255, 255], "the white fill"); + for (x, y) in [(0, 40), (120, 40), (60, 0), (60, 80)] { + let [r, g, b, a] = pixel(&img, x, y); + assert!(a == 255 && r < 8 && g < 8 && b < 8, "the black stroke at {x},{y}: {:?}", [r, g, b, a]); + } + let img = from_text(HALF_RED).expect("the drawing's pixels"); + assert_eq!((img.0, img.1), (40, 20)); + assert_eq!(pixel(&img, 5, 10), [255, 0, 0, 255]); + assert_eq!(pixel(&img, 30, 10), [0, 0, 0, 0], "transparent where there is no art"); + } + + #[test] + fn text_that_is_not_a_drawing_pastes_nothing() { + for text in ["", "hello", "

not a drawing

", ""] { + assert!(from_text(text).is_none(), "{text:?}"); + } + // Markup that doesn't parse, and markup past the read limit, paste nothing either. + assert!(from_text("").is_none()); + let mut huge = String::from(""); + huge.push_str(&" ".repeat(usize::try_from(MAX_CLIPBOARD_SVG_BYTES).unwrap())); + huge.push_str(""); + assert!(from_text(&huge).is_none(), "markup past the limit isn't parsed"); + } + + #[test] + fn a_drawing_past_the_pixel_limit_pastes_scaled_down() { + let wide = r##""##; + let img = from_text(wide).expect("scaled down, not dropped"); + let pixels = u64::from(img.0) * u64::from(img.1); + assert!(pixels <= 24_000_000 && pixels > 12_000_000, "{} × {}", img.0, img.1); + assert!(img.0.abs_diff(img.1 * 2) <= 2, "the proportions are kept: {} × {}", img.0, img.1); + assert_eq!(pixel(&img, img.0 / 2, img.1 / 2), [0, 0, 255, 255]); + } + + /// Copied files and an image come before SVG text, which is read only when neither is there. + #[test] + fn copied_files_and_images_come_before_svg_text() { + let dir = temp("svg-order"); + let png = dir.join("red.png"); + std::fs::write(&png, red_png(3, 2)).unwrap(); + let blue = (2, 2, [0u8, 0, 255, 255].repeat(4)); + let mut text_read = false; + let svg_text = |read: &mut bool| { + *read = true; + Some(COPIED_RECTANGLE.to_string()) + }; + let got = clipboard_image(&mut text_read, |_| Some(vec![png.clone()]), |_| Some(blue.clone()), svg_text); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((3, 2)), "the copied file"); + let got = clipboard_image(&mut text_read, |_| None, |_| Some(blue.clone()), svg_text); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2)), "the image, not the SVG text"); + assert!(!text_read, "the text isn't read while there is a file or an image"); + // A copied file that isn't an image (an .svg) falls through to the image, then the text. + let svg = dir.join("drawing.svg"); + std::fs::write(&svg, COPIED_RECTANGLE).unwrap(); + let got = clipboard_image(&mut (), |_| Some(vec![svg.clone()]), |_| None, |_| Some(COPIED_RECTANGLE.to_string())); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((121, 81))); + } + + /// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the + /// drawing's art; other text is still a quiet "nothing to paste". + #[test] + fn paste_turns_svg_text_on_the_clipboard_into_a_layer() { + let text: Rc> = Rc::new(RefCell::new(HALF_RED.to_string())); + let clip = text.clone(); + let services = Services { + clipboard_get_image: Some(Box::new(move || clipboard_image(&mut (), |_| None, |_| None, |_| Some(clip.borrow().clone())))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap(); + assert_ne!(r["pasted"], json!(false), "{r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers + 1); + let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let bounds = surface.content_bounds(); + assert_eq!((bounds.width(), bounds.height()), (20, 20), "the red half; the transparent half adds nothing"); + *text.borrow_mut() = "just words".to_string(); + let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap(); + assert_eq!(r["pasted"], json!(false)); + assert_eq!(app.ui.status, "Nothing to paste: the clipboard holds no image"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); + } } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 72b2318675..c2a3694daf 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -244,14 +244,47 @@ fn import_parsed(name: &str, parsed: Parsed, max_group_depth: usize) -> Result Result { let tree = parse(bytes)?.tree; let cv = canvas(&tree, &mut Vec::new()); - let k = cv.scale * scale.clamp(1.0 / 64.0, 64.0); + let pixmap = render(&tree, cv.scale * scale.clamp(1.0 / 64.0, 64.0))?; + let rect = Rect::new(0, 0, pixmap.width() as i32, pixmap.height() as i32); + let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect(); + Ok(photocraft_compose::Buffer { rect, px }) +} + +/// The whole drawing at one pixel per SVG unit, scaled down to fit [`MAX_SIDE`] a side and +/// [`MAX_RASTER_PIXELS`] in all: its width, height and straight-alpha RGBA8 pixels. Paste uses it +/// for a drawing copied as SVG markup. +pub fn rasterize_rgba8(bytes: &[u8]) -> Result<(u32, u32, Vec), IoError> { + let tree = parse(bytes)?.tree; + let cv = canvas(&tree, &mut Vec::new()); + let (w, h) = (f64::from(tree.size().width() * cv.scale), f64::from(tree.size().height() * cv.scale)); + // The largest k ≤ 1 with (w·k + 2)(h·k + 2) ≤ the limit: `render` rounds each side up, and + // f32 rounding can add one more pixel. + let max = MAX_RASTER_PIXELS as f64; + let fit = if (w + 2.0) * (h + 2.0) <= max { + 1.0 + } else { + let (a, b) = (w * h, 2.0 * (w + h)); + (-b + (b * b - 4.0 * a * (4.0 - max)).sqrt()) / (2.0 * a) + }; + let pixmap = render(&tree, cv.scale * fit as f32)?; + let px = pixmap + .pixels() + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + Ok((pixmap.width(), pixmap.height(), px)) +} + +/// `tree` drawn at `k` pixels per SVG unit on a transparent pixmap whose sides round up. +fn render(tree: &usvg::Tree, k: f32) -> Result { let side = |v: f32| ((v * k).ceil() as u32).max(1); let (w, h) = (side(tree.size().width()), side(tree.size().height())); let mut pixmap = pixmap(w, h).ok_or_else(|| IoError::Svg(format!("{w} × {h} px is too large to rasterise")))?; - resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut()); - let rect = Rect::new(0, 0, w as i32, h as i32); - let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect(); - Ok(photocraft_compose::Buffer { rect, px }) + resvg::render(tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut()); + Ok(pixmap) } /// A transparent pixmap, or `None` past [`MAX_RASTER_PIXELS`]. @@ -792,4 +825,26 @@ mod tests { assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); assert_eq!(w.len(), 1); } + + /// A pasted drawing is one pixel per SVG unit, and a drawing past the pixel limit is scaled + /// down to fit it, keeping its proportions, instead of failing. + #[test] + fn rgba8_renders_at_its_own_size_within_the_pixel_limit() { + let svg = br##""##; + let (w, h, px) = rasterize_rgba8(svg).unwrap(); + assert_eq!((w, h, px.len()), (40, 20, 40 * 20 * 4)); + assert_eq!(px[..4], [255, 0, 0, 255], "the rectangle"); + assert_eq!(px[(10 * 40 + 30) * 4..][..4], [0, 0, 0, 0], "transparent beside it"); + for (side_w, side_h) in [(10_000u32, 5_000u32), (20_000, 20_000), (20_000, 2_000)] { + let svg = format!(""); + let (w, h, px) = rasterize_rgba8(svg.as_bytes()).unwrap(); + let pixels = u64::from(w) * u64::from(h); + assert!(pixels <= MAX_RASTER_PIXELS && pixels > MAX_RASTER_PIXELS / 2, "{side_w} × {side_h} became {w} × {h}"); + assert!(w <= MAX_SIDE && h <= MAX_SIDE, "{w} × {h}"); + let (aspect, want) = (f64::from(w) / f64::from(h), f64::from(side_w) / f64::from(side_h)); + assert!((aspect / want - 1.0).abs() < 0.01, "{w} × {h} keeps {side_w} × {side_h}"); + assert_eq!(px.len() as u64, pixels * 4); + } + assert!(rasterize_rgba8(b" Date: Sat, 17 Oct 2026 20:12:31 -0700 Subject: [PATCH 18/73] Print: list printers and spool from one thread at a time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Windows 11 (winspool.drv 10.0.26100.9444) the custom_print_paper test binary died with STATUS_ACCESS_VIOLATION. Its three tests open the Print dialog at once, and each one lists printers: file.printers calls craft_print::printers(), which opens each printer's PrintTicket provider (PTOpenProvider). winspool creates a process-wide cache without a lock the first time PTOpenProvider is called for a printer whose provider is PrintConfig.dll. When two threads do this together, winspool can leave its pointer to the cache on a freed object, and the next caller enters that object's deleted critical section. The app can make the same calls from two threads: the Print dialog on the UI thread and a print job's worker. print_cmds::with_spooler holds a process-wide lock around every call PhotoCraft makes into craft-print that lists printers or reaches the spooler or a driver: craft_print::printers and submit, and rgb's printers, default_printer, page, print and settings_dialog. A panic inside the lock does not block later callers. While a print job is being handed to the spooler, File › Print waits for it before the dialog opens. Session::printer_source supplies the printers that file.printers, file.print.printers and the Print dialog list, in place of the spooler's. The tests that open Print or list printers set it, so they no longer query the system's printers or load their drivers. print_cmds::system_printer_listings counts the real listings, and the dialog and print job tests assert that it stays 0. The app leaves printer_source unset and lists the spooler's printers as before. New tests: printer_listings_enter_the_spooler_one_thread_at_a_time (eight threads list printers at once; it fails without the lock) and a_panic_inside_the_spooler_does_not_block_later_callers. --- crates/engine/src/lib.rs | 3 + crates/engine/src/print_cmds.rs | 68 +++++++++++++++++--- crates/engine/src/print_cmds/tests.rs | 72 +++++++++++++++++++--- crates/engine/tests/panic_hunt.rs | 2 + crates/ui-egui/src/file_ui.rs | 13 ++-- crates/ui-egui/src/jobs_ui_tests.rs | 2 + crates/ui-egui/tests/custom_print_paper.rs | 14 ++++- 7 files changed, 151 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b076769040..1c1a968cb5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -489,6 +489,9 @@ pub struct Session { /// A further route for File › Print when neither `lp` nor a CUPS server over IPP is /// reachable (the XDG Print portal in a Flatpak); see `print_cmds::Spooler`. pub print_spooler: Option, + /// The printers `file.printers`, `file.print.printers` and the Print dialog list in place of + /// the system's (tests); see `print_cmds::PrinterSource`. `None` asks the spooler. + pub printer_source: Option, /// Background jobs (see [`jobs`]). jobs: jobs::Jobs, /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 3cc99aa276..bf452315de 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -71,6 +71,53 @@ pub struct Spooler { pub run: SpoolFn, } +/// A stand-in for the system's printers, installed on `Session::printer_source` (tests): +/// `file.printers`, `file.print.printers` and the Print dialog list these and do not ask the spooler. +pub type PrinterSource = std::sync::Arc Vec + Send + Sync>; + +/// Held while a thread of this process lists printers or calls into a printer driver. +static SPOOLER: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Runs `f`, which lists printers or calls into a printer driver, while no other thread of this +/// process does either. On Windows, two threads that open printers' PrintTicket providers for the +/// first time at once can crash the process inside the spooler client (`winspool.drv`). A panic in +/// an earlier caller does not block later ones. +pub fn with_spooler(f: impl FnOnce() -> T) -> T { + let _held = SPOOLER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + f() +} + +/// Counts the times this process asked the system for its printers. +static SYSTEM_LISTINGS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// How many times this process has asked the system for its printers. A session with a +/// `printer_source` does not ask. +pub fn system_printer_listings() -> usize { + SYSTEM_LISTINGS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The printers `craft-print` spools to, or the session's stand-in for them. +fn system_printer_list(s: &Session) -> Vec { + with_spooler(|| match &s.printer_source { + Some(source) => source(), + None => { + SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + craft_print::printers() + } + }) +} + +/// The printers the GDI route prints to (`craft_print::rgb`), or the session's stand-in for them. +pub fn rgb_printers(s: &Session) -> std::result::Result, craft_print::rgb::PrintError> { + with_spooler(|| match &s.printer_source { + Some(source) => Ok(source().into_iter().map(|p| craft_print::rgb::Printer { name: p.name, default: p.default }).collect()), + None => { + SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + craft_print::rgb::printers() + } + }) +} + /// Why the IPP route could not spool: no route at all (the app's spooler may have one), or a /// failure on a route that exists (a wrong printer name, a rejected job). enum SpoolError { @@ -90,7 +137,7 @@ fn spool_job(spooler: Option<&Spooler>, job: &PrintJob, lp: &craft_print::Job) - return app(sp); } if let Some(name) = system_spooler() { - return craft_print::submit(&job.pdf, lp).map(|m| (m, name.to_string())).map_err(other); + return with_spooler(|| craft_print::submit(&job.pdf, lp)).map(|m| (m, name.to_string())).map_err(other); } } match cups_spool(job) { @@ -189,10 +236,10 @@ fn cups_spool(job: &PrintJob) -> std::result::Result { /// `file.printers`: the printers the system's (or `printServer`'s) print server knows, with the default. From /// `craft-print` (`lpstat`, the Windows spooler) where that is the route; over IPP for a named /// server and where there is no `lp` (a sandbox). -fn system_printers(_s: &mut Session, p: &Value) -> Result { +fn system_printers(s: &mut Session, p: &Value) -> Result { let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); - if named.is_none() && system_spooler().is_some() { - let list = craft_print::printers(); + if named.is_none() && (s.printer_source.is_some() || system_spooler().is_some()) { + let list = system_printer_list(s); let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); return Ok(json!({"server": Value::Null, "default": default, "printers": printers})); @@ -671,7 +718,7 @@ fn printer_name(p: &Value) -> Result { if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { return Ok(name.to_string()); } - craft_print::rgb::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set")) + with_spooler(craft_print::rgb::default_printer).map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set")) } /// The driver settings chosen with Print Settings… (`printerSettings`, hex), when any. @@ -717,7 +764,7 @@ pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) { fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Result { let printer = printer_name(p)?; let settings = printer_settings(p)?; - let device_page = craft_print::rgb::page(&printer, settings.as_ref()).map_err(other)?; + let device_page = with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())).map_err(other)?; if (device_page.paper.0 - page.paper.0).abs() > 2.0 || (device_page.paper.1 - page.paper.1).abs() > 2.0 { return Err(other("the driver paper or orientation differs from the print layout; choose the matching paper in Print Settings before printing")); } @@ -739,14 +786,14 @@ fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Resul color_policy, primitives: &primitives, }; - let done = craft_print::rgb::print(&job, &image, rect).map_err(other)?; + let done = with_spooler(|| craft_print::rgb::print(&job, &image, rect)).map_err(other)?; Ok( json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}), ) } -fn printers(_: &mut Session, _: &Value) -> Result { - match craft_print::rgb::printers() { +fn printers(s: &mut Session, _: &Value) -> Result { + match rgb_printers(s) { Ok(list) => Ok(json!({"supported": true, "printers": list.iter().map(|p| json!({"name": p.name, "default": p.default})).collect::>()})), Err(craft_print::rgb::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})), Err(e) => Err(other(e)), @@ -755,7 +802,8 @@ fn printers(_: &mut Session, _: &Value) -> Result { fn printer_page(_: &mut Session, p: &Value) -> Result { let printer = printer_name(p)?; - let pg = craft_print::rgb::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?; + let settings = printer_settings(p)?; + let pg = with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())).map_err(other)?; Ok( json!({"printer": printer, "paper": [pg.paper.0, pg.paper.1], "printable": [pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3], "dpi": [pg.dpi.0, pg.dpi.1]}), ) diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index ddd1a65a16..83eca48f0b 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -196,12 +196,23 @@ fn native_rgb_route_preserves_pdf_only_color_and_page_content() { assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false), "noColorManagement")); } +/// Two printers, the second the default, in place of the system spooler's. +fn test_printers() -> PrinterSource { + std::sync::Arc::new(|| { + vec![ + craft_print::Printer { name: "Studio".into(), default: false, two_sided: None }, + craft_print::Printer { name: "Office".into(), default: true, two_sided: Some(true) }, + ] + }) +} + #[test] fn printer_commands_answer_without_a_document_and_reject_bad_settings() { let mut s = Session::new(); + s.printer_source = Some(test_printers()); let r = s.execute("file.print.printers", json!({})).unwrap(); - assert_eq!(r["supported"], cfg!(windows)); - assert!(r["printers"].is_array()); + assert_eq!(r["supported"], true); + assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}])); assert!(s.execute("file.print.page", json!({"printer": "Anything", "printerSettings": "zz"})).is_err()); let mut s = session("rgb", 8); assert!(s.execute("file.print", json!({"printer": "Anything", "printerSettings": "0102", "send": true})).is_err()); @@ -433,13 +444,60 @@ fn disabled_printing_never_spools() { #[test] fn printers_lists_the_spooler_destinations_without_a_document() { let mut s = Session::new(); + s.printer_source = Some(test_printers()); let r = s.execute("file.printers", json!({})).unwrap(); - let list = r["printers"].as_array().unwrap(); - assert!(list.iter().all(|p| p["name"].is_string() && p["default"].is_boolean())); - match r["default"].as_str() { - Some(d) => assert!(list.iter().any(|p| p["name"] == d && p["default"] == true)), - None => assert!(list.iter().all(|p| p["default"] == false)), + assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}])); + assert_eq!(r["default"], "Office"); + s.printer_source = Some(std::sync::Arc::new(Vec::new)); + let r = s.execute("file.printers", json!({})).unwrap(); + assert_eq!((r["printers"].clone(), r["default"].clone()), (json!([]), Value::Null)); +} + +/// Threads that list printers at the same time enter the spooler one at a time: the stand-in +/// printer list records how many threads were inside it at once. +#[test] +fn printer_listings_enter_the_spooler_one_thread_at_a_time() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier}; + const THREADS: usize = 8; + let inside = Arc::new(AtomicUsize::new(0)); + let most = Arc::new(AtomicUsize::new(0)); + let start = Arc::new(Barrier::new(THREADS)); + let threads: Vec<_> = (0..THREADS) + .map(|i| { + let (inside, most, start) = (Arc::clone(&inside), Arc::clone(&most), Arc::clone(&start)); + std::thread::spawn(move || { + let mut s = Session::new(); + s.printer_source = Some(Arc::new(move || { + let now = inside.fetch_add(1, Ordering::SeqCst) + 1; + most.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(5)); + inside.fetch_sub(1, Ordering::SeqCst); + vec![craft_print::Printer { name: "Office".into(), default: true, two_sided: None }] + })); + start.wait(); + for _ in 0..3 { + let id = if i % 2 == 0 { "file.printers" } else { "file.print.printers" }; + assert_eq!(s.execute(id, json!({})).unwrap()["printers"][0]["name"], "Office"); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); } + assert_eq!(most.load(Ordering::SeqCst), 1, "two threads were in the printer listing at once"); +} + +/// A caller that panics inside the spooler leaves it usable for later callers. +#[test] +fn a_panic_inside_the_spooler_does_not_block_later_callers() { + let panicked = std::thread::spawn(|| with_spooler::<()>(|| panic!("a driver call panicked"))).join(); + assert!(panicked.is_err()); + assert_eq!(with_spooler(|| 7), 7); + let mut s = Session::new(); + s.printer_source = Some(test_printers()); + assert_eq!(s.execute("file.printers", json!({})).unwrap()["default"], "Office"); } /// Spooling tests run in a child process: `disable_printing` is process-wide and a test above diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 893ba5c23d..36b392a9ea 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -13,6 +13,8 @@ fn fresh() -> Session { // Belt and braces with the EXTERNAL skip below: nothing in this process may reach a printer. photocraft_engine::print_cmds::disable_printing(); let mut s = Session::new(); + // `file.printers` and `file.print.printers` list no printers and do not ask the spooler. + s.printer_source = Some(std::sync::Arc::new(Vec::new)); s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); s.execute("select.rect", json!({"x": 1, "y": 1, "width": 6, "height": 5})).unwrap(); diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 3f87f6339c..2a5e632940 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -758,7 +758,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { f.entry(k.to_string()).or_insert(v); } // Windows: the system's printers, and the paper from the chosen printer's driver settings. - if let Ok(list) = craft_print::rgb::printers() { + if let Ok(list) = photocraft_engine::print_cmds::rgb_printers(&app.session) { f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); let known = |n: &str| list.iter().any(|p| p.name == n); if !known(&s(&f, "printer", "")) { @@ -774,7 +774,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { fn driver_page(f: &mut Map) { let printer = s(f, "printer", ""); let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); - match craft_print::rgb::page(&printer, settings.as_ref()) { + match photocraft_engine::print_cmds::with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())) { Ok(pg) => { f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); f.insert("orientation".into(), json!("portrait")); @@ -976,7 +976,7 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { f.insert("printerSettings".into(), json!(dm.to_hex())); driver_page(f); @@ -1168,6 +1168,8 @@ mod tests { fn app() -> (PhotocraftApp, egui::Context) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // Print lists this printer and does not ask the spooler. + app.session.printer_source = Some(Arc::new(|| vec![craft_print::Printer { name: "Test printer".into(), default: true, two_sided: None }])); app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap(); (app, egui::Context::default()) } @@ -1447,9 +1449,12 @@ mod tests { let (mut app, ctx) = app(); let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); let f = &app.ui.dialog_mut(id).unwrap().fields; - assert!(f.get("__systemPrinters").is_some_and(Value::is_array)); + assert_eq!(f["__systemPrinters"], json!([{"name": "Test printer", "default": true}])); + assert_eq!((f["__printers"].clone(), f["printer"].clone()), (json!(["Test printer"]), json!("Test printer"))); assert!(params(f).get("__systemPrinters").is_none()); assert!(params(f).get("__printers").is_none()); + // Every test in this binary that opens Print lists the session's printers. + assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers"); } #[test] diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rs index f2b7d0fbc0..f2f39d040b 100644 --- a/crates/ui-egui/src/jobs_ui_tests.rs +++ b/crates/ui-egui/src/jobs_ui_tests.rs @@ -703,6 +703,8 @@ fn printing_keeps_drawing_and_reports_only_the_final_spooler_result() { assert!(h.state().ui.status_error); } } + // The job and its status do not ask the system spooler for its printers. + assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers"); } fn layer_count(app: &PhotocraftApp) -> usize { diff --git a/crates/ui-egui/tests/custom_print_paper.rs b/crates/ui-egui/tests/custom_print_paper.rs index d0d81dea69..b65d7ce10b 100644 --- a/crates/ui-egui/tests/custom_print_paper.rs +++ b/crates/ui-egui/tests/custom_print_paper.rs @@ -6,15 +6,24 @@ use serde_json::{Map, Value, json}; fn app() -> (PhotocraftApp, u64) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + // Exercise PDF paper controls even when native printers are available, on every OS. Print + // lists this printer and does not ask the spooler. + app.session.printer_source = + Some(std::sync::Arc::new(|| vec![craft_print::Printer { name: "Test native printer".into(), default: true, two_sided: None }])); app.run("file.new", json!({"width": 120, "height": 80, "name": "Custom paper"})).unwrap(); let id = open_print(&mut app); + assert_no_system_listing(); // Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog. app.ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true)); - // Exercise PDF paper controls even when native printers are available, on every OS. - app.ui.dialog_mut(id).unwrap().fields.insert("__printers".into(), json!(["Test native printer"])); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__printers"], json!(["Test native printer"])); (app, id) } +/// No test in this binary asks the system spooler for its printers. +fn assert_no_system_listing() { + assert_eq!(photocraft_engine::print_cmds::system_printer_listings(), 0, "a test asked the system spooler for its printers"); +} + fn show(ui: &mut egui::Ui, app: &mut PhotocraftApp) { if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { photocraft_ui_egui::dialogs::show(app, ui.ctx()); @@ -105,6 +114,7 @@ fn custom_paper_ui_edits_reach_preview_and_pdf_and_restore_when_reopened() { assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 666.00 522.00]")); assert_eq!(h.state().session.file_menu.last_print.as_ref().unwrap()["paper"], json!([522.0, 666.0])); let id = open_print(h.state_mut()); + assert_no_system_listing(); h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true)); h.run_steps(3); assert!(shown(&h, "Custom"), "reopening array-valued settings must show Custom"); From af4da5d602e9dcc73f5bf4aad40484684f59fcdb Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 14:55:20 +0200 Subject: [PATCH 19/73] Channels: Apply Image blends a CMYK layer as tone; spot channels read as tone (#5787) Apply Image now blends a CMYK layer's channels as tone, as Photoshop does, so the default Multiply with a white channel or mask no longer wipes the ink, and Multiply adds ink. A spot channel reads as its tone as well, so its solid ink applies as ink and Load Selection picks the unprinted area (checked in Photoshop). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 17 ++++++++++---- crates/engine/src/channel_cmds/tests.rs | 31 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index 7c4d1c4076..ca6ba905d9 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -445,7 +445,12 @@ fn ref_planes(doc: &Document, layer: Option, active: Option, r _ => planes, } } - ChanRef::Alpha(i) => vec![read_plane(&doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?.surface, area)], + ChanRef::Alpha(i) => { + let ch = doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?; + let plane = read_plane(&ch.surface, area); + // A spot channel stores ink (1 = solid) but reads as its tone, as in Photoshop. + vec![if ch.spot.is_some() { plane.into_iter().map(|v| 1.0 - v).collect() } else { plane }] + } ChanRef::QuickMask => vec![read_plane(&doc.quick_mask.as_ref().ok_or_else(|| EngineError::Other("not in Quick Mask mode".into()))?.surface, area)], ChanRef::Selection => vec![sel::mask_from_surface(doc.selection.as_ref(), area)], ChanRef::Transparency => { @@ -1713,10 +1718,12 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // source-over, so applying to an empty layer copies the source in any mode. let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; for (c, b) in px[..colors].iter_mut().enumerate() { - // One plane is a tone (a channel, a mask): a CMYK layer takes it as ink. - let top = if src.len() > 1 { src.get(c).unwrap_or(&src[0])[i] } else { tone(sf.mode, src[0][i]) }; - let blended = top + (blending.apply(*b, top) - top) * base_a; - *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; + // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back + // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. + let top = if src.len() > 1 { tone(sf.mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + let base = tone(sf.mode, *b); + let blended = top + (blending.apply(base, top) - top) * base_a; + *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); } if sf.alpha { px[colors] = out_a; diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 6e3a3facbd..5397d89c1a 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -645,6 +645,37 @@ fn cmyk_apply_image_of_a_colour_channel_keeps_ink_and_tone_apart() { } } +#[test] +fn cmyk_apply_image_blends_as_tone() { + // Photoshop blends a CMYK layer as tone: Multiply (the default) with a white source changes + // nothing, and Multiply with Cyan multiplies every channel's tone by Cyan's, so it adds ink. + // A spot channel reads as tone too: its solid ink applies as full ink and isn't selected. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": 0}})).unwrap(); + assert!(near(&px(&s, 5, 5), &left), "depth {depth}: white multiplies to no change, {:?} vs {left:?}", px(&s, 5, 5)); + s.undo(); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "multiply"})).unwrap(); + let want: Vec = left[..4].iter().map(|&ink| 1.0 - (1.0 - ink) * (1.0 - left[0])).chain([1.0]).collect(); + assert!(near(&px(&s, 5, 5), &want), "depth {depth}: {:?} vs {want:?}", px(&s, 5, 5)); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: no ink stays no ink"); + s.undo(); + rect(&mut s, 0, 0, 20, 20, "replace"); + let r = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap(); + let spot = r["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": spot}, "blending": "normal"})).unwrap(); + assert!(near(&px(&s, 5, 5), &[1.0; 5]) && near(&px(&s, 30, 5), &right), "depth {depth}: spot ink applies as ink, {:?}", px(&s, 5, 5)); + s.execute("select.loadSelection", json!({"channel": spot})).unwrap(); + assert!(sel_at(&s, 5, 5) < 1e-3 && (sel_at(&s, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: the spot's unprinted area loads"); + } +} + #[test] fn calculations_results() { let mut s = session(); From fcbb428ed527e9478e46e06d835f27f833a2f364 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 16:10:16 +0200 Subject: [PATCH 20/73] Channels: Apply Image and paste into a spot channel work in tone; copy a spot as tone (#5787) A spot channel stores ink but now reads as tone, so it must also take tone: Apply Image onto a spot (itself, Cyan, any source) and Paste into a spot convert its ink to tone and back, and copying a spot gives its tone. An RGB composite applied onto a CMYK layer is read in its own mode, so the default Multiply with white no longer fills the layer with ink. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_clip.rs | 14 ++++----- crates/engine/src/channel_clip/tests.rs | 29 ++++++++++++++++++ crates/engine/src/channel_cmds.rs | 28 ++++++++++++++++-- crates/engine/src/channel_cmds/tests.rs | 39 +++++++++++++++++++++++++ crates/engine/src/edit_cmds.rs | 8 +++++ 5 files changed, 109 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs index a23608f328..5bf31f0e38 100644 --- a/crates/engine/src/channel_clip.rs +++ b/crates/engine/src/channel_clip.rs @@ -36,17 +36,18 @@ pub(crate) fn copy(s: &mut Session) -> Result> { let Some(d) = s.active() else { return Ok(None) }; let doc = &d.doc; let canvas = doc.bounds(); - // The surface the values come from, and which of its samples is the channel. - let (src, k) = match d.channel_view.target { + // The surface the values come from, which of its samples is the channel, and whether it stores + // ink (CMYK, a spot channel) rather than tone. + let (src, k, ink) = match d.channel_view.target { ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask => return Ok(None), ChannelTarget::Color(k) => { let id = d.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; let surf = doc.layer(id).and_then(Layer::surface).ok_or_else(|| EngineError::Other("the active layer has no pixels".into()))?; - (surf, k) + (surf, k, surf.format().mode == ColorMode::Cmyk) } ChannelTarget::Alpha(i) => { let c = doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {})", doc.channels.len())))?; - (&c.surface, 0) + (&c.surface, 0, c.spot.is_some()) } }; let n = src.format().channels(); @@ -59,14 +60,13 @@ pub(crate) fn copy(s: &mut Session) -> Result> { return Err(EngineError::Other("Could not copy: the selected area is empty".into())); } let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, true); - let mode = src.format().mode; let values = crate::allocation::read_region(src, area, "copying a channel")?; let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?; let mut px = crate::allocation::capacity(len, "copying a channel")?; for (i, p) in values.chunks_exact(n).enumerate() { - // A CMYK channel copies as its tone (#5787). - px.push(p.get(k).map_or(0.0, |&v| crate::channel_cmds::tone(mode, v))); + // A CMYK or spot channel copies as its tone (#5787). + px.push(p.get(k).map_or(0.0, |&v| if ink { 1.0 - v } else { v })); px.push(cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0))); } let mut surface = Surface::new(fmt); diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs index cf35bef93e..a5e687b297 100644 --- a/crates/engine/src/channel_clip/tests.rs +++ b/crates/engine/src/channel_clip/tests.rs @@ -97,6 +97,35 @@ fn cmyk_channels_copy_and_paste_as_tone() { } } +#[test] +fn spot_channels_copy_and_paste_as_tone() { + // #5787: a spot channel stores ink but copies as its tone, and a tone pasted into it goes back + // to ink: spot -> Black prints the spot's ink in black, Cyan -> spot gives the spot Cyan's ink. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + let cyan = px(&s, 5, 5)[0]; + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": H})).unwrap(); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": spot})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let clip = &s.clipboard.as_ref().unwrap().surface; + assert!(clip.pixel(5, 5)[0] < 1e-3 && (clip.pixel(30, 5)[0] - 1.0).abs() < 1e-3, "depth {depth}: ink copies dark"); + s.execute("channel.target", json!({"channel": "black"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!((px(&s, 5, 5)[3] - 1.0).abs() < 2e-3 && px(&s, 30, 5)[3] < 2e-3, "depth {depth}: black = the spot's ink"); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": spot})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let ink = |x| s.active().unwrap().doc.channels[spot as usize].surface.sample_channel(x, 5, 0); + assert!(near(&[ink(5), ink(15), ink(30)], &[cyan, cyan, 0.0]), "depth {depth}: spot = Cyan's ink, {:?}", [ink(5), ink(15), ink(30)]); + } +} + #[test] fn copy_an_alpha_channel_without_a_pixel_layer() { let mut s = session(8); diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index c52cbb8b77..b511e45ad9 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -638,6 +638,19 @@ pub(crate) fn is_channel_target(p: &Value) -> bool { matches!(target_of(p), Target::Alpha(_) | Target::QuickMask) } +/// The target is a spot channel: it stores ink but takes tone, as it reads. +pub(crate) fn is_spot_target(doc: &Document, p: &Value) -> bool { + matches!(target_of(p), Target::Alpha(i) if doc.channels.get(i).is_some_and(|c| c.spot.is_some())) +} + +/// Inverts `r` of a channel surface (ink to tone and back). +pub(crate) fn invert_region(s: &mut Surface, r: Rect) -> Result<()> { + let mut v = crate::allocation::read_region(s, r, "inverting a channel")?; + v.iter_mut().for_each(|x| *x = 1.0 - *x); + s.try_write_region(r, &v)?; + Ok(()) +} + /// The surface a pixel command writes to and whether the layer's transparency is locked. pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { match target_of(p) { @@ -1680,6 +1693,8 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); let src = source(s, &src_spec, cmd, false)?; + // A composite's planes are in its own document's mode, which may not be the target's. + let src_mode = s.documents().get(doc_index(s, &src_spec, "document")?).map(|d| edit_mode(&d.doc)).ok_or(EngineError::NoDocument)?; let mask = mask_plane(s, p, cmd)?; let layer = s.active().and_then(|d| d.active_layer); s.edit("Apply Image", |doc, _| { @@ -1690,9 +1705,18 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // A grayscale target gets the luminosity of a colour source (one plane). let srcp = if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; + let spot = is_spot_target(doc, p); + let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; let base = read_plane(surf, area); - let out: Vec = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect(); + let out: Vec = base + .iter() + .enumerate() + .map(|(i, &b)| { + let b = ink(b); + ink(b + (blending.apply(b, srcp[i]) - b) * weight(i)) + }) + .collect(); *surf = plane_surface(&out, area, surf.format()); return Ok(()); } @@ -1722,7 +1746,7 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { for (c, b) in px[..colors].iter_mut().enumerate() { // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. - let top = if src.len() > 1 { tone(sf.mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; let base = tone(sf.mode, *b); let blended = top + (blending.apply(base, top) - top) * base_a; *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 5397d89c1a..5a8e64a952 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -676,6 +676,45 @@ fn cmyk_apply_image_blends_as_tone() { } } +#[test] +fn apply_image_onto_a_spot_channel_blends_as_tone() { + let near = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + // #5787: a spot channel stores ink but reads and takes tone, so the spot applied onto itself + // changes nothing (Normal or Multiply), and Cyan applied onto it gives it Cyan's ink. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let cyan = px(&s, 5, 5)[0]; + rect(&mut s, 0, 0, 10, 20, "replace"); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let ink = |s: &Session| [5, 15, 30].map(|x| chan(s, spot as usize, x, 5)); + let before = ink(&s); + assert!(near(&before, &[1.0, 0.0, 0.0]), "depth {depth}: {before:?}"); + for blending in ["normal", "multiply"] { + s.execute("image.applyImage", json!({"source": {"channel": spot}, "blending": blending, "target": {"channel": spot}})).unwrap(); + assert!(near(&ink(&s), &before), "depth {depth}: {blending} onto itself, {:?}", ink(&s)); + } + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal", "target": {"channel": spot}})).unwrap(); + assert!(near(&ink(&s), &[cyan, cyan, 0.0]), "depth {depth}: Cyan's ink, {:?}", ink(&s)); + } +} + +#[test] +fn apply_image_from_an_rgb_document_onto_cmyk_reads_it_in_its_own_mode() { + let near = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + // #5787: an RGB composite is tone in RGB terms: white multiplied (the default) onto a CMYK + // layer changes nothing. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "background": "white"})).unwrap(); + rect(&mut s, 0, 0, 20, 20, "replace"); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let before = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("image.applyImage", json!({"source": {"document": 0}})).unwrap(); + assert!(near(&px(&s, 5, 5), &before.0) && near(&px(&s, 30, 5), &before.1), "{:?} vs {before:?}", (px(&s, 5, 5), px(&s, 30, 5))); +} + #[test] fn calculations_results() { let mut s = session(); diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 7cdb595212..8bb073d497 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -481,8 +481,16 @@ pub(crate) fn paste_to_target(s: &mut Session, p: &Value, in_place: bool, limit: let src = shifted(&clip.surface, dx, dy); let area = src.content_bounds().intersect(&canvas); s.edit(label, |doc, _| { + // A spot channel stores ink: the paste goes over its tone, then back to ink (#5787). + let spot = crate::channel_cmds::is_spot_target(doc, p); let (surf, _) = crate::channel_cmds::target_surface(doc, layer, p)?; + if spot { + crate::channel_cmds::invert_region(surf, area)?; + } crate::fill_cmds::composite_over(surf, &src, area, limit)?; + if spot { + crate::channel_cmds::invert_region(surf, area)?; + } surf.prune(); doc.selection = None; Ok(()) From b1fdd74afe6169d145cebef78325c8838cae20d8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 16:50:44 +0200 Subject: [PATCH 21/73] Apply Image: a CMYK composite reads as tone onto channels and other modes (#5787) A CMYK composite applied onto a spot channel averaged its stored ink and then treated it as tone, so Normal on a white page filled the spot with solid ink (main left it empty). The composite's planes are now averaged as tone. Onto an RGB or Gray layer, Black alone turned white because K was dropped; each tone is now darkened by the source's Black. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 15 ++++++++--- crates/engine/src/channel_cmds/tests.rs | 35 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index b511e45ad9..d2f95f0edf 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1702,9 +1702,13 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); if is_channel_target(p) { - // A grayscale target gets the luminosity of a colour source (one plane). - let srcp = - if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; + // A grayscale target gets the luminosity of a colour source (one plane). A composite's + // planes are averaged as tone: a CMYK composite stores ink, so white has none. + let srcp = if src.len() == 1 { + src[0].clone() + } else { + (0..src[0].len()).map(|i| src.iter().map(|pl| tone(src_mode, pl[i])).sum::() / src.len() as f32).collect() + }; let spot = is_spot_target(doc, p); let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; @@ -1746,7 +1750,10 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { for (c, b) in px[..colors].iter_mut().enumerate() { // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. - let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + // A CMYK composite onto another mode darkens each tone by its Black, so Black + // alone stays black. + let k = if src_mode == ColorMode::Cmyk && sf.mode != ColorMode::Cmyk { src.get(3).map_or(1.0, |pl| tone(src_mode, pl[i])) } else { 1.0 }; + let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] }; let base = tone(sf.mode, *b); let blended = top + (blending.apply(base, top) - top) * base_a; *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 5a8e64a952..a461b655b0 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -715,6 +715,41 @@ fn apply_image_from_an_rgb_document_onto_cmyk_reads_it_in_its_own_mode() { assert!(near(&px(&s, 5, 5), &before.0) && near(&px(&s, 30, 5), &before.1), "{:?} vs {before:?}", (px(&s, 5, 5), px(&s, 30, 5))); } +#[test] +fn apply_image_of_a_cmyk_composite_onto_a_spot_channel_blends_as_tone() { + // #5787: the CMYK composite stores ink, so its white has none: applied in Normal onto an empty + // spot channel, the spot stays empty on the white and takes ink on the Cyan. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap() as usize; + s.execute("image.applyImage", json!({"blending": "normal", "target": {"channel": spot}})).unwrap(); + let (cyan, white) = (chan(&s, spot, 5, 5), chan(&s, spot, 30, 5)); + assert!(white < 0.01 && cyan > 0.1 && cyan < 0.9, "depth {depth}: cyan {cyan}, white {white}"); + } +} + +#[test] +fn apply_image_of_a_cmyk_composite_onto_rgb_keeps_black() { + // #5787: Black alone (no C, M or Y) applied from a CMYK document onto RGB stays black, and + // the CMYK white stays white (the merged image goes through RGB, so a few levels of drift). + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "background": "white"})).unwrap(); + { + let d = s.active_mut().unwrap(); + let id = d.active_layer.unwrap(); + let surf = std::sync::Arc::make_mut(&mut d.doc).layer_mut(id).unwrap().surface_mut().unwrap(); + let n = surf.format().channels(); + let mut k = vec![0.0; 20 * 20 * n]; + k.chunks_exact_mut(n).for_each(|p| p[3] = 1.0); + surf.write_region(Rect::new(0, 0, 20, 20), &k); + } + s.execute("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"document": 0}, "blending": "normal"})).unwrap(); + let (black, white) = (px(&s, 5, 5), px(&s, 30, 5)); + assert!(black[..3].iter().all(|&v| v < 0.05), "{black:?}"); + assert!(white[..3].iter().all(|&v| v > 0.95), "{white:?}"); +} + #[test] fn calculations_results() { let mut s = session(); From 9154d64ce5bee7fe740f88a45623b193e6bd9369 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 15:17:44 +0200 Subject: [PATCH 22/73] Channels: Apply Image of a CMYK composite onto a channel takes its luminosity (#5787) An average of the four tones left Black alone light gray (0.67 where Calculations reads 0.13); the channel now gets the same luminosity Calculations reads. Other modes are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 15 +++++++-------- crates/engine/src/channel_cmds/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index d2f95f0edf..f2f1ef3a5b 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1692,9 +1692,11 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); - let src = source(s, &src_spec, cmd, false)?; // A composite's planes are in its own document's mode, which may not be the target's. let src_mode = s.documents().get(doc_index(s, &src_spec, "document")?).map(|d| edit_mode(&d.doc)).ok_or(EngineError::NoDocument)?; + // A CMYK composite reaches a channel as its luminosity, as Calculations reads it: its planes + // are ink, and an average of their tones would leave Black alone light gray. + let src = source(s, &src_spec, cmd, src_mode == ColorMode::Cmyk && is_channel_target(p))?; let mask = mask_plane(s, p, cmd)?; let layer = s.active().and_then(|d| d.active_layer); s.edit("Apply Image", |doc, _| { @@ -1702,13 +1704,10 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); if is_channel_target(p) { - // A grayscale target gets the luminosity of a colour source (one plane). A composite's - // planes are averaged as tone: a CMYK composite stores ink, so white has none. - let srcp = if src.len() == 1 { - src[0].clone() - } else { - (0..src[0].len()).map(|i| src.iter().map(|pl| tone(src_mode, pl[i])).sum::() / src.len() as f32).collect() - }; + // A grayscale target gets one plane: a CMYK composite's luminosity (above), the average of + // another composite's planes. + let srcp = + if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; let spot = is_spot_target(doc, p); let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index a461b655b0..01a24c4414 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -750,6 +750,31 @@ fn apply_image_of_a_cmyk_composite_onto_rgb_keeps_black() { assert!(white[..3].iter().all(|&v| v > 0.95), "{white:?}"); } +#[test] +fn apply_image_of_a_cmyk_composite_onto_an_alpha_channel_takes_its_luminosity() { + // #5787: a CMYK composite reaches a channel as its luminosity, as Calculations reads it, so + // Black alone stays dark and white stays white. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + { + let d = s.active_mut().unwrap(); + let id = d.active_layer.unwrap(); + let surf = std::sync::Arc::make_mut(&mut d.doc).layer_mut(id).unwrap().surface_mut().unwrap(); + let n = surf.format().channels(); + let mut k = vec![1.0; 20 * 20 * n]; + k.chunks_exact_mut(n).for_each(|p| p[..3].fill(0.0)); + surf.write_region(Rect::new(0, 0, 20, 20), &k); + } + let a = s.execute("channel.new", json!({})).unwrap()["channel"].as_u64().unwrap() as usize; + s.execute("image.applyImage", json!({"blending": "normal", "target": {"channel": a}})).unwrap(); + let b = s.execute("image.calculations", json!({"source1": {}, "source2": {}, "blending": "normal"})).unwrap()["channel"].as_u64().unwrap() as usize; + let (black, white) = (chan(&s, a, 5, 5), chan(&s, a, 30, 5)); + assert!(black < 0.25 && (white - 1.0).abs() < 1e-3, "depth {depth}: black {black}, white {white}"); + assert!((black - chan(&s, b, 5, 5)).abs() < 1e-3, "depth {depth}: as Calculations reads it"); + } +} + #[test] fn calculations_results() { let mut s = session(); From a6d36d0879dfc9b1c8f04449fbb764235ec6ce95 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 16:54:40 +0200 Subject: [PATCH 23/73] Crop: the default-mode swap test expects X to turn the ratio frame (#7057) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/crop_default_mode.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/crop_default_mode.rs b/crates/ui-egui/tests/crop_default_mode.rs index 7c426410db..58d9709e99 100644 --- a/crates/ui-egui/tests/crop_default_mode.rs +++ b/crates/ui-egui/tests/crop_default_mode.rs @@ -126,7 +126,7 @@ fn a_ratio_dropdown_updates_the_preview_and_enter_without_touching_a_handle() { } #[test] -fn the_swap_button_and_x_apply_the_same_inscribed_ratio() { +fn the_swap_button_and_x_swap_the_ratio_about_the_centre() { // Windows WARP can access-violate when GPU harnesses initialize or tear down concurrently: // hold the GPU lock for the whole test, harness included. let _gpu = photocraft_testkit::gpu_lock(); @@ -148,7 +148,8 @@ fn the_swap_button_and_x_apply_the_same_inscribed_ratio() { h.run_steps(3); h.key_press(Key::X); h.run_steps(3); - assert_eq!(h.state().ui.crop_rect, Some(button)); + // X turns the frame instead of fitting the turned ratio inside it (#7057). + assert_eq!(h.state().ui.crop_rect, Some([70.0, -20.0, 230.0, 220.0])); assert!(mid(screen_box(&h)).distance(before) < 0.01); } From ebe865e686e80c0ec2d3068b1abbdfd2a6f67d26 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 17:28:38 +0200 Subject: [PATCH 24/73] Layered TIFF test: PSD saves now switch to PSB on the encoded size Main's layered TIFF test (#5514) checked the removed size estimate and expected a .psd of 140 cheap fills to become PSB. With the encoded-size switch that file stays PSD; the TIFF still writes PSD-style layer data because it turns size_limit_psb off. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/tiff_layers.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 7da61fa466..b8f57334c6 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -204,10 +204,9 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr // keeps straight alpha) and uncompressed (its planes are interleaved below). // Layer data is written PSD-style ("Adobe Photoshop Document Data Block", 4-byte lengths), as // Photoshop writes it: Photoshop does not read the PSB-style header ("... Data V0002") in a - // TIFF and opens only the composite, as one locked Background. The exporter's size estimate - // counts layer planes uncompressed, so a document with many canvas-sized layers passes 2 GB - // while its real layer data is a small fraction of that; it is not used here. PSB-style data - // is written only past 30000 px, when asked for, or when a length really overflows 32 bits. + // TIFF and opens only the composite, as one locked Background. The exporter's switch to PSB + // on the encoded file size is not used here: PSB-style data is written only past 30000 px, + // when asked for, or when a length really overflows 32 bits. let force_psb = opts.force_psb || big; let psd_opts = PsdExportOptions { force_psb, @@ -311,11 +310,11 @@ mod tests { use crate::{ExportOptions, export}; - /// Hidden solid fills on a 2048² canvas: the PSD size estimate counts each one as a - /// canvas-sized plane (16 MiB at 8 bits), so 140 of them pass 2 GB, while their real pixels - /// (the cached rendering, pruned to nothing) take almost no space. A layered TIFF of such a - /// document must still carry PSD-style layer data: Photoshop does not read the PSB-style - /// header in a TIFF and opens only the composite, as one locked Background. + /// Hidden solid fills on a 2048² canvas: counted as canvas-sized planes (16 MiB each at 8 + /// bits), 140 of them pass 2 GB, while their real pixels (the cached rendering, pruned to + /// nothing) take almost no space. A layered TIFF of such a document must still carry + /// PSD-style layer data: Photoshop does not read the PSB-style header in a TIFF and opens only + /// the composite, as one locked Background. fn many_cheap_fills() -> Document { let mut doc = Document::new("many fills", photocraft_geom::Size::new(2048, 2048), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8); for i in 0..140 { @@ -331,7 +330,6 @@ mod tests { #[test] fn layered_tiff_ignores_the_uncompressed_size_estimate() { let doc = many_cheap_fills(); - assert!(crate::psd_export::psd_size_exceeds_limit(&doc), "the fixture must pass the 2 GB estimate"); let r = export(&doc, "x.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap(); let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes); @@ -341,9 +339,9 @@ mod tests { let back = crate::import("x.tif", &r.bytes).unwrap().document; assert_eq!(back.layers.len(), doc.layers.len()); - // A .psd save still switches to PSB on the estimate, as before. + // A .psd save switches to PSB on the encoded size, which is small here: it stays PSD. let psd = export(&doc, "x.psd", &ExportOptions::default()).unwrap(); - assert_eq!(psd.bytes.get(4..6), Some(&[0u8, 2][..]), "PSD saves keep the size-estimate switch"); + assert_eq!(psd.bytes.get(4..6), Some(&[0u8, 1][..]), "PSD saves switch on the encoded size"); } #[test] From 3758eec7b44730023252a177a03cff99621b7015 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 19:45:47 +0200 Subject: [PATCH 25/73] 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 c4b53a20f8..cc70f448d9 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 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 169 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 171 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -179,7 +179,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 25 of 169** (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: 25 of 171** (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`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From e504339385406768a0becaf679cc131fcb276a03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 20 Oct 2026 18:46:43 -0700 Subject: [PATCH 26/73] Print: the Print dialog does not wait for the spooler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Print listed printers under the spooler lock on the UI thread, and the dialog's Printer menu, Print Settings… and Orientation buttons called the driver under it too, so the UI waited while a print job was being handed to the spooler. The dialog now tries the lock. While another thread holds it, the dialog lists the printers from the last listing in this process (only the first listing in the process waits), and the driver controls show that the driver is busy and leave the settings as they were. A driver call made while the same thread holds the lock runs at once. --- crates/engine/src/print_cmds.rs | 115 +++++++++++++++++++++++--- crates/engine/src/print_cmds/tests.rs | 65 +++++++++++++++ crates/ui-egui/src/file_ui.rs | 90 ++++++++++++++++---- 3 files changed, 239 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 1c75632afe..5d32d2eb4b 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -81,9 +81,31 @@ static SPOOLER: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// Runs `f`, which lists printers or calls into a printer driver, while no other thread of this /// process does either. On Windows, two threads that open printers' PrintTicket providers for the /// first time at once can crash the process inside the spooler client (`winspool.drv`). A panic in -/// an earlier caller does not block later ones. +/// an earlier caller does not block later ones. A call made inside `f` on the same thread runs at +/// once. pub fn with_spooler(f: impl FnOnce() -> T) -> T { + if HOLDING.get() { + return f(); + } let _held = SPOOLER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + holding(f) +} + +thread_local! { + /// Whether this thread holds `SPOOLER`. + static HOLDING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with `HOLDING` set; called with `SPOOLER` held. +fn holding(f: impl FnOnce() -> T) -> T { + struct Release; + impl Drop for Release { + fn drop(&mut self) { + HOLDING.set(false); + } + } + HOLDING.set(true); + let _release = Release; f() } @@ -96,26 +118,96 @@ pub fn system_printer_listings() -> usize { SYSTEM_LISTINGS.load(std::sync::atomic::Ordering::Relaxed) } -/// The printers `craft-print` spools to, or the session's stand-in for them. -fn system_printer_list(s: &Session) -> Vec { - with_spooler(|| match &s.printer_source { +/// Runs `f` as `with_spooler` does, or returns `None` at once while another thread of this +/// process holds the lock (the UI thread, which must not wait for a print job or a driver). +pub fn try_with_spooler(f: impl FnOnce() -> T) -> Option { + if HOLDING.get() { + return Some(f()); + } + let _held = match SPOOLER.try_lock() { + Ok(held) => held, + Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => return None, + }; + Some(holding(f)) +} + +/// What the Print dialog shows when `try_with_spooler` finds the lock held. +pub const SPOOLER_BUSY: &str = "the printer driver is busy with another print; try again when it finishes"; + +/// The GDI route's printers, or why they could not be listed. +pub type RgbPrinters = std::result::Result, craft_print::rgb::PrintError>; + +/// The last answers `system_printer_list` and `rgb_printers` got in this process. +static LAST_PRINTERS: std::sync::Mutex>> = std::sync::Mutex::new(None); +static LAST_RGB_PRINTERS: std::sync::Mutex> = std::sync::Mutex::new(None); + +fn last(kept: &std::sync::Mutex>) -> Option { + kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +} + +fn keep(kept: &std::sync::Mutex>, value: T) { + *kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(value); +} + +/// Lists the printers; called with the spooler lock held. +fn list_system_printers(s: &Session) -> Vec { + let list = match &s.printer_source { Some(source) => source(), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); craft_print::printers() } - }) + }; + keep(&LAST_PRINTERS, list.clone()); + list } -/// The printers the GDI route prints to (`craft_print::rgb`), or the session's stand-in for them. -pub fn rgb_printers(s: &Session) -> std::result::Result, craft_print::rgb::PrintError> { - with_spooler(|| match &s.printer_source { +/// Lists the GDI route's printers; called with the spooler lock held. +fn list_rgb_printers(s: &Session) -> RgbPrinters { + let list = match &s.printer_source { Some(source) => Ok(source().into_iter().map(|p| craft_print::rgb::Printer { name: p.name, default: p.default }).collect()), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); craft_print::rgb::printers() } - }) + }; + keep(&LAST_RGB_PRINTERS, list.clone()); + list +} + +/// The printers `craft-print` spools to, or the session's stand-in for them. +fn system_printer_list(s: &Session) -> Vec { + with_spooler(|| list_system_printers(s)) +} + +/// The printers the GDI route prints to (`craft_print::rgb`), or the session's stand-in for them. +pub fn rgb_printers(s: &Session) -> RgbPrinters { + with_spooler(|| list_rgb_printers(s)) +} + +/// `rgb_printers` for the UI thread: while another thread lists printers or is in a printer driver +/// (a print job being handed to the spooler, Print Settings…), the list the last listing in this +/// process got, without waiting. Only the first listing in the process waits. +pub fn rgb_printers_without_waiting(s: &Session) -> RgbPrinters { + try_with_spooler(|| list_rgb_printers(s)).or_else(|| last(&LAST_RGB_PRINTERS)).unwrap_or_else(|| rgb_printers(s)) +} + +/// `file.printers` for the UI thread, which lists the printers as `rgb_printers_without_waiting` +/// does where `craft-print` is the route. +pub fn printers_without_waiting(s: &mut Session) -> Value { + if s.printer_source.is_none() && system_spooler().is_none() { + return system_printers(s, &json!({})).unwrap_or_default(); + } + let list = try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS)).unwrap_or_else(|| system_printer_list(s)); + printers_answer(list) +} + +/// `file.printers`' answer for a list from `craft-print`. +fn printers_answer(list: Vec) -> Value { + let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); + let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); + json!({"server": Value::Null, "default": default, "printers": printers}) } /// Why the IPP route could not spool: no route at all (the app's spooler may have one), or a @@ -240,10 +332,7 @@ fn cups_spool(job: &PrintJob) -> std::result::Result { fn system_printers(s: &mut Session, p: &Value) -> Result { let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); if named.is_none() && (s.printer_source.is_some() || system_spooler().is_some()) { - let list = system_printer_list(s); - let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); - let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); - return Ok(json!({"server": Value::Null, "default": default, "printers": printers})); + return Ok(printers_answer(system_printer_list(s))); } #[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] { diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index ee323ad45b..3345888b8c 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -615,6 +615,71 @@ fn a_panic_inside_the_spooler_does_not_block_later_callers() { assert_eq!(s.execute("file.printers", json!({})).unwrap()["default"], "Office"); } +/// A driver call made while this thread already holds the spooler (a command run from the Print +/// dialog's `try_with_spooler`) runs at once. +#[test] +fn a_thread_holding_the_spooler_does_not_wait_for_itself() { + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut s = Session::new(); + s.printer_source = Some(test_printers()); + // Inside one outer hold, so no other test takes the lock between the calls. + let answers = with_spooler(|| { + let nested = with_spooler(|| with_spooler(|| 7)); + let tried = try_with_spooler(|| with_spooler(|| try_with_spooler(|| 8))); + let listed = try_with_spooler(|| s.execute("file.printers", json!({})).unwrap()["default"].clone()); + (nested, tried, listed) + }); + done.send(answers).unwrap(); + }); + // Bounded, so a thread that waits for itself fails the test rather than hanging it. + let answers = finished.recv_timeout(std::time::Duration::from_secs(30)).expect("a thread holding the spooler waited for itself"); + assert_eq!(answers, (7, Some(Some(8)), Some(json!("Office")))); +} + +/// While another thread is in the spooler (a print job being handed over, Print Settings…), the +/// Print dialog's listings return at once with the last lists this process got. +#[test] +fn listings_without_waiting_return_the_last_lists_while_the_spooler_is_busy() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Arc, mpsc}; + let asked = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&asked); + let mut s = Session::new(); + s.printer_source = Some(Arc::new(move || { + counted.fetch_add(1, Ordering::SeqCst); + vec![craft_print::Printer { name: "Office".into(), default: true, two_sided: None }] + })); + // Lists once, so there are last lists. + s.execute("file.printers", json!({})).unwrap(); + s.execute("file.print.printers", json!({})).unwrap(); + let (held_tx, held) = mpsc::channel(); + let (release, released_rx) = mpsc::channel::<()>(); + let released = Arc::new(AtomicBool::new(false)); + let holder = { + let released = Arc::clone(&released); + std::thread::spawn(move || { + with_spooler(|| { + // Nothing replaces the last lists while the lock is held. + held_tx.send((last(&LAST_PRINTERS), last(&LAST_RGB_PRINTERS))).unwrap(); + // Bounded, so a listing that waits fails the test rather than hanging it. + let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); + released.store(true, Ordering::SeqCst); + }); + }) + }; + let (kept, kept_rgb) = held.recv().unwrap(); + let before = asked.load(Ordering::SeqCst); + let listed = printers_without_waiting(&mut s); + let listed_rgb = rgb_printers_without_waiting(&s); + assert!(!released.load(Ordering::SeqCst), "the listing waited for the spooler"); + release.send(()).unwrap(); + holder.join().unwrap(); + assert_eq!(asked.load(Ordering::SeqCst), before, "a printer list was asked for while the spooler was busy"); + assert_eq!(listed, printers_answer(kept.unwrap())); + assert_eq!(listed_rgb, kept_rgb.unwrap()); +} + /// Spooling tests run in a child process: `disable_printing` is process-wide and a test above /// sets it, and CI sets `PHOTOCRAFT_NO_PRINT` for the whole shell. True in the child, which runs /// the test body; the parent starts the child and checks that it passed. diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 51f225c875..63f05df307 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -727,8 +727,9 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { let mut f = Map::new(); f.insert("__print".into(), json!(true)); f.insert("__label".into(), json!("PhotoCraft Print Settings")); - // Asked once per opening: the Printer menu lists what the spooler knows now. - let printers = app.session.execute("file.printers", json!({})).unwrap_or_default(); + // Asked once per opening: the Printer menu lists what the spooler knows now, or what it knew at + // the last listing while a print job or Print Settings… is in a printer driver. + let printers = photocraft_engine::print_cmds::printers_without_waiting(&mut app.session); f.insert("__systemPrinters".into(), printers["printers"].clone()); // The settings of the last print, also from an earlier session (#7410). if let Some(Value::Object(m)) = photocraft_engine::print_cmds::last_print(&app.session) { @@ -760,7 +761,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { f.entry(k.to_string()).or_insert(v); } // Windows: the system's printers, and the paper from the chosen printer's driver settings. - if let Ok(list) = photocraft_engine::print_cmds::rgb_printers(&app.session) { + if let Ok(list) = photocraft_engine::print_cmds::rgb_printers_without_waiting(&app.session) { f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); let known = |n: &str| list.iter().any(|p| p.name == n); if !known(&s(&f, "printer", "")) { @@ -781,17 +782,20 @@ fn driver_paper_is_wide(f: &Map) -> bool { /// The Orientation buttons: the driver settings (or the printer's own) turned portrait or /// landscape through `file.print.page`. An error stays on the dialog, with the settings left as -/// they were. +/// they were. While another thread is in a printer driver, the dialog says so and does not wait. fn turn_driver(app: &mut PhotocraftApp, f: &mut Map, landscape: bool) { let mut q = json!({"printer": s(f, "printer", ""), "orientation": if landscape { "landscape" } else { "portrait" }}); if let (Some(h), Some(o)) = (f.get("printerSettings").cloned(), q.as_object_mut()) { o.insert("printerSettings".into(), h); } - match app.session.execute("file.print.page", q) { - Ok(r) => take_turned_page(f, &r), - Err(e) => { + match photocraft_engine::print_cmds::try_with_spooler(|| app.session.execute("file.print.page", q)) { + Some(Ok(r)) => take_turned_page(f, &r), + Some(Err(e)) => { f.insert("__pageError".into(), json!(e.to_string())); } + None => { + f.insert("__pageError".into(), json!(photocraft_engine::print_cmds::SPOOLER_BUSY)); + } } } @@ -810,20 +814,28 @@ fn take_turned_page(f: &mut Map, r: &Value) { f.remove("__pageError"); } -/// Takes the paper from the printer's driver settings (Windows), as Photoshop does. -fn driver_page(f: &mut Map) { +/// Takes the paper from the printer's driver settings (Windows), as Photoshop does. While another +/// thread is in a printer driver, the dialog says so and does not wait, and the page is asked for +/// again on a later frame; then this returns false. +fn driver_page(f: &mut Map) -> bool { let printer = s(f, "printer", ""); let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); - match photocraft_engine::print_cmds::with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())) { - Ok(pg) => { + match photocraft_engine::print_cmds::try_with_spooler(|| craft_print::rgb::page(&printer, settings.as_ref())) { + Some(Ok(pg)) => { f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); f.insert("orientation".into(), json!("portrait")); f.remove("__pageError"); } - Err(e) => { + Some(Err(e)) => { f.insert("__pageError".into(), json!(e.to_string())); } + None => { + f.insert("__pageError".into(), json!(photocraft_engine::print_cmds::SPOOLER_BUSY)); + f.remove("__driverPageInitialized"); + return false; + } } + true } /// Points per unit for the Position and Size fields. @@ -931,8 +943,8 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { + match photocraft_engine::print_cmds::try_with_spooler(|| craft_print::rgb::settings_dialog(&printer, current.as_ref(), None)) { + Some(Ok(Some(dm))) => { f.insert("printerSettings".into(), json!(dm.to_hex())); driver_page(f); } - Ok(None) => {} - Err(e) => { + Some(Ok(None)) => {} + Some(Err(e)) => { f.insert("__pageError".into(), json!(e.to_string())); } + None => { + f.insert("__pageError".into(), json!(photocraft_engine::print_cmds::SPOOLER_BUSY)); + } } } }); @@ -1646,6 +1661,45 @@ mod tests { assert!(f.get("__pageError").is_some(), "{partial}"); } } + + /// While another thread is in a printer driver (a print job being handed over), the Print + /// dialog's driver calls say so at once and leave the settings as they were. + #[test] + fn driver_calls_do_not_wait_while_the_spooler_is_busy() { + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut app, _) = app(); + let (held_tx, held) = std::sync::mpsc::channel(); + let (release, released_rx) = std::sync::mpsc::channel::<()>(); + let released = Arc::new(AtomicBool::new(false)); + let holder = { + let released = Arc::clone(&released); + std::thread::spawn(move || { + photocraft_engine::print_cmds::with_spooler(|| { + held_tx.send(()).unwrap(); + // Bounded, so a call that waits fails the test rather than hanging it. + let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); + released.store(true, Ordering::SeqCst); + }); + }) + }; + held.recv().unwrap(); + let mut page = Map::new(); + page.insert("printer".into(), json!("Test printer")); + page.insert("__driverPageInitialized".into(), json!(true)); + let answered = driver_page(&mut page); + let mut turn = Map::new(); + turn.insert("printer".into(), json!("Test printer")); + turn.insert("paper".into(), json!([595.28, 841.89])); + turn_driver(&mut app, &mut turn, true); + assert!(!released.load(Ordering::SeqCst), "a driver call waited for the spooler"); + release.send(()).unwrap(); + holder.join().unwrap(); + assert!(!answered); + assert!(page.get("__driverPageInitialized").is_none(), "the page is asked for again on a later frame"); + assert_eq!(page["__pageError"], photocraft_engine::print_cmds::SPOOLER_BUSY); + assert_eq!(turn["__pageError"], photocraft_engine::print_cmds::SPOOLER_BUSY); + assert_eq!((turn.get("paper"), turn.get("printerSettings")), (Some(&json!([595.28, 841.89])), None)); + } } #[cfg(test)] From 4d25188410abb6d9fd771001204c171f6990ffd1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 09:43:50 +0200 Subject: [PATCH 27/73] Address review: add frame_stroke: None to the Group literal main gained in web_cmds tests (#6668) Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/web_cmds/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs index ce7abe927b..10cb76ade6 100644 --- a/crates/engine/src/web_cmds/tests.rs +++ b/crates/engine/src/web_cmds/tests.rs @@ -640,8 +640,10 @@ fn image_assets_never_write_one_file_twice() { let dir = tmp("asset-variant-collisions"); d.layer_mut(top).unwrap().name = "icon.png".into(); d.layer_mut(logo).unwrap().name = "Logo".into(); - d.layers - .push(Layer::new("default 50% + 200% + 200% @2x", LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }))); + d.layers.push(Layer::new( + "default 50% + 200% + 200% @2x", + LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None, frame_stroke: None }), + )); let (files, errors) = generate_assets(&d, &dir); let names: Vec<_> = files.iter().map(|p| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); assert_eq!(names, ["icon.png", "icon@2x.png"]); From 088f3d5849e20eda1e117ef7abb7faa1bab1fa12 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 09:54:34 +0200 Subject: [PATCH 28/73] Address review: only selecting the Work Path shows a hidden Work Path `work_path_shown` returned true for any row selected in the Paths panel, so clicking a saved path re-showed (and let Delete remove) the Work Path hidden by Make Selection. Only the Work Path row shows it again now. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/path_selection_tests.rs | 28 ++++++++++++++++++++++ crates/ui-egui/src/vector_ui.rs | 13 +++++++--- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/path_selection_tests.rs b/crates/ui-egui/src/path_selection_tests.rs index 592a6dc3bd..51cd2de25b 100644 --- a/crates/ui-egui/src/path_selection_tests.rs +++ b/crates/ui-egui/src/path_selection_tests.rs @@ -87,6 +87,34 @@ fn cmd_enter_while_drawing_finishes_the_path_and_loads_it() { assert!(h.state().session.active().unwrap().doc.selection.is_none()); } +#[test] +fn selecting_a_saved_path_keeps_the_hidden_work_path_hidden() { + // #6079 review: only selecting the Work Path in the Paths panel shows it again. + let mut h = harness(); + h.state_mut().run("path.set", json!({"name": "Saved", "path": rect_path(100.0, 40.0, 60.0, 50.0)})).unwrap(); + h.state_mut().ui.tool = Tool::Pen; + let p = |x: f64, y: f64| [[x, y], [x, y], [x, y]]; + h.state_mut().ui.pen = Some(PenPath { knots: vec![p(20.0, 20.0), p(120.0, 20.0), p(120.0, 80.0)], ..Default::default() }); + h.run_steps(2); + press(&mut h, Key::Enter, command()); + assert!(!crate::vector_ui::work_path_shown(h.state()), "⌘↩ hid the work path"); + panel(&mut h, 2); + let saved = h.get_by_label("Saved").rect(); + click(&mut h, egui::pos2(saved.left() + 70.0, saved.center().y), Modifiers::NONE); + assert_eq!(h.state().ui.selected_path.as_deref(), Some("Saved")); + assert!(!crate::vector_ui::work_path_shown(h.state()), "a saved path doesn't show the Work Path"); + // So Delete with the Pen doesn't delete the invisible work path either. + press(&mut h, Key::Delete, Modifiers::NONE); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "the hidden work path survives Delete"); + // Selecting the Work Path shows it; now Delete deletes it. + let work = h.get_by_label("Work Path").rect(); + click(&mut h, egui::pos2(work.left() + 70.0, work.center().y), Modifiers::NONE); + assert_eq!(h.state().ui.selected_path.as_deref(), Some("work")); + assert!(crate::vector_ui::work_path_shown(h.state()), "selecting the Work Path shows it"); + press(&mut h, Key::Delete, Modifiers::NONE); + assert!(h.state().session.active().unwrap().doc.work_path.is_none(), "{}", h.state().ui.status); +} + #[test] fn cmd_enter_loads_the_path_selected_in_the_paths_panel() { let mut h = harness(); diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 7e6fc86958..baae7d5d46 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -725,10 +725,11 @@ pub(crate) fn deselect_loaded_path(app: &mut PhotocraftApp, name: &str) { } /// Is the active document's Work Path drawn and edited on the canvas? Not after -/// [`deselect_loaded_path`] hid it, until a path is selected again in the Paths panel or the Work -/// Path changes (a new one drawn, Make Work Path, `path.set`…) (#6079). +/// [`deselect_loaded_path`] hid it, until the Work Path is selected again in the Paths panel (a +/// saved path or a layer's path doesn't show it) or it changes (a new one drawn, Make Work Path, +/// `path.set`…) (#6079). pub(crate) fn work_path_shown(app: &PhotocraftApp) -> bool { - if app.ui.selected_path.is_some() { + if app.ui.selected_path.as_deref() == Some("work") { return true; } let Some((doc, hidden)) = &app.ui.hidden_work_path else { return true }; @@ -2154,6 +2155,12 @@ mod tests { assert!(app.session.active().unwrap().doc.work_path.is_some()); assert!(app.session.active().unwrap().doc.selection.is_none()); assert_eq!(overlay_shapes(&app, &ctx), 0, "still hidden"); + // Selecting a saved path in the Paths panel doesn't show it; only the Work Path does. + let saved = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [60, 60]}, {"anchor": [90, 60]}, {"anchor": [90, 90]}]}]}); + app.run("path.set", json!({"name": "Saved", "path": saved})).unwrap(); + app.ui.selected_path = Some("Saved".into()); + assert!(!work_path_shown(&app) && overlay_shapes(&app, &ctx) == 0, "a saved path keeps the Work Path hidden"); + app.ui.selected_path = None; // Another Work Path made any other way (Make Work Path, `path.set` over the control // channel…) is a different path: it shows without being selected. let other = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [5, 5]}, {"anchor": [50, 5]}, {"anchor": [50, 50]}]}]}); From 4399b9e7d814f534bcd27dea2952745a2194767e Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 09:59:14 +0200 Subject: [PATCH 29/73] Address review: palette save picks PSB by encoded size; sign blocks after promotion Indexed/Bitmap (#4816) and Multichannel files go through `layerless_file`, which now runs `fit_psd_size` and then signs every global block for the version the file is written as (`sign_global_blocks`, shared with the layered path), so a file promoted to PSB by its size writes its 8-byte-length blocks as 8B64 (#7948). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/multichannel_map.rs | 20 ++++++---- crates/io/src/palette_map.rs | 5 ++- crates/io/src/psd_export.rs | 62 ++++++++++++++++++++++++++++--- 3 files changed, 72 insertions(+), 15 deletions(-) diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index d6f1bfa462..42c534b825 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -120,15 +120,16 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: u64) // Alpha identifiers: one u32 per channel, only while they still match the channels. let keep = |id: u16, data: &[u8]| id != ALPHA_IDENTIFIERS || data.len() == channels.len().saturating_mul(4); let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth); - let mut file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, &mut warnings); - warnings.extend(crate::psd_export::fit_psd_size(&mut file, size_limit)); + let file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings); (file, warnings) } /// A PSD without layers around `image_data`: `resources` (the mode's own) plus the paths, XMP, /// EXIF and every other imported resource `keep` accepts (except the ones that only describe /// layers and any already in `resources`), and the document-level tagged blocks. Shared by the -/// modes that have no layers in Photoshop: Multichannel, Indexed Color and Bitmap. +/// modes that have no layers in Photoshop: Multichannel, Indexed Color and Bitmap. A file past +/// `size_limit` bytes is written as PSB (see `psd_export::fit_psd_size`). +#[allow(clippy::too_many_arguments)] pub(crate) fn layerless_file( doc: &Document, header: Header, @@ -136,6 +137,7 @@ pub(crate) fn layerless_file( color_mode_data: Vec, mut resources: Vec, keep: impl Fn(u16, &[u8]) -> bool, + size_limit: u64, warnings: &mut Vec, ) -> PsdFile { resources.extend(crate::psd_export::path_resources(doc, warnings)); @@ -163,13 +165,14 @@ pub(crate) fn layerless_file( } resources.push(version_info_resource(true)); // Document-level tagged blocks (patterns, notes, ...) are valid without a layer section; a - // kept layer block would describe layers the document doesn't have. + // kept layer block would describe layers the document doesn't have. Their signatures follow + // the version the file is written as, known once its size is. let global_blocks: Vec = crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc)) .into_iter() .filter(|(_, key, _)| !matches!(key, b"Layr" | b"Lr16" | b"Lr32")) - .map(|(sig, key, data)| crate::psd_export::global_block(crate::psd_export::block_signature(sig, key, header.version), key, &data)) + .map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data)) .collect(); - PsdFile { + let mut file = PsdFile { header, color_mode_data, resources, @@ -180,5 +183,8 @@ pub(crate) fn layerless_file( layer_mask_trailing: Vec::new(), image_data, write_as_psb: false, - } + }; + warnings.extend(crate::psd_export::fit_psd_size(&mut file, size_limit)); + crate::psd_export::sign_global_blocks(&mut file); + file } diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index 4bc80d1f3c..b429a59d70 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -21,7 +21,8 @@ const CHANNEL_RESOURCES: [u16; 4] = [1006, 1045, 1053, crate::channel_map::DISPL /// opaque, or a Bitmap document; None for any other document (it is written like the others). A /// document with alpha channels or a Quick Mask is written like the others too: the importer does /// not read the extra channels of these modes back, so they would be lost. -pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFile, Vec)> { +/// A file past `size_limit` bytes is written as PSB (see `psd_export::fit_psd_size`). +pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: u64) -> Option<(PsdFile, Vec)> { if !doc.channels.is_empty() || doc.quick_mask.is_some() { return None; } @@ -63,7 +64,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> Option<(PsdFil } // An imported transparency index that no longer applies is not copied either. let keep = |id: u16, _: &[u8]| !CHANNEL_RESOURCES.contains(&id) && id != TRANSPARENCY_INDEX && id != COLOR_TABLE_COUNT; - let file = crate::multichannel_map::layerless_file(doc, header, image_data, color_mode_data, resources, keep, &mut warnings); + let file = crate::multichannel_map::layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings); Some((file, warnings)) } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 5c609487ae..f0cde7aa45 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1463,6 +1463,15 @@ pub(crate) fn fit_psd_size(file: &mut PsdFile, limit: u64) -> Option { } } +/// Signs every global block for the version `file` is written as ([`block_signature`]): run +/// after [`fit_psd_size`], which may turn a PSD into a PSB. +pub(crate) fn sign_global_blocks(file: &mut PsdFile) { + let version = file.written_version(); + for block in &mut file.global_blocks { + block.signature = block_signature(block.signature, block.key, version); + } +} + /// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { document_to_psd_sized(doc, opts, depth, ctl, PSD_MAX_FILE_SIZE) @@ -1473,7 +1482,7 @@ fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ct if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, size_limit); } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { + if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, size_limit) { return file; } let fmt = doc.pixel_format(); @@ -1713,7 +1722,7 @@ fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ct if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { continue; } - // The signature follows the final version (see `block_signature` below). + // The signature follows the final version (see `sign_global_blocks`). global_blocks.push(global_block(sig, key, &data)); } if let Some(txt2) = txt2 { @@ -1798,10 +1807,7 @@ fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ct if opts.size_limit_psb { ex.warnings.extend(fit_psd_size(&mut file, size_limit)); } - let version = file.written_version(); - for block in &mut file.global_blocks { - block.signature = block_signature(block.signature, block.key, version); - } + sign_global_blocks(&mut file); (file, ex.warnings) } @@ -2111,6 +2117,50 @@ mod tests { assert_eq!(back.decode_merged().unwrap(), PsdFile::from_bytes(&export_sized(&doc, u64::MAX).0.to_bytes().unwrap()).unwrap().decode_merged().unwrap()); } + /// Indexed Color and Bitmap (written without layers, #4816), Multichannel and RGB follow the + /// encoded-size rule, and a file turned into PSB by its size writes its global blocks with + /// 8-byte lengths as `8B64` (#7937), whatever signature they were kept with; a file that fits + /// stays a PSD with `8BIM` throughout. + #[test] + fn every_mode_promoted_by_size_signs_long_blocks_8b64() { + let white = photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0); + let mut docs = Vec::new(); + for (mode, psd_mode) in [(ColorMode::Indexed, PsdMode::Indexed), (ColorMode::Bitmap, PsdMode::Bitmap), (ColorMode::Rgb, PsdMode::Rgb)] { + let mut doc = Document::with_background("modes", photocraft_geom::Size::new(64, 64), ColorMode::Rgb, SampleType::U8, white); + doc.mode = mode; + doc.color_table = Some(photocraft_doc::ColorTable { colors: vec![[255, 255, 255], [0, 0, 0]], transparent: None }); + docs.push((doc, psd_mode)); + } + let mut multichannel = document(64, 64); + multichannel.mode = ColorMode::Multichannel; + multichannel.channels.push(photocraft_doc::AlphaChannel::new("Cyan", photocraft_raster::Surface::new(PixelFormat::GRAY8))); + docs.push((multichannel, PsdMode::Multichannel)); + for (mut doc, psd_mode) in docs { + doc.metadata.psd_global_blocks = vec![ + (*b"8BIM", *b"cinf", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8BIM", *b"pths", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), + (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), + ]; + let written = |limit| { + let (file, warnings) = export_sized(&doc, limit); + let bytes = file.to_bytes().unwrap(); + let back = PsdFile::from_bytes(&bytes).unwrap(); + let blocks = back.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>(); + (bytes.len() as u64, back, blocks, warnings) + }; + let (len, small, blocks, _) = written(u64::MAX); + assert_eq!((small.header.version, small.header.color_mode), (Version::Psd, psd_mode), "{psd_mode:?}"); + assert_eq!(blocks, vec![(*b"8BIM", *b"cinf"), (*b"8BIM", *b"pths"), (*b"8BIM", *b"FMsk"), (*b"8BIM", *b"Patt")], "{psd_mode:?}: a PSD keeps 8BIM"); + // One byte short of the encoded length: the same document is written as PSB. + let (_, big, blocks, warnings) = written(len + PSD_SAVE_HEADROOM - 1); + assert_eq!((big.header.version, big.header.color_mode), (Version::Psb, psd_mode), "{psd_mode:?}: {warnings:?}"); + assert!(warnings.iter().any(|w| w == "encoded size exceeds 2 GB; written as PSB"), "{psd_mode:?}: {warnings:?}"); + assert_eq!(blocks, vec![(*b"8B64", *b"cinf"), (*b"8B64", *b"pths"), (*b"8B64", *b"FMsk"), (*b"8BIM", *b"Patt")], "{psd_mode:?}: a PSB signs 8B64"); + assert_eq!(big.decode_merged().unwrap(), small.decode_merged().unwrap(), "{psd_mode:?}"); + } + } + #[test] fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this From c4d741c5bf466d4bede2ac050684761a79db2563 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 21 Oct 2026 01:17:12 -0700 Subject: [PATCH 30/73] Print: list the stand-in printers on the GDI route on Windows only With a printer stand-in installed, file.print.printers and the Print dialog's driver Printer menu listed its printers on every platform, while the GDI route answers Unsupported off Windows. Tests on Linux and macOS then opened the Windows Print dialog instead of the system printers and paper controls. The stand-in now answers Unsupported off Windows too, and the tests that read the driver menu expect it on Windows only. --- crates/engine/src/print_cmds.rs | 16 ++++++++++++++-- crates/engine/src/print_cmds/tests.rs | 18 +++++++++++++++--- crates/ui-egui/src/file_ui.rs | 6 +++++- crates/ui-egui/tests/custom_print_paper.rs | 11 +++++++---- 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 5d32d2eb4b..9eb8956a7d 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -73,6 +73,8 @@ pub struct Spooler { /// A stand-in for the system's printers, installed on `Session::printer_source` (tests): /// `file.printers`, `file.print.printers` and the Print dialog list these and do not ask the spooler. +/// `file.print.printers` and the dialog's driver Printer menu list them on Windows only, where the +/// GDI route is; elsewhere they answer as that route does there. pub type PrinterSource = std::sync::Arc Vec + Send + Sync>; /// Held while a thread of this process lists printers or calls into a printer driver. @@ -166,7 +168,7 @@ fn list_system_printers(s: &Session) -> Vec { /// Lists the GDI route's printers; called with the spooler lock held. fn list_rgb_printers(s: &Session) -> RgbPrinters { let list = match &s.printer_source { - Some(source) => Ok(source().into_iter().map(|p| craft_print::rgb::Printer { name: p.name, default: p.default }).collect()), + Some(source) => stand_in_rgb_printers(source, cfg!(windows)), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); craft_print::rgb::printers() @@ -176,12 +178,22 @@ fn list_rgb_printers(s: &Session) -> RgbPrinters { list } +/// The GDI route's answer from a stand-in: its printers on Windows, and `Unsupported` elsewhere, +/// as `craft_print::rgb::printers` answers there. +fn stand_in_rgb_printers(source: &PrinterSource, windows: bool) -> RgbPrinters { + if !windows { + return Err(craft_print::rgb::PrintError::Unsupported); + } + Ok(source().into_iter().map(|p| craft_print::rgb::Printer { name: p.name, default: p.default }).collect()) +} + /// The printers `craft-print` spools to, or the session's stand-in for them. fn system_printer_list(s: &Session) -> Vec { with_spooler(|| list_system_printers(s)) } -/// The printers the GDI route prints to (`craft_print::rgb`), or the session's stand-in for them. +/// The printers the GDI route prints to (`craft_print::rgb`), or on Windows the session's stand-in +/// for them. pub fn rgb_printers(s: &Session) -> RgbPrinters { with_spooler(|| list_rgb_printers(s)) } diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 3345888b8c..8be12d8902 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -211,13 +211,24 @@ fn printer_commands_answer_without_a_document_and_reject_bad_settings() { let mut s = Session::new(); s.printer_source = Some(test_printers()); let r = s.execute("file.print.printers", json!({})).unwrap(); - assert_eq!(r["supported"], true); - assert_eq!(r["printers"], json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}])); + assert_eq!(r["supported"], cfg!(windows)); + let listed = if cfg!(windows) { json!([{"name": "Studio", "default": false}, {"name": "Office", "default": true}]) } else { json!([]) }; + assert_eq!(r["printers"], listed); assert!(s.execute("file.print.page", json!({"printer": "Anything", "printerSettings": "zz"})).is_err()); let mut s = session("rgb", 8); assert!(s.execute("file.print", json!({"printer": "Anything", "printerSettings": "0102", "send": true})).is_err()); } +/// The GDI route lists a stand-in's printers only on Windows. Elsewhere it answers `Unsupported` +/// as the real route does, so the Print dialog shows the system's printers and paper controls. +#[test] +fn stand_in_printers_reach_the_gdi_route_on_windows_only() { + let source = test_printers(); + assert_eq!(stand_in_rgb_printers(&source, false), Err(craft_print::rgb::PrintError::Unsupported)); + let listed = stand_in_rgb_printers(&source, true).unwrap(); + assert_eq!(listed.iter().map(|p| (p.name.as_str(), p.default)).collect::>(), [("Studio", false), ("Office", true)]); +} + /// Synthetic driver settings: a DEVMODEW of `size` bytes plus `extra` private driver bytes, every /// byte a pattern so a stray write shows, with `dmFields` saying only the paper size is set. fn devmode(size: u16, extra: u16) -> Vec { @@ -592,7 +603,8 @@ fn printer_listings_enter_the_spooler_one_thread_at_a_time() { })); start.wait(); for _ in 0..3 { - let id = if i % 2 == 0 { "file.printers" } else { "file.print.printers" }; + // `file.print.printers` lists the stand-in on Windows only. + let id = if i % 2 == 0 || !cfg!(windows) { "file.printers" } else { "file.print.printers" }; assert_eq!(s.execute(id, json!({})).unwrap()["printers"][0]["name"], "Office"); } }) diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 63f05df307..6d954e8022 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -1540,7 +1540,11 @@ mod tests { let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); let f = &app.ui.dialog_mut(id).unwrap().fields; assert_eq!(f["__systemPrinters"], json!([{"name": "Test printer", "default": true}])); - assert_eq!((f["__printers"].clone(), f["printer"].clone()), (json!(["Test printer"]), json!("Test printer"))); + // The driver Printer menu lists the stand-in on Windows only, where the GDI route is. + assert_eq!(f.get("__printers"), cfg!(windows).then(|| json!(["Test printer"])).as_ref()); + if cfg!(windows) { + assert_eq!(f["printer"], "Test printer"); + } assert!(params(f).get("__systemPrinters").is_none()); assert!(params(f).get("__printers").is_none()); // Every test in this binary that opens Print lists the session's printers. diff --git a/crates/ui-egui/tests/custom_print_paper.rs b/crates/ui-egui/tests/custom_print_paper.rs index b65d7ce10b..120dbf3ca9 100644 --- a/crates/ui-egui/tests/custom_print_paper.rs +++ b/crates/ui-egui/tests/custom_print_paper.rs @@ -6,16 +6,19 @@ use serde_json::{Map, Value, json}; fn app() -> (PhotocraftApp, u64) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); - // Exercise PDF paper controls even when native printers are available, on every OS. Print - // lists this printer and does not ask the spooler. + // Print lists this printer and does not ask the spooler. app.session.printer_source = Some(std::sync::Arc::new(|| vec![craft_print::Printer { name: "Test native printer".into(), default: true, two_sided: None }])); app.run("file.new", json!({"width": 120, "height": 80, "name": "Custom paper"})).unwrap(); let id = open_print(&mut app); assert_no_system_listing(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; // Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog. - app.ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true)); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__printers"], json!(["Test native printer"])); + fields.insert("dryRun".into(), json!(true)); + // The driver Printer menu lists the stand-in on Windows only, where the GDI route is. + assert_eq!(fields.get("__printers"), cfg!(windows).then(|| json!(["Test native printer"])).as_ref()); + // Exercise PDF paper controls even when native printers are available, on every OS. + fields.insert("__printers".into(), json!(["Test native printer"])); (app, id) } From 02a771bf52893781e4ec6fbef8df89cf80e7b2ed Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 11:01:09 +0200 Subject: [PATCH 31/73] Address review: Color Lookup literals and pattern main gained in adjust_warnings (#6322) carry source The PSB round trip of a Photoshop-layout clrL block now also asserts the reopened lookup keeps its .cube file as source; the tables made in the test have none. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/tests/adjust_warnings.rs | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/io/tests/adjust_warnings.rs b/crates/io/tests/adjust_warnings.rs index a448aa6c1f..38ef6a1390 100644 --- a/crates/io/tests/adjust_warnings.rs +++ b/crates/io/tests/adjust_warnings.rs @@ -70,10 +70,15 @@ fn photoshop_layout_color_lookup_round_trips_through_psb() { let opts = ExportOptions { force_psb: true, ..Default::default() }; let (doc, warnings) = reopen(Adjustment::Unsupported { psd_key: "clrL".into(), raw: raw.clone() }, "x.psb", &opts); assert!(warnings.iter().all(|w| !w.contains("Teal Look")), "{warnings:?}"); - let LayerContent::Adjustment(Adjustment::ColorLookup { name, size, lut: Some(table), tetrahedral: false, dither: false }) = &doc.layers[0].content else { + let LayerContent::Adjustment(Adjustment::ColorLookup { name, size, lut: Some(table), tetrahedral: false, dither: false, source: Some(source) }) = + &doc.layers[0].content + else { panic!("{:?}", doc.layers[0].content) }; assert_eq!(name, "frost.cube"); + // The loaded `.cube` file is kept as its source, so a later save can embed it unchanged. + assert_eq!(source.format, photocraft_doc::adjust::LutFormat::Cube); + assert_eq!(source.bytes.as_slice(), b"LUT_3D_SIZE 2\n0 0 0\n0 1 1\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"); assert_eq!(*size, 2); let want: Vec = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0].into(); assert_eq!(table.as_slice(), want.as_slice()); @@ -95,18 +100,32 @@ fn photoshop_layout_color_lookup_round_trips_through_psb() { fn short_color_lookup_table_warns_on_open() { // A stored table shorter than size³×3 renders as the identity; opening must say so, naming // the layer (#1763). - let short = Adjustment::ColorLookup { name: "t.cube".into(), size: 3, lut: Some(std::sync::Arc::new(vec![0.5; 7])), tetrahedral: false, dither: false }; + let short = Adjustment::ColorLookup { + name: "t.cube".into(), + size: 3, + lut: Some(std::sync::Arc::new(vec![0.5; 7])), + tetrahedral: false, + dither: false, + source: None, + }; let (doc, warnings) = reopen(short, "x.pcraft", &ExportOptions::default()); assert!(matches!(&doc.layers[0].content, LayerContent::Adjustment(Adjustment::ColorLookup { .. })), "{:?}", doc.layers[0].content); let w: Vec<&String> = warnings.iter().filter(|w| w.contains("Teal Look")).collect(); assert_eq!(w.len(), 1, "{warnings:?}"); assert!(w[0].contains("Color Lookup") && w[0].contains("7 values") && w[0].contains("81"), "{}", w[0]); // A table long enough for its size opens without the note. - let ok = Adjustment::ColorLookup { name: "t.cube".into(), size: 2, lut: Some(std::sync::Arc::new(vec![0.5; 24])), tetrahedral: false, dither: false }; + let ok = Adjustment::ColorLookup { + name: "t.cube".into(), + size: 2, + lut: Some(std::sync::Arc::new(vec![0.5; 24])), + tetrahedral: false, + dither: false, + source: None, + }; let (_, warnings) = reopen(ok, "x.pcraft", &ExportOptions::default()); assert!(warnings.iter().all(|w| !w.contains("Teal Look")), "{warnings:?}"); // A missing table renders as the identity too. - let none = Adjustment::ColorLookup { name: "t.cube".into(), size: 2, lut: None, tetrahedral: false, dither: false }; + let none = Adjustment::ColorLookup { name: "t.cube".into(), size: 2, lut: None, tetrahedral: false, dither: false, source: None }; let (_, warnings) = reopen(none, "x.pcraft", &ExportOptions::default()); assert!(warnings.iter().any(|w| w.contains("Teal Look") && w.contains("no usable table")), "{warnings:?}"); } From 09562dc8980e50c12928bc3d25c48ae1174e5bc5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 10:12:51 +0200 Subject: [PATCH 32/73] Address review: undo restores visibility a recorded step changed; non-linear Delete at the oldest state With Make Layer Visibility Changes Undoable off, stepping through history kept every layer's current visibility, so undoing a recorded step that changed visibility (Apply Layer Comp, a snapshot, a compound) left the new visibility in place. Each history state now remembers the layers whose visibility its own step changed (History::current_visibility, set by the session when it records); Undo, Redo, History rows and non-linear Delete carry only the other layers' visibility, so only the unrecorded eye changes survive. Deleting, purging or branching keeps the lists consistent by merging them into the following step. history.deleteState is now enabled in non-linear history while the oldest state is current and later states exist, so a later state can still be deleted there. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/analysis_cmds.rs | 3 +- crates/engine/src/history_cmds.rs | 7 +- crates/engine/src/history_options_cmds.rs | 78 +++++++++++++- crates/engine/src/history_select_cmds.rs | 19 ++-- crates/engine/src/lib.rs | 35 +++++-- crates/ops/src/lib.rs | 122 +++++++++++++++++++++- 6 files changed, 244 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 92b630aa44..4c1b85e393 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -197,7 +197,8 @@ pub(crate) fn compound(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess Ok(v) => { // As in `Session::edit`: undo targets what was selected just before the step (#1356). st.history.set_current_layers(prior); - st.history.record(label, before, st.layer_target()); + st.history.record(label, before.clone(), st.layer_target()); + st.history.add_current_visibility(&crate::visibility_changes(&before, &st.doc)); st.trim_history(); st.coalesce = None; Ok(v) diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index 9e9362a626..d09cd42900 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -207,8 +207,13 @@ fn delete_snapshot(s: &mut Session, p: &Value) -> Result { Ok(json!({ "snapshot": snap.id, "snapshots": st.snapshots.len() })) } +/// A state other than the oldest exists to delete: a past or the current one, and with Allow +/// Non-Linear History a later (dimmed) one too, also while the oldest state is current. fn can_delete(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "the oldest state can't be deleted".into()) + s.active() + .filter(|d| d.history.can_undo() || (d.history.non_linear && d.history.can_redo())) + .map(|_| ()) + .ok_or_else(|| "the oldest state can't be deleted".into()) } fn has_doc(s: &Session) -> std::result::Result<(), String> { diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index bdd6e75eac..db415d7316 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -86,13 +86,15 @@ pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result< st.last_damage = Some(photocraft_geom::Rect::EMPTY); return Ok(()); } + // The step that made the current state: the layers whose visibility it changed get it back. + let changed = st.history.current_visibility().to_vec(); let (mut d, layers) = st.history.drop_current().ok_or_else(|| EngineError::Other("the history can't step back right now".into()))?; // As Undo does: Save As changes file identity outside history. if d.name != st.doc.name { std::sync::Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } if keep_visibility { - crate::carry_visibility(&st.doc, &mut d); + crate::carry_visibility(&st.doc, &mut d, &changed); } let damage = crate::layer_multi_cmds::step_damage(&d, &st.doc); st.doc = d; @@ -258,6 +260,55 @@ mod tests { assert!(red(&s, id) && !visible(&s, id), "the hide is a state of its own"); } + /// Off, only the unrecorded visibility changes carry across history: a recorded step that + /// changed visibility (Apply Layer Comp) gives it back when undone and sets it again when + /// redone, whether by Undo / Redo, a History row or deleting the current state. + #[test] + fn stepping_over_a_recorded_visibility_change_restores_it() { + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + // A comp with the layer hidden, then the eye shows it again (no state) and a fill. + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("layerComp.new", json!({"name": "Hidden"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("layerComp.apply", json!({"comp": "Hidden"})).unwrap(); + assert!(red(&s, id) && !visible(&s, id), "the comp hides the layer"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(red(&s, id) && visible(&s, id), "undoing Apply Layer Comp shows the layer again"); + // The eye hides it (no state): undoing the fill keeps that. + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(!red(&s, id) && !visible(&s, id), "the unrecorded hide carries across the fill's undo"); + s.execute("edit.redo", json!({})).unwrap(); + assert!(red(&s, id) && !visible(&s, id)); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert!(red(&s, id) && !visible(&s, id), "redoing the comp hides the layer again"); + + // History rows: New, New Layer, New Layer Comp, Fill, Apply Layer Comp. + assert_eq!(entries(&s).len(), 5); + s.execute("history.selectState", json!({"state": 2})).unwrap(); + assert!(!red(&s, id) && visible(&s, id), "jumping back over the comp shows the layer again"); + s.execute("history.selectState", json!({"state": 4})).unwrap(); + assert!(red(&s, id) && !visible(&s, id), "jumping forward over the comp hides it again"); + + // Non-linear Delete of the current state (the comp) steps back and shows the layer too. + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + s.execute("history.deleteState", json!({})).unwrap(); + assert!(red(&s, id) && visible(&s, id), "deleting the comp's state shows the layer again"); + + // Non-linear Delete of a past state: the step after it now starts from the state before + // it, so undoing that step also gives back the visibility the deleted step changed. + s.execute("layerComp.apply", json!({"comp": "Hidden"})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let comp = entries(&s).len() - 2; + s.execute("history.deleteState", json!({"state": comp})).unwrap(); + assert!(!visible(&s, id)); + s.execute("edit.undo", json!({})).unwrap(); + assert!(red(&s, id) && visible(&s, id), "back at the red fill, where the layer was shown"); + } + #[test] fn non_linear_history_keeps_later_states_and_delete_removes_only_one() { let mut s = Session::new(); @@ -301,6 +352,31 @@ mod tests { assert!(s.active().unwrap().history.non_linear); } + /// With the oldest state current, non-linear Delete is still enabled for a later (dimmed) + /// state (the History panel's trash and its drop target ask for it); linear history has + /// nothing to delete there. + #[test] + fn non_linear_delete_is_enabled_while_the_oldest_state_is_current() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + for c in ["#ff0000", "#00ff00"] { + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(!s.is_enabled("history.deleteState"), "linear: only the oldest state is left to delete"); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + assert!(s.is_enabled("history.deleteState")); + let doc = s.active().unwrap().doc.clone(); + s.execute("history.deleteState", json!({"state": 1})).unwrap(); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the document is unchanged"); + assert_eq!(st.history.redo_labels().count(), 1, "only the first fill went"); + assert!(s.execute("history.deleteState", json!({})).is_err(), "the oldest state itself stays"); + s.execute("history.deleteState", json!({"state": 1})).unwrap(); + assert!(!s.is_enabled("history.deleteState"), "nothing left but the oldest state"); + } + /// Non-linear Delete reaches a later (dimmed) state too, and deletes only it; linear history /// still refuses one past the current state. #[test] diff --git a/crates/engine/src/history_select_cmds.rs b/crates/engine/src/history_select_cmds.rs index 2b4adc21d7..5fddd9c5ca 100644 --- a/crates/engine/src/history_select_cmds.rs +++ b/crates/engine/src/history_select_cmds.rs @@ -45,8 +45,19 @@ fn select_state(s: &mut Session, p: &Value) -> Result { let mut layers = None; let mut at = past; while at != target { - let step = if target < at { st.history.undo(doc.clone()) } else { st.history.redo(doc.clone()) }; - let Some((d, l)) = step else { break }; + // History Options: visibility changes that are not history states stay as they are, + // step by step as Undo / Redo keep them, except on the layers whose visibility the step + // passed over changed. + let undoing = target < at; + let mut changed = if undoing { st.history.current_visibility().to_vec() } else { Vec::new() }; + let step = if undoing { st.history.undo(doc.clone()) } else { st.history.redo(doc.clone()) }; + let Some((mut d, l)) = step else { break }; + if keep_visibility { + if !undoing { + changed = st.history.current_visibility().to_vec(); + } + crate::carry_visibility(&doc, &mut d, &changed); + } doc = d; layers = Some(l); at = if target < at { at - 1 } else { at + 1 }; @@ -58,10 +69,6 @@ fn select_state(s: &mut Session, p: &Value) -> Result { if doc.name != start.name { std::sync::Arc::make_mut(&mut doc).name.clone_from(&start.name); } - // Visibility changes that are not history states stay as they are (History Options). - if keep_visibility { - crate::carry_visibility(&start, &mut doc); - } let damage = crate::layer_multi_cmds::step_damage(&start, &doc); st.doc = doc; crate::restore_target(st, layers); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d4f986844a..c1f900ff04 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -864,11 +864,13 @@ impl Session { st.coalesce = None; } else if key.is_none() || st.coalesce != key || !st.history.can_undo() { st.history.set_current_layers(prior); - st.history.record(label, before, layers); + st.history.record(label, before.clone(), layers); + st.history.add_current_visibility(&visibility_changes(&before, &st.doc)); st.trim_history(); st.coalesce = key; } else { st.history.set_current_layers(layers); + st.history.add_current_visibility(&visibility_changes(&before, &st.doc)); st.coalesce = key; } st.revision += 1; @@ -952,6 +954,8 @@ impl Session { let keep_visibility = !self.visibility_undoable(); let Some(st) = self.active_mut() else { return false }; st.coalesce = None; + // The step being undone: the layers whose visibility it changed get it back. + let changed = st.history.current_visibility().to_vec(); match st.history.undo(st.doc.clone()) { Some((mut d, layers)) => { // Save As changes file identity outside history, just like the saved path. @@ -959,7 +963,7 @@ impl Session { Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } if keep_visibility { - carry_visibility(&st.doc, &mut d); + carry_visibility(&st.doc, &mut d, &changed); } // Pixels this step can have touched, so the canvas recomposites only that // (it recomposited everything before). @@ -987,7 +991,9 @@ impl Session { Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } if keep_visibility { - carry_visibility(&st.doc, &mut d); + // The step being redone sets the visibility it changed again. + let changed = st.history.current_visibility().to_vec(); + carry_visibility(&st.doc, &mut d, &changed); } let damage = layer_multi_cmds::step_damage(&st.doc, &d); st.doc = d; @@ -1035,12 +1041,18 @@ impl Session { /// History Options › Make Layer Visibility Changes Undoable off: showing or hiding a layer is not /// a history state, so stepping through history must not bring the old visibility back either /// (history states hold whole documents). Gives every layer of `to` that `from` also has the -/// visibility it has in `from`; layers only one of them has keep theirs. Copies `to` only when -/// something differs. -pub(crate) fn carry_visibility(from: &Document, to: &mut Arc) { +/// visibility it has in `from`, except the `stepped` layers: a recorded step between the two +/// states changed their visibility (Apply Layer Comp, a snapshot, a visibility change recorded +/// while the option was on), so they keep the visibility `to` holds. Layers only one of them has +/// keep theirs. Copies `to` only when something differs. +pub(crate) fn carry_visibility(from: &Document, to: &mut Arc, stepped: &[LayerId]) { let visible: std::collections::HashMap = from.walk().into_iter().map(|(_, _, l)| (l.id, l.visible)).collect(); - let changes: Vec<(LayerId, bool)> = - to.walk().into_iter().filter_map(|(_, _, l)| visible.get(&l.id).filter(|v| **v != l.visible).map(|v| (l.id, *v))).collect(); + let changes: Vec<(LayerId, bool)> = to + .walk() + .into_iter() + .filter(|(_, _, l)| !stepped.contains(&l.id)) + .filter_map(|(_, _, l)| visible.get(&l.id).filter(|v| **v != l.visible).map(|v| (l.id, *v))) + .collect(); if changes.is_empty() { return; } @@ -1052,6 +1064,13 @@ pub(crate) fn carry_visibility(from: &Document, to: &mut Arc) { } } +/// The layers (in both documents) whose visibility differs between `before` and `after`: what a +/// recorded step changed, for [`photocraft_ops::History::add_current_visibility`]. +pub(crate) fn visibility_changes(before: &Document, after: &Document) -> Vec { + let visible: std::collections::HashMap = before.walk().into_iter().map(|(_, _, l)| (l.id, l.visible)).collect(); + after.walk().into_iter().filter(|(_, _, l)| visible.get(&l.id).is_some_and(|v| *v != l.visible)).map(|(_, _, l)| l.id).collect() +} + /// Undo / redo: target the layers the restored state targeted, as far as they still exist. fn restore_target(st: &mut DocState, layers: LayerTarget) { // Deselect Layers is a valid history target, not a missing layer to replace with the top diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index c4da888e5a..0b3e7f9151 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -33,6 +33,9 @@ pub struct HistoryState { pub doc: Arc, /// The layers targeted when this state was created. pub layers: LayerTarget, + /// The layers whose visibility the step that created this state changed, as stepping to this + /// state from the one before it in the list must apply it; see [`History::current_visibility`]. + pub visibility: Vec, } #[derive(Clone, Debug)] @@ -50,6 +53,8 @@ pub struct History { current_label: String, /// The layers targeted when the current document was created (opened or edited). current_layers: LayerTarget, + /// [`HistoryState::visibility`] of the current state. + current_visibility: Vec, /// History Options › Allow Non-Linear History: a step recorded while later states exist /// (after stepping back) keeps them and goes to the end of the list, instead of discarding /// them; see [`History::record`] and [`History::remove`]. @@ -77,6 +82,7 @@ impl History { max_bytes: 0, current_label: "Open".into(), current_layers: LayerTarget::default(), + current_visibility: Vec::new(), non_linear: false, last_moved: None, } @@ -98,12 +104,16 @@ impl History { } let prev_label = std::mem::replace(&mut self.current_label, label.into()); let prev_layers = std::mem::replace(&mut self.current_layers, layers); - self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers }); + let prev_visibility = std::mem::take(&mut self.current_visibility); + self.undo.push_back(HistoryState { label: prev_label, doc: before, layers: prev_layers, visibility: prev_visibility }); let mut moved = 0; if self.non_linear { // `redo` holds the next state last; the list order is oldest first. Their tiles stay // counted: they only move from the redo side to the undo side. while let Some(state) = self.redo.pop() { + // The new step follows the last of them in the list but was made from `before`: + // stepping back to them walks back over their steps. + merge_ids(&mut self.current_visibility, &state.visibility); self.undo.push_back(state); moved += 1; } @@ -143,6 +153,21 @@ impl History { self.current_layers = layers; } + /// The layers whose visibility the step that produced the current document changed, as the + /// session reported them with [`History::add_current_visibility`]. With History Options › + /// Make Layer Visibility Changes Undoable off, showing or hiding a layer is not a step, so + /// stepping through history keeps every other layer's visibility as it is; these layers take + /// the visibility of the state stepped to, since a recorded step changed them. + pub fn current_visibility(&self) -> &[LayerId] { + &self.current_visibility + } + + /// Note layers whose visibility the current step changed (after [`History::record`], and + /// again when a later change coalesces into the step). + pub fn add_current_visibility(&mut self, ids: &[LayerId]) { + merge_ids(&mut self.current_visibility, ids); + } + /// Undo: `current` becomes redoable; returns the document to make current and the layers it /// targeted when it was created. pub fn undo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { @@ -154,7 +179,8 @@ impl History { } let label = std::mem::replace(&mut self.current_label, prev.label); let layers = std::mem::replace(&mut self.current_layers, prev.layers.clone()); - self.redo.push(HistoryState { label, doc: current, layers }); + let visibility = std::mem::replace(&mut self.current_visibility, prev.visibility); + self.redo.push(HistoryState { label, doc: current, layers, visibility }); Some((prev.doc, prev.layers)) } @@ -168,7 +194,8 @@ impl History { } let label = std::mem::replace(&mut self.current_label, next.label); let layers = std::mem::replace(&mut self.current_layers, next.layers.clone()); - self.undo.push_back(HistoryState { label, doc: current, layers }); + let visibility = std::mem::replace(&mut self.current_visibility, next.visibility); + self.undo.push_back(HistoryState { label, doc: current, layers, visibility }); Some((next.doc, next.layers)) } @@ -202,6 +229,8 @@ impl History { if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } + // The current step now starts where the purged one did. + merge_ids(&mut self.current_visibility, &state.visibility); true } @@ -219,6 +248,11 @@ impl History { if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } + // The state after it now follows the one before it. + match self.undo.get_mut(i) { + Some(next) => merge_ids(&mut next.visibility, &state.visibility), + None => merge_ids(&mut self.current_visibility, &state.visibility), + } true } @@ -232,6 +266,11 @@ impl History { if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } + // The state after it in the list (the one before it in `redo`) now follows the state + // before it. + if let Some(next) = k.checked_sub(1).and_then(|n| self.redo.get_mut(n)) { + merge_ids(&mut next.visibility, &state.visibility); + } true } @@ -246,6 +285,11 @@ impl History { } self.current_label = prev.label; self.current_layers = prev.layers.clone(); + let dropped = std::mem::replace(&mut self.current_visibility, prev.visibility); + // The next later state now follows `prev`. + if let Some(next) = self.redo.last_mut() { + merge_ids(&mut next.visibility, &dropped); + } Some((prev.doc, prev.layers)) } @@ -273,6 +317,7 @@ impl History { } self.current_label = prev.label; self.current_layers = prev.layers.clone(); + self.current_visibility = prev.visibility; Some((prev.doc, prev.layers)) } @@ -299,6 +344,7 @@ impl History { pub fn clear(&mut self) { self.last_moved = None; + self.current_visibility.clear(); self.undo.clear(); self.redo.clear(); self.tiles = None; @@ -405,6 +451,15 @@ impl History { } } +/// Add the ids of `from` that `into` lacks. +fn merge_ids(into: &mut Vec, from: &[LayerId]) { + for id in from { + if !into.contains(id) { + into.push(*id); + } + } +} + /// Bytes of the pixel tiles of `doc` (layers, masks, fill caches, smart filter masks, alpha channels, selection) not already in `seen`. fn tile_bytes(doc: &Document, seen: &mut HashSet) -> usize { let mut n = 0usize; @@ -617,6 +672,67 @@ mod tests { assert_counter(&h, &c); } + /// Each state keeps the layers whose visibility its own step changed; when a state goes + /// (Purge, a non-linear Delete) or a step is appended after the kept later states, the step + /// that now follows covers the changes of the steps it now spans. + #[test] + fn step_visibility_follows_steps_and_spans_removed_ones() { + let vis = |h: &History| { + let mut v: Vec = h.current_visibility().iter().map(|l| l.0).collect(); + v.sort_unstable(); + v + }; + // Open, then steps A, B, C, D changing layers 1, 2, 3, 4. + let steps = |n: usize, non_linear: bool| { + let mut h = History { non_linear, ..History::default() }; + let mut cur = Arc::new(base()); + for (i, label) in ["A", "B", "C", "D"].into_iter().take(n).enumerate() { + edit(&mut h, &mut cur, label, |d| d.name = label.to_lowercase()); + h.add_current_visibility(&[LayerId(i as u64 + 1)]); + } + (h, cur) + }; + let (mut h, cur) = steps(3, false); + assert_eq!(vis(&h), [3]); + let (cur, _) = h.undo(cur).unwrap(); + assert_eq!(vis(&h), [2]); + h.redo(cur).unwrap(); + assert_eq!(vis(&h), [3]); + // Purge: C now starts from A. + h.purge_last(); + assert_eq!(vis(&h), [2, 3]); + // Non-linear Delete of B (between A and C): C now follows A. + let (mut h, cur) = steps(4, true); + assert!(h.remove(2)); + h.undo(cur).unwrap(); + assert_eq!(vis(&h), [2, 3]); + // Of the later B (A current): C follows A. + let (mut h, mut cur) = steps(3, true); + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + assert!(h.remove_later(0)); + h.redo(cur).unwrap(); + assert_eq!(vis(&h), [2, 3]); + // Of the current B (C later): A is current, C follows it. + let (mut h, cur) = steps(3, true); + h.undo(cur).unwrap(); + let cur = h.drop_current().unwrap().0; + assert_eq!(vis(&h), [1]); + h.redo(cur).unwrap(); + assert_eq!(vis(&h), [2, 3]); + // A step after the kept later states B and C (made from A) follows C in the list. + let (mut h, mut cur) = steps(3, true); + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + h.add_current_visibility(&[LayerId(4)]); + assert_eq!(vis(&h), [2, 3, 4]); + h.rollback().unwrap(); + assert_eq!(vis(&h), [1], "rollback restores A's"); + h.clear(); + assert_eq!(vis(&h), Vec::::new()); + } + #[test] fn rollback_takes_the_last_record_back_exactly_in_both_modes() { // Non-linear, with redo states: the moved states go back to the redo side and the From 28c195b85685b22df12f9df08e1bf5ec5efc3011 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 12:15:26 +0200 Subject: [PATCH 33/73] Address CodeRabbit review: clean document after non-linear Delete, redo-row drag label Deleting a past or later state in non-linear history leaves the document unchanged, so a saved document now stays clean (view-only revision bump, as select_layer and channel eye toggles do). Dragging a later (dimmed) History row now shows its label at the pointer instead of an empty ghost. Adds a test for undoing a mixed visible + opacity layer.setProps with visibility changes not undoable. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/history_options_cmds.rs | 58 ++++++++++++++++++- .../ui-egui/src/history_panel_select_tests.rs | 38 ++++++++++++ crates/ui-egui/src/panels.rs | 3 +- 3 files changed, 97 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index db415d7316..c02c4660ca 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -81,8 +81,14 @@ pub(crate) fn delete_state(s: &mut Session, i: usize, current: usize) -> Result< if !removed { return Err(EngineError::Other(format!("state {i} is not held"))); } - // The document is unchanged, but the History panel's rows are not. + // The document is unchanged, but the History panel's rows are not: a view-only change + // that keeps a clean document clean. + let clean = st.saved_revision == st.revision; st.revision += 1; + st.view_revision += 1; + if clean { + st.saved_revision = st.revision; + } st.last_damage = Some(photocraft_geom::Rect::EMPTY); return Ok(()); } @@ -377,6 +383,56 @@ mod tests { assert!(!s.is_enabled("history.deleteState"), "nothing left but the oldest state"); } + /// Non-linear Delete of a past or later state leaves the document as it is, so a saved + /// (clean) document stays clean; deleting the current state steps back and modifies it. + #[test] + fn non_linear_delete_of_another_state_keeps_a_clean_document_clean() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + for c in ["#ff0000", "#00ff00", "#0000ff", "#808080"] { + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("edit.undo", json!({})).unwrap(); + // States: New, Fill 1-3 (3 current), the dimmed Fill 4. As if just saved. + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let rev = st.revision; + s.execute("history.deleteState", json!({"state": 1})).unwrap(); + let st = s.active().unwrap(); + assert!(!st.is_dirty(), "deleting a past state left the saved document unmodified"); + assert!(st.revision > rev, "the History panel still sees the change"); + s.execute("history.deleteState", json!({"state": 3})).unwrap(); + assert!(!s.active().unwrap().is_dirty(), "deleting a later state left it unmodified too"); + assert_eq!(s.active().unwrap().history.redo_labels().count(), 0); + // A modified document stays modified. + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + s.execute("history.deleteState", json!({"state": 1})).unwrap(); + assert!(s.active().unwrap().is_dirty()); + // The current state: the document steps back, which is a change. + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + s.execute("history.deleteState", json!({})).unwrap(); + assert!(s.active().unwrap().is_dirty()); + } + + /// With the option off, a recorded step that changes visibility along with other properties + /// (layer.setProps visible + opacity is one Layer Properties state) is undone and redone as a + /// whole: the carried-over visibility skips the layers the step itself changed. + #[test] + fn undoing_a_mixed_visibility_and_opacity_change_undoes_both() { + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + let n = entries(&s).len(); + s.execute("layer.setProps", json!({"layer": id, "visible": false, "opacity": 0.5})).unwrap(); + assert_eq!(entries(&s).len(), n + 1, "the mixed change is a state"); + let opacity = |s: &Session| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().opacity; + s.execute("edit.undo", json!({})).unwrap(); + assert!(visible(&s, id) && (opacity(&s) - 1.0).abs() < 1e-6, "undo shows the layer again and restores its opacity"); + s.execute("edit.redo", json!({})).unwrap(); + assert!(!visible(&s, id) && (opacity(&s) - 0.5).abs() < 1e-6, "redo hides it again"); + } + /// Non-linear Delete reaches a later (dimmed) state too, and deletes only it; linear history /// still refuses one past the current state. #[test] diff --git a/crates/ui-egui/src/history_panel_select_tests.rs b/crates/ui-egui/src/history_panel_select_tests.rs index 92c458e37f..0a0cd6f3c5 100644 --- a/crates/ui-egui/src/history_panel_select_tests.rs +++ b/crates/ui-egui/src/history_panel_select_tests.rs @@ -58,3 +58,41 @@ fn clicking_a_state_jumps_there_with_one_command() { h.run_steps(2); assert_eq!(state(&h), (4, 0, rev + 2)); } + +/// The ghost label that follows a History row being dragged to the trash (the text painted at +/// the pointer, `layer_transfer::ghost`), if one is drawn. +fn ghost_label(h: &Harness<'_, PhotocraftApp>, p: egui::Pos2) -> Option { + let at = p + vec2(20.0, -6.0); + h.output().shapes.iter().find_map(|c| match &c.shape { + egui::Shape::Text(t) if (t.pos - at).length() < 1.0 => Some(t.galley.job.text.clone()), + _ => None, + }) +} + +/// Allow Non-Linear History lets a later (dimmed) state be dragged onto the trash: its row's +/// label follows the pointer, as a past state's does. +#[test] +fn dragging_a_later_state_shows_its_label_at_the_pointer() { + let mut h = harness(); + h.state_mut().run("history.options", json!({"allowNonLinearHistory": true})).unwrap(); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(2); + // Rows: Open, New Layer, Fill, New Layer (current), the dimmed Fill. + for (label, row) in [("New Layer", 1), ("Fill", 1)] { + let from = h.get_all_by_label(label).nth(row).expect("the row").rect().center(); + let to = from + vec2(-60.0, 40.0); + h.hover_at(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 i in 1..=4 { + h.hover_at(from + (to - from) * (i as f32 / 4.0)); + h.run_steps(1); + } + assert_eq!(ghost_label(&h, to).as_deref(), Some(label), "the dragged {label} row's label follows the pointer"); + // Released off the trash: nothing is deleted. + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + } + assert_eq!(h.state().session.active().unwrap().history.entries().len() + h.state().session.active().unwrap().history.redo_labels().count(), 5); +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index e4876e7045..749bab24ce 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3421,7 +3421,8 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { { let label = match drag { HistoryDrag::Snapshot(id) => app.session.active().and_then(|st| st.snapshots.iter().find(|s| s.id == id)).map(|s| s.name.clone()), - HistoryDrag::State(i) => entries.get(i).cloned(), + // Rows number the past states, then the later (dimmed) ones a non-linear drag can lift. + HistoryDrag::State(i) => entries.get(i).or_else(|| i.checked_sub(entries.len()).and_then(|j| redo.get(j))).cloned(), }; crate::layer_transfer::ghost(&ctx, p, &label.unwrap_or_default()); } From 3ec2590687bff4d0a3ff25becca9650dbc4b92f1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 12:16:28 +0200 Subject: [PATCH 34/73] Address CodeRabbit review: report out-of-range stylize/pixelate numbers on save pi_in clamped a Trace Contour level or Crystallize/Pointillize cell size outside Photoshop's range and replaced a non-number with the default, so the PSD held a different filter with no warning. It now errors like enum_out does; only a missing key takes the default. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/smart_map.rs | 43 ++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 73861e2123..900eb45e16 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -622,9 +622,18 @@ fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str Ok(enumv(type_id, psd)) } -/// `key` rounded to a `long` in `lo..=hi`. -fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { - Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) +/// `key` (`default` when absent) rounded to a `long`; a value that is not a number, or rounds +/// outside `lo..=hi`, is an error rather than a different filter written in its place. +fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { + let v = match p.get(key) { + None => default, + Some(v) => v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| format!("`{key}` is not a number"))?, + } + .round(); + if !(f64::from(lo)..=f64::from(hi)).contains(&v) { + return Err(format!("{key} {v} is outside {lo}..={hi}")); + } + Ok(Value::Integer(v as i32)) } /// The `Fltr` descriptor of a modelled filter (`None` = written without options). @@ -650,9 +659,9 @@ fn fltr_for(k: &Known, p: &J) -> Result, String> { "Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)), // Photoshop stores no random seed for these: `seed` is ours only and is not written. "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), - "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), - "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), - "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), + "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)?).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), + "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)?), + "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)?), "Lvls" => d.with("Adjs", adjustments(p, false)?), "Crvs" => d.with("Adjs", adjustments(p, true)?), "adaptCorrect" => { @@ -1340,7 +1349,7 @@ mod tests { fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) ); - // Defaults and out-of-range values are written in Photoshop's ranges. + // Defaults, range ends and values that round into the range are written. assert_eq!( fltr("filter.stylize.traceContour", json!({})), Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) @@ -1348,17 +1357,21 @@ mod tests { assert_eq!(fltr("filter.pixelate.crystallize", json!({})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))); assert_eq!(fltr("filter.pixelate.pointillize", json!({})), Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5))))); assert_eq!( - fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), + fltr("filter.pixelate.crystallize", json!({"cellSize": 300})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(300)))) ); assert_eq!( - fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), - Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5)))) + fltr("filter.pixelate.pointillize", json!({"cellSize": 2.6})), + Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(3)))) ); assert_eq!( - fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), + fltr("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})), Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(0)).with("Edg ", enumv("CntE", "Upr ")))) ); + assert_eq!( + fltr("filter.stylize.traceContour", json!({"level": 255.4})), + Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(255)).with("Edg ", enumv("CntE", "Lwr ")))) + ); } #[test] @@ -1408,6 +1421,14 @@ mod tests { ("filter.stylize.traceContour", json!({"edge": "middle"})), ("filter.pixelate.pointillize", json!({"background": "teal"})), ("filter.pixelate.pointillize", json!({"background": [1.0]})), + // Numbers outside Photoshop's ranges, or not numbers: not clamped or replaced. + ("filter.pixelate.crystallize", json!({"cellSize": 1e9})), + ("filter.pixelate.crystallize", json!({"cellSize": 2.4})), + ("filter.pixelate.pointillize", json!({"cellSize": "big"})), + ("filter.pixelate.pointillize", json!({"cellSize": null})), + ("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), + ("filter.stylize.traceContour", json!({"level": 255.5})), + ("filter.stylize.traceContour", json!({"level": [128]})), ] { assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); } From c0007ed02d673c83b1ad31ece7baa02b488cc33d Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 12:24:36 +0200 Subject: [PATCH 35/73] Address CodeRabbit review: frame stroke bounds from the compiled stroke A mitered corner reaches up to miter_limit widths past the path, past the path bounds grown by the width; take the bounds from the compiled stroke. An empty frame's effects now count its stroke too, as layer_bounds and composite_bounds already did. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/lib.rs | 35 +++++++++++++++++++------------- crates/compose/src/tests.rs | 40 +++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 14 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 61e779bd25..f58c678b82 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1023,9 +1023,13 @@ pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { } /// Where a Photoshop Frame's stroke ([`shape_split::frame_shape`]) draws, within `canvas`; empty -/// for other layers. +/// for other layers. Taken from the compiled stroke the renderer draws, not the path grown by the +/// stroke width: a mitered corner reaches up to `miter_limit` widths past the path, and a frame +/// has no pixels of its own that would cover it. fn frame_stroke_bounds(layer: &Layer, canvas: Rect) -> Rect { - shape_split::frame_shape(layer).and_then(|sh| shape_bounds(&sh)).map_or(Rect::EMPTY, |r| r.intersect(&canvas)) + shape_split::frame_shape(layer) + .and_then(|sh| photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, canvas).bounds()) + .map_or(Rect::EMPTY, |r| r.intersect(&canvas)) } /// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's @@ -1033,18 +1037,21 @@ fn frame_stroke_bounds(layer: &Layer, canvas: Rect) -> Rect { /// shadow and must not be cut off at the child's pixels, #3274). pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; - let b = effect_source_bounds(c, canvas); - let b = if b.is_empty() { b } else { b.inflate(m) }; - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), + // A Frame's stroke is part of the group's content its effects are built from. + LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => { + g.children.iter().filter(|c| c.visible).fold(frame_stroke_bounds(layer, canvas), |acc, c| { + let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; + let b = effect_source_bounds(c, canvas); + let b = if b.is_empty() { b } else { b.inflate(m) }; + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }) + } _ => layer_bounds(layer, canvas), } } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 99823457fa..3e1f9628a2 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1176,6 +1176,46 @@ fn group_effects_reach_past_children_effects() { assert!(close4(px(&d, 24, 43), [1.0; 4]), "nothing past the shadow: {:?}", px(&d, 24, 43)); } +/// An empty Photoshop Frame with an outside stroke along `points` (#4381). +fn stroked_frame(points: &[(f64, f64)], width: f32) -> Layer { + use photocraft_doc::vector::{Path, ShapeStroke, StrokeAlign, Subpath, VectorMask}; + let mut l = Layer::group("Frame 1", vec![]); + l.vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::polygon(points)]))); + if let LayerContent::Group(g) = &mut l.content { + g.frame_stroke = Some(ShapeStroke { width, align: StrokeAlign::Outside, paint: Fill::Solid(Color::rgb(0.0, 0.0, 1.0)), ..Default::default() }); + } + l +} + +#[test] +fn frame_stroke_bounds_hold_its_mitered_corners() { + // A flat triangle's sharp corners miter far past the path (Photoshop's miter limit is 100): + // more than the stroke width, which is all the path's bounds grow by. + let canvas = Rect::new(0, 0, 64, 64); + let frame = stroked_frame(&[(20.0, 32.0), (44.0, 32.0), (32.0, 29.0)], 2.0); + let drawn = crate::bounds::content_bounds(&shape_split::frame_stroke(&frame, canvas, SampleType::U8).unwrap()); + assert!(drawn.x0 < 20 - 2 && drawn.x1 > 44 + 2, "the miters reach past the width: {drawn:?}"); + for b in [layer_bounds(&frame, canvas), composite_bounds(&frame, canvas).unwrap(), effect_source_bounds(&frame, canvas)] { + assert_eq!(b.union(&drawn), b, "{b:?} holds the stroke {drawn:?}"); + } +} + +#[test] +fn an_empty_frames_effects_follow_its_stroke() { + // No children: the frame's drop shadow is shaped by its stroke alone. + let mut d = doc_white(48, 48); + let mut frame = stroked_frame(&[(14.0, 14.0), (34.0, 14.0), (34.0, 34.0), (14.0, 34.0)], 4.0); + frame.effects.items = vec![Effect::DropShadow(shadow(3.0, 90.0))]; + d.layers.push(frame); + let canvas = d.bounds(); + let drawn = crate::bounds::content_bounds(&shape_split::frame_stroke(&d.layers[1], canvas, SampleType::U8).unwrap()); + let b = effect_source_bounds(&d.layers[1], canvas); + assert!(!drawn.is_empty() && b.union(&drawn) == b, "{b:?} holds the stroke {drawn:?}"); + assert!(close4(px(&d, 24, 36), [0.0, 0.0, 1.0, 1.0]), "stroke below the frame: {:?}", px(&d, 24, 36)); + assert!(close4(px(&d, 24, 39), [0.0, 0.0, 0.0, 1.0]), "shadow below the stroke: {:?}", px(&d, 24, 39)); + assert!(close4(px(&d, 24, 24), [1.0; 4]), "the frame's inside is empty: {:?}", px(&d, 24, 24)); +} + #[test] fn drop_shadow_uses_global_light_and_knockout() { let mut d = fx_doc(vec![Effect::DropShadow(Shadow { use_global_light: true, ..shadow(5.0, 0.0) })]); From 367981bee6bf29c3d296c8b55bb4d676dd7b725b Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 13:23:17 +0200 Subject: [PATCH 36/73] Address CodeRabbit review: test that a clipped knockout keeps the base alpha A Transparency Shapes Layer off base of the special eight under a clipped shallow or deep knockout with a feathered vector mask: the knockout stops at the base's own content, so the alpha the blend reads as Fill is the base's. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/advanced_tests.rs | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index 601912901c..9f43e66c57 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -617,3 +617,40 @@ fn transparency_shapes_off_ignores_masks_and_reaches_groups() { check(&d, 9, 4, px([148, 151, 150], 1.0), "group, alpha 70 %"); } } + +/// A clipped knockout in a Transparency Shapes Layer off base of the special eight: the knockout +/// stops at the base's own content (Blend Clipped Layers as Group), so it gives back the base's +/// colour without touching its alpha, and the base's transparency still blends as Fill under a +/// feathered vector mask. Where the fill-0 knocker covers an earlier clipped layer the composite +/// is the base's alone. +#[test] +fn transparency_shapes_off_keeps_the_base_alpha_under_a_clipped_knockout() { + let square = photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polygon(&[(2.0, 1.0), (10.0, 1.0), (10.0, 7.0), (2.0, 7.0)])]); + for depth in DEPTHS { + for k in [Knockout::Shallow, Knockout::Deep] { + let mut d = Document::with_background("t", Size::new(12, 8), ColorMode::Rgb, depth, Color::rgb(90.0 / 255.0, 110.0 / 255.0, 130.0 / 255.0)); + let mut base = solid(&d, "base", Rect::new(0, 0, 3, 8), [0.78, 0.59, 0.31, 0.3]); + base.surface_mut().unwrap().fill_rect(Rect::new(3, 0, 12, 8), &photocraft_raster::from_rgba(&d.pixel_format(), [0.78, 0.59, 0.31, 0.7])); + base.blend = BlendMode::ColorDodge; + base.opacity = 0.53; + base.advanced.transparency_shapes = false; + base.vector_mask = Some(photocraft_doc::vector::VectorMask { feather: 1.5, ..photocraft_doc::vector::VectorMask::new(square.clone()) }); + d.layers.push(base); + let alone = render(&d, d.bounds()).px; + let mut red = solid(&d, "red", full(&d), [1.0, 0.0, 0.0, 0.5]); + red.clipped = true; + let mut knock = knocker(&d, k); + knock.clipped = true; + d.layers.extend([red, knock]); + let got = render(&d, d.bounds()).px; + let what = format!("{k:?} ({depth:?})"); + for (i, (g, a)) in got.iter().zip(&alone).enumerate() { + if i % 12 < 6 { + assert!(close(*g, *a), "{what}: knocked out at {i}: {g:?}, the base alone {a:?}"); + } + } + assert!(!close(got[6 * 12 + 8], alone[6 * 12 + 8]), "{what}: the red shows outside the knocker"); + check(&d, 4, 3, alone[3 * 12 + 4], &what); + } + } +} From e63eb82ce086891e3d5f77e83d743339475513cf Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 13:32:55 +0200 Subject: [PATCH 37/73] Session::rollback keeps unrecorded visibility, as Undo does With Make Layer Visibility Changes Undoable off, taking a step back exactly (a cancelled Free Transform of a made layer, an abandoned Alt-drag copy, a failed compound command) brought back the visibility from before the step; only the fallback through Undo kept it. Carry it as Undo and Redo do. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/history_options_cmds.rs | 70 +++++++++++++++++++++++ crates/engine/src/lib.rs | 7 +++ 2 files changed, 77 insertions(+) diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index c02c4660ca..bf9e50a511 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -463,4 +463,74 @@ mod tests { let px = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(1, 1); assert!(px[2] > 0.5 && px[1] < 0.5, "redo reaches the blue fill: {px:?}"); } + + /// Off, taking a step back with `Session::rollback` (a cancelled Free Transform of a made + /// layer, an abandoned Alt-drag copy, a compound command whose later part failed) keeps the + /// unrecorded visibility as Undo does, and gives back the visibility the step itself changed, + /// whether it takes the step back exactly, falls back to Undo or lands on the oldest state. + #[test] + fn rollback_keeps_unrecorded_visibility() { + // Exactly: the fill is taken back, the eye's hide stays. + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert!(s.rollback()); + assert!(!red(&s, id), "the fill is taken back"); + assert!(!visible(&s, id), "the unrecorded hide stays"); + assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); + + // Landing on the oldest state (the New Layer step taken back): the hidden background stays + // hidden. + let (mut s, _) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + let bg = s.active().unwrap().doc.layers[0].id.0; + s.execute("layer.setProps", json!({"layer": bg, "visible": false})).unwrap(); + assert!(s.rollback()); + assert_eq!(s.active().unwrap().doc.layers.len(), 1, "the new layer is taken back"); + assert!(!visible(&s, bg), "the unrecorded hide stays on the oldest state"); + assert!(!s.rollback(), "nothing left to take back"); + assert!(!visible(&s, bg)); + + // A step that changed visibility (Apply Layer Comp) gives it back. + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + s.execute("layerComp.new", json!({"name": "Hidden"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap(); + s.execute("layerComp.apply", json!({"comp": "Hidden"})).unwrap(); + assert!(!visible(&s, id)); + assert!(s.rollback()); + assert!(visible(&s, id), "taking back Apply Layer Comp shows the layer again"); + + // Falling back to Undo (the history changed since the fill: undo, redo). + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert!(s.rollback()); + assert!(!red(&s, id) && !visible(&s, id), "the fallback Undo keeps the hide too"); + assert!(!s.active().unwrap().history.can_redo()); + + // Non-linear: a step recorded after stepping back, taken back exactly, keeps the hide and + // gives the later state back to redo. + let (mut s, id) = doc(); + s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false, "allowNonLinearHistory": true})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert!(s.rollback()); + assert!(!red(&s, id) && !visible(&s, id), "back before the invert, still hidden"); + assert!(s.active().unwrap().history.can_redo(), "the fill is redoable again"); + + // On (the default) the eye records a state of its own, which a rollback takes back. + let (mut s, id) = doc(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + assert!(s.rollback()); + assert!(red(&s, id) && visible(&s, id), "the hide is taken back, the fill stays"); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1f900ff04..4548a3fe88 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1017,8 +1017,12 @@ impl Session { if self.active_job().is_some() { return false; } + let keep_visibility = !self.visibility_undoable(); let Some(st) = self.active_mut() else { return false }; st.coalesce = None; + // The step taken back (and the later states it moved, in non-linear history): the layers + // whose visibility it changed get it back, the unrecorded changes stay, as for Undo. + let changed = st.history.current_visibility().to_vec(); let Some((mut d, layers)) = st.history.rollback() else { let undone = self.undo(); if undone && let Some(st) = self.active_mut() { @@ -1029,6 +1033,9 @@ impl Session { if d.name != st.doc.name { Arc::make_mut(&mut d).name.clone_from(&st.doc.name); } + if keep_visibility { + carry_visibility(&st.doc, &mut d, &changed); + } let damage = layer_multi_cmds::step_damage(&d, &st.doc); st.doc = d; restore_target(st, layers); From b52f0231916db16a61fe4fd1ff1123766ea7261b Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 15:27:23 +0200 Subject: [PATCH 38/73] Address CodeRabbit review: rollback brings back states the limit dropped for the step In non-linear history a record moves the later states onto the undo side and trims to the History States limit (and the byte budget) at once. A compound command whose later part failed then could not take its first step back when the trim dropped the state it replaced: the fallback Undo landed on the last later state and cleared the rest. Even when that state survived, the oldest states were lost. The latest record now holds the states it evicted until the next change to the list, and History::rollback puts them back. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/history_options_cmds.rs | 25 +++++ crates/ops/src/lib.rs | 118 +++++++++++++++++----- 2 files changed, 119 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/history_options_cmds.rs b/crates/engine/src/history_options_cmds.rs index bf9e50a511..17341b5ae1 100644 --- a/crates/engine/src/history_options_cmds.rs +++ b/crates/engine/src/history_options_cmds.rs @@ -533,4 +533,29 @@ mod tests { assert!(s.rollback()); assert!(red(&s, id) && visible(&s, id), "the hide is taken back, the fill stays"); } + + /// Non-linear, a step that moves more later states than the History States limit leaves room + /// for is still taken back exactly by a rollback (a compound command whose later part failed): + /// the document before it comes back with the full list, not an Undo onto the last later + /// state that also drops the rest. + #[test] + fn rollback_past_the_state_limit_restores_the_list() { + let (mut s, id) = doc(); + s.execute(CMD, json!({"allowNonLinearHistory": true})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let before = entries(&s); + let redo: Vec = s.active().unwrap().history.redo_labels().map(str::to_string).collect(); + assert_eq!(redo.len(), 2); + s.active_mut().unwrap().history.max_states = 2; + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + assert!(s.rollback()); + assert_eq!(entries(&s), before); + assert_eq!(s.active().unwrap().history.redo_labels().map(str::to_string).collect::>(), redo); + assert!(!red(&s, id), "back on the New Layer state, not on the inverted fill"); + s.execute("edit.redo", json!({})).unwrap(); + assert!(red(&s, id), "the red fill is still redoable"); + } } diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 0b3e7f9151..1ce090a9b7 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -59,11 +59,21 @@ pub struct History { /// (after stepping back) keeps them and goes to the end of the list, instead of discarding /// them; see [`History::record`] and [`History::remove`]. pub non_linear: bool, - /// How many former redo states the most recent [`History::record`] moved onto the undo side - /// (always 0 in linear history), while that record is still the latest change to the list; + /// The most recent [`History::record`], while it is still the latest change to the list; /// `None` once anything else changed it. [`History::rollback`] needs it to take the step back /// exactly. - last_moved: Option, + last_record: Option, +} + +/// What [`History::rollback`] needs to take the most recent [`History::record`] back. +#[derive(Clone, Debug, Default)] +struct LastRecord { + /// How many former redo states it moved onto the undo side (always 0 in linear history). + moved: usize, + /// The oldest states it (and the [`History::trim`] after it) dropped for the state limit or + /// the byte budget, oldest first. Their tiles are no longer counted; they are only held + /// until the next change to the list, so a rollback can put them back. + evicted: Vec, } impl Default for History { @@ -84,7 +94,7 @@ impl History { current_layers: LayerTarget::default(), current_visibility: Vec::new(), non_linear: false, - last_moved: None, + last_record: None, } } @@ -120,14 +130,15 @@ impl History { } else { self.clear_redo(); } - self.last_moved = Some(moved); + let mut evicted = Vec::new(); while self.undo.len() > self.max_states { - if let Some(state) = self.undo.pop_front() - && let Some(tiles) = &mut self.tiles - { + let Some(state) = self.undo.pop_front() else { break }; + if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } + evicted.push(state); } + self.last_record = Some(LastRecord { moved, evicted }); } pub fn can_undo(&self) -> bool { @@ -172,7 +183,7 @@ impl History { /// targeted when it was created. pub fn undo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { let prev = self.undo.pop_back()?; - self.last_moved = None; + self.last_record = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&prev.doc); tiles.add(¤t); @@ -187,7 +198,7 @@ impl History { /// Redo: the mirror of [`Self::undo`]. pub fn redo(&mut self, current: Arc) -> Option<(Arc, LayerTarget)> { let next = self.redo.pop()?; - self.last_moved = None; + self.last_record = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&next.doc); tiles.add(¤t); @@ -224,7 +235,7 @@ impl History { /// last step can no longer be undone and its pixels are released. pub fn purge_last(&mut self) -> bool { self.clear_redo(); - self.last_moved = None; + self.last_record = None; let Some(state) = self.undo.pop_back() else { return false }; if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); @@ -244,7 +255,7 @@ impl History { return false; } let Some(state) = self.undo.remove(i) else { return false }; - self.last_moved = None; + self.last_record = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } @@ -262,7 +273,7 @@ impl History { pub fn remove_later(&mut self, j: usize) -> bool { let Some(k) = self.redo.len().checked_sub(j.saturating_add(1)) else { return false }; let state = self.redo.remove(k); - self.last_moved = None; + self.last_record = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&state.doc); } @@ -279,7 +290,7 @@ impl History { /// list) stay. Returns the document to make current and the layers it targeted. pub fn drop_current(&mut self) -> Option<(Arc, LayerTarget)> { let prev = self.undo.pop_back()?; - self.last_moved = None; + self.last_record = None; if let Some(tiles) = &mut self.tiles { tiles.remove(&prev.doc); } @@ -296,16 +307,22 @@ impl History { /// Take back the most recent [`History::record`] exactly, for a compound command whose later /// part failed: the document it replaced becomes current again, the current document is /// dropped (nothing to redo), and in non-linear history the states that record moved from - /// the redo side go back there, so the list reads as before the command. Returns `None` + /// the redo side go back there, so the list reads as before the command, with the oldest + /// states the state limit or the byte budget dropped for it back too. Returns `None` /// (changing nothing) when something else changed the list since that record, e.g. an undo; /// the caller then falls back to [`History::undo`]. pub fn rollback(&mut self) -> Option<(Arc, LayerTarget)> { - let moved = self.last_moved?; - if self.undo.len() <= moved { - // The state it replaced went with the state limit. + let held = self.last_record.as_ref()?; + if self.undo.len().saturating_add(held.evicted.len()) <= held.moved { return None; } - self.last_moved = None; + let LastRecord { moved, evicted } = self.last_record.take()?; + for state in evicted.into_iter().rev() { + if let Some(tiles) = &mut self.tiles { + tiles.add(&state.doc); + } + self.undo.push_front(state); + } for _ in 0..moved { // Tiles stay counted: they only move back to the redo side. let state = self.undo.pop_back()?; @@ -324,15 +341,14 @@ impl History { /// The document the most recent [`History::record`] replaced, while [`History::rollback`] /// can still take that record back. pub fn recorded_before(&self) -> Option> { - let moved = self.last_moved?; - let i = self.undo.len().checked_sub(moved.checked_add(1)?)?; - self.undo.get(i).map(|s| s.doc.clone()) + let held = self.last_record.as_ref()?; + held.evicted.iter().chain(&self.undo).rev().nth(held.moved).map(|s| s.doc.clone()) } /// Forget the redo states, e.g. after undoing half of a compound step that failed. pub fn clear_redo(&mut self) { if !self.redo.is_empty() { - self.last_moved = None; + self.last_record = None; } if let Some(tiles) = &mut self.tiles { for state in &self.redo { @@ -343,7 +359,7 @@ impl History { } pub fn clear(&mut self) { - self.last_moved = None; + self.last_record = None; self.current_visibility.clear(); self.undo.clear(); self.redo.clear(); @@ -446,6 +462,10 @@ impl History { let drop = self.undo.len() - keep; for state in self.undo.drain(..drop) { tiles.remove(&state.doc); + // Held for a rollback of the step that pushed them out. + if let Some(held) = &mut self.last_record { + held.evicted.push(state); + } } drop } @@ -784,6 +804,56 @@ mod tests { assert_counter(&h, &cur); } + /// A failed compound command whose first step moved more later states than the state limit + /// leaves room for (or whose step the byte budget trimmed for) is still taken back exactly: + /// the states the limit dropped for it come back, as in the list before the command. + #[test] + fn rollback_brings_back_the_states_the_limit_dropped_for_the_step() { + for max in 1..=4 { + let (mut h, mut cur) = stepped_back(true); + h.max_states = max; + let a = cur.clone(); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert!(h.past_len() <= max); + assert_eq!(h.recorded_before().map(|d| d.name.clone()).as_deref(), Some("a"), "max {max}"); + let (d, _) = h.rollback().unwrap(); + assert!(Arc::ptr_eq(&d, &a), "max {max}: back on A, not on an Undo of C"); + assert_eq!(h.entries(), ["Open", "A"], "max {max}"); + assert_eq!(h.redo_labels().collect::>(), ["B", "C"], "max {max}"); + assert!(h.rollback().is_none()); + } + // Once anything else changed the list, the dropped states stay dropped. + let (mut h, mut cur) = stepped_back(true); + h.max_states = 2; + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + cur = h.undo(cur).unwrap().0; + h.redo(cur).unwrap(); + assert!(h.rollback().is_none()); + assert_eq!(h.entries(), ["B", "C", "D"]); + // The byte budget: the trim after the step keeps only its newest state; the rollback + // brings back the rest and the tile counter follows. + let mut h = History { non_linear: true, ..History::default() }; + let mut cur = Arc::new(base()); + for (i, n) in ["A", "B", "C"].into_iter().enumerate() { + edit(&mut h, &mut cur, n, |d| { + d.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + cur = h.undo(cur).unwrap().0; + cur = h.undo(cur).unwrap().0; + h.max_bytes = 1; + edit(&mut h, &mut cur, "D", |d| { + d.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[1.0, 0.0, 0.0, 1.0]); + }); + assert!(h.trim(&cur) > 0); + assert_eq!(h.entries(), ["C", "D"]); + assert_counter(&h, &cur); + cur = h.rollback().unwrap().0; + assert_eq!(h.entries(), ["Open", "A"]); + assert_eq!(h.redo_labels().collect::>(), ["B", "C"]); + assert_counter(&h, &cur); + } + #[test] fn max_states_bound() { let mut h = History::new(3); From 54788d006ec069a9fba5e85cab1faed41f09444d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 21 Oct 2026 06:36:15 -0700 Subject: [PATCH 39/73] Print: file.printers lists no stand-in printers in the browser In the browser file.printers lists no printers and answers with a note, but with a printer_source installed it listed the stand-in's printers. The stand-in now follows the platform there too: file.printers and the Print dialog's system Printer menu use it everywhere but the browser. --- crates/engine/src/print_cmds.rs | 15 +++++++++++---- crates/engine/src/print_cmds/tests.rs | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9eb8956a7d..a4d3084853 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -74,7 +74,8 @@ pub struct Spooler { /// A stand-in for the system's printers, installed on `Session::printer_source` (tests): /// `file.printers`, `file.print.printers` and the Print dialog list these and do not ask the spooler. /// `file.print.printers` and the dialog's driver Printer menu list them on Windows only, where the -/// GDI route is; elsewhere they answer as that route does there. +/// GDI route is; elsewhere they answer as that route does there. In the browser `file.printers` +/// lists none of them, as it lists no printers there without a stand-in. pub type PrinterSource = std::sync::Arc Vec + Send + Sync>; /// Held while a thread of this process lists printers or calls into a printer driver. @@ -154,7 +155,7 @@ fn keep(kept: &std::sync::Mutex>, value: T) { /// Lists the printers; called with the spooler lock held. fn list_system_printers(s: &Session) -> Vec { - let list = match &s.printer_source { + let list = match stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")) { Some(source) => source(), None => { SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -165,6 +166,12 @@ fn list_system_printers(s: &Session) -> Vec { list } +/// `file.printers`' stand-in: the session's outside the browser, and `None` in the browser, where +/// `file.printers` lists no printers. +fn stand_in_printers(source: Option<&PrinterSource>, browser: bool) -> Option<&PrinterSource> { + source.filter(|_| !browser) +} + /// Lists the GDI route's printers; called with the spooler lock held. fn list_rgb_printers(s: &Session) -> RgbPrinters { let list = match &s.printer_source { @@ -208,7 +215,7 @@ pub fn rgb_printers_without_waiting(s: &Session) -> RgbPrinters { /// `file.printers` for the UI thread, which lists the printers as `rgb_printers_without_waiting` /// does where `craft-print` is the route. pub fn printers_without_waiting(s: &mut Session) -> Value { - if s.printer_source.is_none() && system_spooler().is_none() { + if stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")).is_none() && system_spooler().is_none() { return system_printers(s, &json!({})).unwrap_or_default(); } let list = try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS)).unwrap_or_else(|| system_printer_list(s)); @@ -343,7 +350,7 @@ fn cups_spool(job: &PrintJob) -> std::result::Result { /// server and where there is no `lp` (a sandbox). fn system_printers(s: &mut Session, p: &Value) -> Result { let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); - if named.is_none() && (s.printer_source.is_some() || system_spooler().is_some()) { + if named.is_none() && (stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")).is_some() || system_spooler().is_some()) { return Ok(printers_answer(system_printer_list(s))); } #[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 8be12d8902..06aa18f4f0 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -229,6 +229,17 @@ fn stand_in_printers_reach_the_gdi_route_on_windows_only() { assert_eq!(listed.iter().map(|p| (p.name.as_str(), p.default)).collect::>(), [("Studio", false), ("Office", true)]); } +/// `file.printers` lists a stand-in's printers everywhere but the browser. In the browser it lists +/// none, as the real command does there. +#[test] +fn stand_in_printers_reach_file_printers_outside_the_browser_only() { + let source = test_printers(); + assert!(stand_in_printers(Some(&source), true).is_none()); + let listed = stand_in_printers(Some(&source), false).map(|source| source()); + assert_eq!(listed.unwrap_or_default().iter().map(|p| (p.name.as_str(), p.default)).collect::>(), [("Studio", false), ("Office", true)]); + assert!(stand_in_printers(None, false).is_none()); +} + /// Synthetic driver settings: a DEVMODEW of `size` bytes plus `extra` private driver bytes, every /// byte a pattern so a stray write shows, with `dmFields` saying only the paper size is set. fn devmode(size: u16, extra: u16) -> Vec { From 5fbe4a6da9a2306d228fb9636b97bc78f22ef86e Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 21 Oct 2026 20:10:56 +0200 Subject: [PATCH 40/73] Address CodeRabbit review: the History trash click never targets the oldest state With Allow Non-Linear History on and only the oldest state current, history.deleteState stays enabled for a drop of a later (dimmed) state, but the trash took that as its enabled state: a click sent {} for the current, oldest state and only put an error in the status bar. The trash is now enabled for a click when a snapshot is selected or a past state exists, and for a drop while a row is being dragged that the command can delete. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels.rs | 55 ++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 46c1e2d246..3c368a8411 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -3456,8 +3456,16 @@ fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } let mut footer_cmd: Option<(&str, Value)> = None; if t.pro { - // With a snapshot selected the trash deletes it, as in Photoshop (#5324). - let can_delete = selected_snap.is_some() || app.session.is_enabled("history.deleteState"); + // With a snapshot selected the trash deletes it, as in Photoshop (#5324). A click deletes + // the current state, never the oldest; a drop can delete a later (dimmed) one, which + // Allow Non-Linear History offers even while the oldest state is current. + let can_click = selected_snap.is_some() || app.session.active().is_some_and(|st| st.history.past_len() > 0); + let can_drop = match drag { + Some(HistoryDrag::Snapshot(_)) => true, + Some(HistoryDrag::State(_)) => app.session.is_enabled("history.deleteState"), + None => false, + }; + let can_delete = can_click || can_drop; let can_new = app.session.is_enabled("history.newDocument"); widgets::panel_footer(ui, |ui| { let trash = ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash", 26.0, false, tl!("Delete current state"))).inner; @@ -5334,6 +5342,49 @@ mod snapshot_row_tests { assert_eq!(st.snapshots.len(), 1, "the snapshot is kept"); } + /// With Allow Non-Linear History and only the oldest state current, a click on the trash has + /// nothing to delete (the oldest state stays, as in Photoshop), so the trash is disabled; a + /// later (dimmed) state dragged onto it is still deleted, and once a past state exists again + /// the click works. + #[test] + fn non_linear_trash_click_never_targets_the_oldest_state() { + let mut h = pro_history(); + h.state_mut().run("history.options", json!({"allowNonLinearHistory": true})).unwrap(); + for _ in 0..3 { + h.state_mut().run("edit.undo", json!({})).unwrap(); + } + h.run_steps(3); + let history = |h: &Harness<'static, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + (st.history.past_len(), st.history.redo_labels().count()) + }; + assert_eq!(history(&h), (0, 3), "Open current, New Layer, Fill, Fill dimmed"); + assert!(h.state().session.is_enabled("history.deleteState"), "the engine still offers a later state to delete"); + let enabled = |h: &Harness<'static, PhotocraftApp>| { + let p = trash(h); + h.ctx.viewport(|v| { + v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.rect.size() == vec2(26.0, 26.0) && w.rect.center() == p).map(|w| w.enabled) + }) + }; + assert_eq!(enabled(&h), Some(false), "a click would only target the oldest state"); + let p = trash(&h); + click(&mut h, p); + assert_eq!(history(&h), (0, 3), "the click deletes nothing"); + assert!(!h.state().ui.status_error, "and reports no error: {}", h.state().ui.status); + + // The last dimmed Fill dragged onto the trash: only it goes. + let row = h.get_all_by_label("Fill").last().expect("the dimmed Fill row").rect().center(); + drag(&mut h, row, p); + assert_eq!(history(&h), (0, 2), "the dragged later state is deleted"); + + // A past state again: the click deletes the current one. + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(enabled(&h), Some(true)); + click(&mut h, p); + assert_eq!(history(&h).0, 0, "the click deleted the current state"); + } + /// Snapshot rows scroll with the states: many snapshots in a short dock leave the footer and /// its camera button in view. #[test] From 63ccb9b3256af09436a0d12c9f5948630b40d409 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 22 Oct 2026 11:56:44 +0200 Subject: [PATCH 41/73] Clamp out-of-range Trace Contour and Crystallize/Pointillize numbers on save again 3ec259068 made an out-of-range level or cell size an error, so save left the whole smart filter out of the PSD (only a warning). The engine clamps these to 0..255 and 3..300 and reads a non-number as the default when it renders, so the clamped write is the filter the user sees, as main's Extrude and Tiles already do with pi_in. Back to pi_in; the tests now pin the clamped values instead of the errors. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/smart_map.rs | 44 +++++++++++++++----------------------- 1 file changed, 17 insertions(+), 27 deletions(-) diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 9bc8212b06..d417b7e887 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -984,25 +984,12 @@ fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str Ok(enumv(type_id, psd)) } -/// `key` rounded to a `long` in `lo..=hi` (clamped, as the engine clamps Extrude and Tiles). +/// `key` rounded to a `long` in `lo..=hi` (clamped, and a non-number is the default, as the +/// engine reads Extrude, Tiles, Trace Contour, Crystallize and Pointillize). fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) } -/// `key` (`default` when absent) rounded to a `long`; a value that is not a number, or rounds -/// outside `lo..=hi`, is an error rather than a different filter written in its place. -fn pi_checked(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { - let v = match p.get(key) { - None => default, - Some(v) => v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| format!("`{key}` is not a number"))?, - } - .round(); - if !(f64::from(lo)..=f64::from(hi)).contains(&v) { - return Err(format!("{key} {v} is outside {lo}..={hi}")); - } - Ok(Value::Integer(v as i32)) -} - /// Param `key` as a `bool` (false when absent or not a bool, as the engine reads it). fn bool_param(p: &J, key: &str) -> Value { Value::Boolean(p.get(key).and_then(J::as_bool).unwrap_or(false)) @@ -1076,9 +1063,9 @@ fn fltr_for(k: &Known, p: &J) -> Result, String> { } // Photoshop stores no random seed for these: `seed` is ours only and is not written. "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), - "TrcC" => d.with("Lvl ", pi_checked(p, "level", 128.0, 0, 255)?).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), - "Crst" => d.with("ClSz", pi_checked(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)?), - "Pntl" => d.with("ClSz", pi_checked(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)?), + "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), + "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), + "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), // Photoshop stores no random seed for these: our `seed` is not written. "Wnd " => { d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?) @@ -2879,7 +2866,8 @@ mod tests { fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) ); - // Defaults, range ends and values that round into the range are written. + // Defaults and out-of-range values are written as the engine renders them: clamped to + // Photoshop's ranges, and a non-number as the default. assert_eq!( fltr("filter.stylize.traceContour", json!({})), Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) @@ -2902,6 +2890,16 @@ mod tests { fltr("filter.stylize.traceContour", json!({"level": 255.4})), Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(255)).with("Edg ", enumv("CntE", "Lwr ")))) ); + let crst = |v: i32| Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(v)))); + let pntl = |v: i32| Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(v)))); + let trcc = |v: i32, e: &str| Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(v)).with("Edg ", enumv("CntE", e)))); + assert_eq!(fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), crst(300)); + assert_eq!(fltr("filter.pixelate.crystallize", json!({"cellSize": 2.4})), crst(3)); + assert_eq!(fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), pntl(5)); + assert_eq!(fltr("filter.pixelate.pointillize", json!({"cellSize": null})), pntl(5)); + assert_eq!(fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), trcc(0, "Upr ")); + assert_eq!(fltr("filter.stylize.traceContour", json!({"level": 255.5})), trcc(255, "Lwr ")); + assert_eq!(fltr("filter.stylize.traceContour", json!({"level": [128]})), trcc(128, "Lwr ")); } #[test] @@ -2951,14 +2949,6 @@ mod tests { ("filter.stylize.traceContour", json!({"edge": "middle"})), ("filter.pixelate.pointillize", json!({"background": "teal"})), ("filter.pixelate.pointillize", json!({"background": [1.0]})), - // Numbers outside Photoshop's ranges, or not numbers: not clamped or replaced. - ("filter.pixelate.crystallize", json!({"cellSize": 1e9})), - ("filter.pixelate.crystallize", json!({"cellSize": 2.4})), - ("filter.pixelate.pointillize", json!({"cellSize": "big"})), - ("filter.pixelate.pointillize", json!({"cellSize": null})), - ("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), - ("filter.stylize.traceContour", json!({"level": 255.5})), - ("filter.stylize.traceContour", json!({"level": [128]})), ] { assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); } From cf4d2c863c1f38641fd3733af98eb6955b4c9156 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 22 Oct 2026 19:15:26 +0200 Subject: [PATCH 42/73] Address CodeRabbit review: a hidden Work Path is not the active path (#6079) After Make Selection hid the Work Path, active_path_name still fell back to it, so the Pen and Path Selection canvas menus offered Delete Path, Transform Path and the rest on a path nobody could see, and the options bar's Make Selection used it again. The fallback now applies only while the Work Path is shown; selecting it in the Paths panel makes it the active path again. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas_tool_menu.rs | 12 +++++++++++- crates/ui-egui/src/vector_ui.rs | 6 ++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs index 5a1ce569dc..89fc739b96 100644 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas_tool_menu.rs @@ -1726,6 +1726,12 @@ mod tests { assert_eq!(h.state().ui.selected_path, None); assert!(h.state().session.active().unwrap().doc.work_path.is_some()); assert!(!crate::vector_ui::work_path_shown(h.state())); + // The hidden work path is no longer the active path: a second right-click offers no path + // commands, so Delete Path can't remove it unseen. + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Pen && !m.has_path && m.path_name.is_none())); + choose(h.state_mut(), &ctx, "path.delete"); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "the hidden work path survives Delete Path"); } #[test] @@ -1765,8 +1771,12 @@ mod tests { crate::dialogs::confirm(&mut app, dialog).unwrap(); let st = app.session.active().unwrap(); assert!(st.doc.work_path.is_some() && st.doc.selection.is_some()); - // The active (Work) path again, with no pen path in progress. + // That hid the Work Path (#6079): it is not the active path until it is selected in the + // Paths panel again, and then it is, with no pen path in progress. app.run("select.deselect", json!({})).unwrap(); + assert!(make_selection(&mut app).is_err(), "the hidden Work Path is not the active path"); + assert!(app.ui.dialogs.is_empty()); + app.ui.selected_path = Some("work".into()); make_selection(&mut app).unwrap(); let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); crate::dialogs::confirm(&mut app, dialog).unwrap(); diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 1ee8b20178..69897c4e94 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -815,7 +815,8 @@ pub fn curvature_toggle(app: &mut PhotocraftApp, x: f64, y: f64) { } /// The path that path commands act on without a name: the one selected in the Paths panel, else -/// the work path, else the selected layer's shape path or vector mask; `None` when there's none. +/// the work path while it is shown (not after Make Selection hid it, #6079), else the selected +/// layer's shape path or vector mask; `None` when there's none. pub fn active_path_name(app: &PhotocraftApp) -> Option { let st = app.session.active()?; let rows = path_rows(&st.doc, st.active_layer); @@ -825,7 +826,8 @@ pub fn active_path_name(app: &PhotocraftApp) -> Option { PathRow::Saved => r.name.clone(), }; let selected = app.ui.selected_path.as_deref().filter(|s| rows.iter().any(|r| key(r) == *s)).map(str::to_string); - selected.or_else(|| rows.iter().find(|r| r.kind == PathRow::Work).map(key)).or_else(|| rows.iter().find(|r| r.kind == PathRow::Layer).map(key)) + let work = rows.iter().find(|r| r.kind == PathRow::Work).filter(|_| work_path_shown(app)).map(key); + selected.or(work).or_else(|| rows.iter().find(|r| r.kind == PathRow::Layer).map(key)) } /// The commands that create a fill or adjustment layer and take a `"path"` as its vector mask. From c641cf44a82b0fa0912969deed6601c12cffff32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 22 Oct 2026 11:59:03 -0700 Subject: [PATCH 43/73] Print: reuse a kept printer list only for the printers it came from While another thread holds the spooler, the Print dialog's listings return the last printer lists this process got. The lists were kept process-wide, so a session with one printer_source could get the lists of another session's stand-in, or the system's. Each kept list now records the printer_source it came from, and a session with other printers lists its own, waiting for the spooler as a first listing does. --- crates/engine/src/print_cmds.rs | 39 +++++++++++++++-------- crates/engine/src/print_cmds/tests.rs | 46 +++++++++++++++++++++++---- 2 files changed, 65 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 2d0762268f..bdc3d07864 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -141,16 +141,27 @@ pub const SPOOLER_BUSY: &str = "the printer driver is busy with another print; t /// The GDI route's printers, or why they could not be listed. pub type RgbPrinters = std::result::Result, craft_print::rgb::PrintError>; -/// The last answers `system_printer_list` and `rgb_printers` got in this process. -static LAST_PRINTERS: std::sync::Mutex>> = std::sync::Mutex::new(None); -static LAST_RGB_PRINTERS: std::sync::Mutex> = std::sync::Mutex::new(None); +/// A list kept with the session's `printer_source` it came from (`None` for the system's printers). +type Kept = std::sync::Mutex, T)>>; -fn last(kept: &std::sync::Mutex>) -> Option { - kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() +/// The last answers `system_printer_list` and `rgb_printers` got in this process. +static LAST_PRINTERS: Kept> = std::sync::Mutex::new(None); +static LAST_RGB_PRINTERS: Kept = std::sync::Mutex::new(None); + +/// The kept list when it came from `source`; a list from other printers is not returned. +fn last(kept: &Kept, source: Option<&PrinterSource>) -> Option { + let kept = kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (from, list) = kept.as_ref()?; + let same = match (from, source) { + (None, None) => true, + (Some(from), Some(source)) => std::sync::Arc::ptr_eq(from, source), + _ => false, + }; + same.then(|| list.clone()) } -fn keep(kept: &std::sync::Mutex>, value: T) { - *kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(value); +fn keep(kept: &Kept, source: Option<&PrinterSource>, value: T) { + *kept.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((source.cloned(), value)); } /// Lists the printers; called with the spooler lock held. @@ -162,7 +173,7 @@ fn list_system_printers(s: &Session) -> Vec { craft_print::printers() } }; - keep(&LAST_PRINTERS, list.clone()); + keep(&LAST_PRINTERS, s.printer_source.as_ref(), list.clone()); list } @@ -181,7 +192,7 @@ fn list_rgb_printers(s: &Session) -> RgbPrinters { craft_print::rgb::printers() } }; - keep(&LAST_RGB_PRINTERS, list.clone()); + keep(&LAST_RGB_PRINTERS, s.printer_source.as_ref(), list.clone()); list } @@ -206,10 +217,11 @@ pub fn rgb_printers(s: &Session) -> RgbPrinters { } /// `rgb_printers` for the UI thread: while another thread lists printers or is in a printer driver -/// (a print job being handed to the spooler, Print Settings…), the list the last listing in this -/// process got, without waiting. Only the first listing in the process waits. +/// (a print job being handed to the spooler, Print Settings…), the list the last listing of the same +/// printers (the system's, or the same stand-in) got in this process, without waiting. Only the +/// first listing of those printers waits. pub fn rgb_printers_without_waiting(s: &Session) -> RgbPrinters { - try_with_spooler(|| list_rgb_printers(s)).or_else(|| last(&LAST_RGB_PRINTERS)).unwrap_or_else(|| rgb_printers(s)) + try_with_spooler(|| list_rgb_printers(s)).or_else(|| last(&LAST_RGB_PRINTERS, s.printer_source.as_ref())).unwrap_or_else(|| rgb_printers(s)) } /// `file.printers` for the UI thread, which lists the printers as `rgb_printers_without_waiting` @@ -218,7 +230,8 @@ pub fn printers_without_waiting(s: &mut Session) -> Value { if stand_in_printers(s.printer_source.as_ref(), cfg!(target_arch = "wasm32")).is_none() && system_spooler().is_none() { return system_printers(s, &json!({})).unwrap_or_default(); } - let list = try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS)).unwrap_or_else(|| system_printer_list(s)); + let list = + try_with_spooler(|| list_system_printers(s)).or_else(|| last(&LAST_PRINTERS, s.printer_source.as_ref())).unwrap_or_else(|| system_printer_list(s)); printers_answer(list) } diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index fc47a839ba..00137449b0 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -735,18 +735,18 @@ fn listings_without_waiting_return_the_last_lists_while_the_spooler_is_busy() { counted.fetch_add(1, Ordering::SeqCst); vec![craft_print::Printer { name: "Office".into(), default: true, two_sided: None }] })); - // Lists once, so there are last lists. - s.execute("file.printers", json!({})).unwrap(); - s.execute("file.print.printers", json!({})).unwrap(); let (held_tx, held) = mpsc::channel(); let (release, released_rx) = mpsc::channel::<()>(); let released = Arc::new(AtomicBool::new(false)); let holder = { let released = Arc::clone(&released); + let mut lister = Session::new(); + lister.printer_source = s.printer_source.clone(); std::thread::spawn(move || { with_spooler(|| { - // Nothing replaces the last lists while the lock is held. - held_tx.send((last(&LAST_PRINTERS), last(&LAST_RGB_PRINTERS))).unwrap(); + // Lists this stand-in's printers once with the lock held, so another test's listing + // cannot replace the last lists before the listings below. + held_tx.send((list_system_printers(&lister), list_rgb_printers(&lister))).unwrap(); // Bounded, so a listing that waits fails the test rather than hanging it. let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); released.store(true, Ordering::SeqCst); @@ -761,8 +761,40 @@ fn listings_without_waiting_return_the_last_lists_while_the_spooler_is_busy() { release.send(()).unwrap(); holder.join().unwrap(); assert_eq!(asked.load(Ordering::SeqCst), before, "a printer list was asked for while the spooler was busy"); - assert_eq!(listed, printers_answer(kept.unwrap())); - assert_eq!(listed_rgb, kept_rgb.unwrap()); + assert_eq!(listed, printers_answer(kept)); + assert_eq!(listed_rgb, kept_rgb); +} + +/// While the spooler is busy, a session whose printers were never listed waits for its own list: +/// the last lists another session's stand-in got are not its printers. +#[test] +fn listings_without_waiting_skip_the_lists_of_another_stand_in() { + use std::sync::{Arc, mpsc}; + let one = |name: &'static str| -> PrinterSource { Arc::new(move || vec![craft_print::Printer { name: name.into(), default: true, two_sided: None }]) }; + let mut other = Session::new(); + other.printer_source = Some(one("Elsewhere")); + other.execute("file.printers", json!({})).unwrap(); + other.execute("file.print.printers", json!({})).unwrap(); + let mut s = Session::new(); + s.printer_source = Some(one("Proofing")); + let (held_tx, held) = mpsc::channel(); + let holder = std::thread::spawn(move || { + with_spooler(|| { + held_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(500)); + }); + }); + held.recv().unwrap(); + let listed = printers_without_waiting(&mut s); + let listed_rgb = rgb_printers_without_waiting(&s); + holder.join().unwrap(); + assert_eq!(listed["printers"], json!([{"name": "Proofing", "default": true}])); + let names = listed_rgb.map(|list| list.into_iter().map(|p| p.name).collect::>()); + if cfg!(windows) { + assert_eq!(names, Ok(vec!["Proofing".to_string()])); + } else { + assert_eq!(names, Err(craft_print::rgb::PrintError::Unsupported)); + } } /// Spooling tests run in a child process: `disable_printing` is process-wide and a test above From 36e9d88326886ca9ea558a91ecea77ccc472c876 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 22 Oct 2026 13:14:05 -0700 Subject: [PATCH 44/73] Paste: a failed clipboard read is an error, not nothing to paste The copied-file and text reads treated every arboard error except a busy clipboard as an empty clipboard, so a read that failed (a broken pipe on Wayland, for example) dropped a mirrored copy and reported "Nothing to paste". Now only ContentNotAvailable reads as nothing, as the image read already does; any other failure is the paste's error. Text that is not UTF-8 still reads as no SVG markup. --- apps/photocraft/src/services.rs | 54 +++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 3e87f48890..86819b39e3 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -576,6 +576,26 @@ fn clipboard_image( Ok(text(clipboard)?.and_then(|text| image_from_svg_text(&text))) } +/// One OS clipboard read as [`clipboard_image`] takes it: no content in the format asked for is +/// `None`, and any other failure, such as a busy clipboard or a broken pipe on Wayland, is the +/// read's error. +fn clipboard_read(read: Result) -> Result, String> { + match read { + Ok(value) => Ok(Some(value)), + Err(arboard::Error::ContentNotAvailable) => Ok(None), + Err(error) => Err(error.to_string()), + } +} + +/// Clipboard text as [`clipboard_image`] takes it: like [`clipboard_read`], except that text that +/// isn't UTF-8 is `None`, like other text that isn't SVG markup. +fn clipboard_text(read: Result) -> Result, String> { + match read { + Err(arboard::Error::ConversionFailure) => Ok(None), + read => clipboard_read(read), + } +} + /// The shell command that starts this install under XWayland, where winit delivers file drops /// (winit 0.30 has none on Wayland, #386). A Flatpak gets the X11 socket only without the Wayland /// one, an AppImage relaunches by its own path, and anything else is `photocraft` on the PATH. @@ -688,11 +708,7 @@ pub fn native(automation: Option) -> }; clipboard_image( cb, - |cb| match cb.get().file_list() { - Ok(paths) => Ok(Some(paths)), - Err(error @ arboard::Error::ClipboardOccupied) => Err(error.to_string()), - Err(_) => Ok(None), - }, + |cb| clipboard_read(cb.get().file_list()), |cb| match cb.get_image() { Ok(img) => Ok(Some((img.width as u32, img.height as u32, img.bytes.into_owned()))), Err(error) => { @@ -706,11 +722,7 @@ pub fn native(automation: Option) -> } } }, - |cb| match cb.get_text() { - Ok(text) => Ok(Some(text)), - Err(error @ arboard::Error::ClipboardOccupied) => Err(error.to_string()), - Err(_) => Ok(None), - }, + |cb| clipboard_text(cb.get_text()), ) }) }), @@ -1518,6 +1530,28 @@ mod tests { assert_eq!(got, Err("the clipboard is busy".to_string()), "the text's error"); } + /// Only a clipboard with nothing in the format asked for reads as nothing to paste. A read + /// that fails in any other way, such as a broken pipe on Wayland, is the paste's error, for + /// the copied files and the text alike. Text that isn't UTF-8 reads as no SVG markup. + #[test] + fn only_missing_content_reads_as_nothing_to_paste() { + use arboard::Error; + let failures = || [Error::ClipboardOccupied, Error::ClipboardNotSupported, Error::Unknown { description: "broken pipe".to_string() }]; + assert_eq!(clipboard_read(Ok::<_, Error>(vec![PathBuf::from("a.png")])), Ok(Some(vec![PathBuf::from("a.png")]))); + assert_eq!(clipboard_read::>(Err(Error::ContentNotAvailable)), Ok(None)); + for error in failures().into_iter().chain([Error::ConversionFailure]) { + let message = error.to_string(); + assert_eq!(clipboard_read::>(Err(error)), Err(message.clone()), "{message}"); + } + assert_eq!(clipboard_text(Ok("words".to_string())), Ok(Some("words".to_string()))); + assert_eq!(clipboard_text(Err(Error::ContentNotAvailable)), Ok(None)); + assert_eq!(clipboard_text(Err(Error::ConversionFailure)), Ok(None), "text that isn't UTF-8"); + for error in failures() { + let message = error.to_string(); + assert_eq!(clipboard_text(Err(error)), Err(message.clone()), "{message}"); + } + } + /// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the /// drawing's art; other text is still a quiet "nothing to paste". #[test] From bf74a679f5edba08f0abef0005238ea928bd1972 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 24 Oct 2026 02:39:26 +0200 Subject: [PATCH 45/73] Loading a saved path as a selection leaves no target path (#6079) After Ctrl/Cmd+Enter or Make Selection on a saved path, the Paths panel selection is cleared; the Work Path stayed shown and so became the fallback active path, and a second Ctrl/Cmd+Enter or the canvas menu's Delete Path acted on it. As in Photoshop, no path is targeted after loading one: the Work Path is hidden in that case too. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/path_selection_tests.rs | 25 +++++++++++++++++++++- crates/ui-egui/src/vector_ui.rs | 9 ++++---- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/path_selection_tests.rs b/crates/ui-egui/src/path_selection_tests.rs index a5d0005183..af5a2de54e 100644 --- a/crates/ui-egui/src/path_selection_tests.rs +++ b/crates/ui-egui/src/path_selection_tests.rs @@ -126,13 +126,36 @@ fn cmd_enter_loads_the_path_selected_in_the_paths_panel() { h.run_steps(2); press(&mut h, Key::Enter, command()); assert_eq!(selection(&h), Some([100, 40, 60, 50]), "{}", h.state().ui.status); - // A selected path that went away falls back to the work path. + // A selected path that went away falls back to the work path once that is selected again. h.state_mut().run("path.delete", json!({"name": "Path 1"})).unwrap(); h.state_mut().run("select.deselect", json!({})).unwrap(); + h.state_mut().ui.selected_path = Some("work".into()); press(&mut h, Key::Enter, command()); assert_eq!(selection(&h), Some([0, 0, 30, 30])); } +#[test] +fn cmd_enter_on_a_saved_path_leaves_no_target_path() { + // #6079: after loading a saved path nothing is the target path; the shown Work Path must not + // take over (a second ⌘↩ or the canvas menu's Delete Path would act on it). + let mut h = harness(); + h.state_mut().run("path.set", json!({"name": "work", "path": rect_path(0.0, 0.0, 30.0, 30.0)})).unwrap(); + h.state_mut().run("path.set", json!({"name": "Path 1", "path": rect_path(100.0, 40.0, 60.0, 50.0)})).unwrap(); + h.state_mut().ui.tool = Tool::Pen; + h.state_mut().ui.selected_path = Some("Path 1".into()); + h.run_steps(2); + press(&mut h, Key::Enter, command()); + assert_eq!(selection(&h), Some([100, 40, 60, 50]), "{}", h.state().ui.status); + assert_eq!(h.state().ui.selected_path, None); + assert_eq!(crate::vector_ui::active_path_name(h.state()), None, "the Work Path didn't become the target path"); + assert!(!crate::vector_ui::work_path_shown(h.state()), "the Work Path isn't drawn"); + // A second ⌘↩ has no path to load. + h.state_mut().run("select.deselect", json!({})).unwrap(); + press(&mut h, Key::Enter, command()); + assert_eq!(selection(&h), None, "the unselected Work Path wasn't loaded"); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "the Work Path stays"); +} + #[test] fn without_a_path_it_says_why_and_the_key_can_be_rebound() { let mut h = harness(); diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 69897c4e94..c405b70bbc 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -886,16 +886,17 @@ pub fn path_to_selection(app: &mut PhotocraftApp, params: Value) -> Result"); + assert!(parse(&xml, ParsingOptions::default()).is_ok()); + } + + #[test] + fn an_internal_subset_is_refused_an_external_doctype_parses() { + let krita = "\n\n"; + assert!(parse(krita, dtd()).is_ok()); + let deep = format!("]>&e;", "".repeat(20_000), "".repeat(20_000)); + for xml in [ + "]>&e;".to_string(), + "\u{feff} ]>".to_string(), + deep, + ] { + let e = parse(&xml, dtd()).err().unwrap_or_else(|| panic!("parsed {xml:.60}")); + assert!(e.contains("internal DTD"), "{e}"); + } + // Without allow_dtd roxmltree refuses any DOCTYPE itself. + assert!(parse(krita, ParsingOptions::default()).is_err()); + } +} From e1b9c30294e1881999c4f439e38a638c45b6401d Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 12:59:31 +0100 Subject: [PATCH 61/73] XML: check every DOCTYPE for an internal subset, not only the prolog's A quoted ?> in the XML declaration hid the DOCTYPE from the prolog walk. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/kra/tests.rs | 4 ++- crates/io/src/xml.rs | 59 ++++++++++++++++---------------------- 2 files changed, 27 insertions(+), 36 deletions(-) diff --git a/crates/io/src/kra/tests.rs b/crates/io/src/kra/tests.rs index 711b91364a..214ccdc9c6 100644 --- a/crates/io/src/kra/tests.rs +++ b/crates/io/src/kra/tests.rs @@ -208,7 +208,9 @@ fn deeply_nested_maindoc_is_an_error_not_a_stack_overflow() { let (open, close) = ("".repeat(20_000), "".repeat(20_000)); let direct = maindoc("RGBA", &format!("{open}{close}")); let entity = format!("]>&e;"); - for (xml, why) in [(direct, "nested"), (entity, "internal DTD")] { + // A quoted `?>` in the XML declaration must not hide the DOCTYPE behind it. + let declared = format!("\"?>{entity}"); + for (xml, why) in [(direct, "nested"), (entity, "internal DTD"), (declared, "internal DTD")] { let bytes = archive(&xml, &[]); let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || crate::import("deep.kra", &bytes).err()).unwrap().join().unwrap(); assert!(matches!(&e, Some(IoError::Kra(m)) if m.contains(why)), "{why}: {e:?}"); diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs index 02a493a671..f152d4e000 100644 --- a/crates/io/src/xml.rs +++ b/crates/io/src/xml.rs @@ -21,41 +21,27 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result Document::parse_with_options(text, opts).map_err(|e| e.to_string()) } -/// Does the prolog's DOCTYPE have an internal subset (``)? Only the prolog can -/// hold a DOCTYPE; the parser rejects one anywhere else. +/// Does a DOCTYPE have an internal subset (``)? Every `` in the XML +/// declaration must not hide it. One inside a comment may be refused needlessly; that fails safe. fn internal_subset(xml: &[u8]) -> bool { - let mut rest = xml.strip_prefix("\u{feff}".as_bytes()).unwrap_or(xml); - loop { - rest = rest.trim_ascii_start(); - let skip = |rest: &[u8], open: usize, close: &[u8]| -> Option { - let body = rest.get(open..)?; - body.windows(close.len()).position(|w| w == close).map(|p| open.saturating_add(p).saturating_add(close.len())) - }; - let next = if rest.starts_with(b"") - } else if rest.starts_with(b"") - } else if rest.starts_with(b"` ends a DOCTYPE without one. - let mut quote = None; - for &b in rest.iter().skip(9) { - match quote { - Some(q) if b == q => quote = None, - Some(_) => {} - None if b == b'"' || b == b'\'' => quote = Some(b), - None if b == b'[' => return true, - None if b == b'>' => return false, - None => {} - } + const DOCTYPE: &[u8] = b"` ends a DOCTYPE without one. + let mut quote = None; + for &b in xml.iter().skip(at.saturating_add(DOCTYPE.len())) { + match quote { + Some(q) if b == q => quote = None, + Some(_) => {} + None if b == b'"' || b == b'\'' => quote = Some(b), + None if b == b'[' => return true, + None if b == b'>' => return false, + None => {} } - return false; - } else { - return false; - }; - let Some(next) = next else { return false }; - rest = rest.get(next..).unwrap_or_default(); - } + } + false + }) } #[cfg(test)] @@ -100,11 +86,14 @@ mod tests { fn an_internal_subset_is_refused_an_external_doctype_parses() { let krita = "\n\n"; assert!(parse(krita, dtd()).is_ok()); - let deep = format!("]>&e;", "".repeat(20_000), "".repeat(20_000)); + let g = ("".repeat(20_000), "".repeat(20_000)); for xml in [ "]>&e;".to_string(), "\u{feff} ]>".to_string(), - deep, + format!("]>&e;", g.0, g.1), + // roxmltree reads the declaration's values as quoted attributes, so they may hold `?>`. + format!("\"?>]>&e;", g.0, g.1), + format!("\"?>]>{}{}", g.0, g.1), ] { let e = parse(&xml, dtd()).err().unwrap_or_else(|| panic!("parsed {xml:.60}")); assert!(e.contains("internal DTD"), "{e}"); From b53f2dcac75537423fff4beaef4b84299353b406 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 13:26:53 +0100 Subject: [PATCH 62/73] Automation: refuse every Windows device name in request paths (#9424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The automation device-name check was narrower than cap-std's own Windows check (COM0/LPT0, COM¹-³/LPT¹-³, spaces before the extension). write() renames through a Win32 path and skips cap-std's check, so a file such as COM¹.png or "NUL .png" could be written but not read back, and export_sequence left an empty folder behind. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/workspace.rs | 36 +++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index e8566b439e..f19397e563 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -221,11 +221,14 @@ fn relative_path(raw: &str) -> Result { Ok(PathBuf::from(raw)) } +/// At least every name cap-std refuses to open on Windows (`COM0`–`COM9`, `COM¹`–`COM³`, the same +/// for `LPT`, spaces before the extension ignored), so nothing written is unreadable (#9424). fn is_windows_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).to_ascii_uppercase(); + let stem = component.split('.').next().unwrap_or(component).trim_end().to_ascii_uppercase(); + let port = |n: &str| matches!(n, "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"); matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") - || stem.strip_prefix("COM").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")) - || stem.strip_prefix("LPT").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")) + || stem.strip_prefix("COM").is_some_and(port) + || stem.strip_prefix("LPT").is_some_and(port) } fn path_error(path: &str, reason: &str) -> AutomationError { @@ -675,6 +678,33 @@ mod tests { } } + #[test] + fn every_device_name_cap_std_refuses_to_open_is_refused_before_any_write() { + // cap-std refuses these when it opens a file on Windows, so a file written under one of + // them could not be read back (#9424). + let (inside, _, workspace) = roots("devices"); + std::fs::create_dir(inside.join("sub")).unwrap(); + for path in + ["COM0.txt", "LPT0", "COM¹.png", "com².png", "COM³", "LPT¹.txt", "LPT².txt", "lpt³", "NUL .png", "Aux .txt", "sub/CON .psd", "COM¹/frame.png"] + { + let error = workspace.write(path, b"x").unwrap_err().to_string(); + assert!(error.contains("reserved device names"), "write {path:?}: {error}"); + let error = workspace.read(path).unwrap_err().to_string(); + assert!(error.contains("reserved device names"), "read {path:?}: {error}"); + } + for dir in ["COM¹", "LPT0", "sub/PRN .x"] { + let error = workspace.export_sequence(dir).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("reserved device names"), "export {dir:?}: {error}"); + } + assert_eq!(std::fs::read_dir(&inside).unwrap().count(), 1, "only `sub` may exist"); + assert_eq!(std::fs::read_dir(inside.join("sub")).unwrap().count(), 0); + // Look-alikes are ordinary names. + for path in ["COM10.txt", "COM¹0.txt", "LPT00", "console.txt", "NULL.txt", "nul_.txt", " NUL.txt"] { + workspace.write(path, b"x").unwrap_or_else(|e| panic!("write {path:?}: {e}")); + assert_eq!(workspace.read(path).unwrap(), b"x", "{path:?}"); + } + } + #[test] fn read_and_write_authority_are_separate() { let (inside, _, _) = roots("separate"); From 4c66dd45d235d9cccc6c3f8cb5b1f31b8459cdeb Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 13:50:54 +0100 Subject: [PATCH 63/73] Address CodeRabbit review: the DOCTYPE check is one linear pass Each ' or '[', so a comment full of them cost quadratic time. Scans in the same quote state go on alike, so one pass with three flags finds the same answer. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/xml.rs | 82 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 67 insertions(+), 15 deletions(-) diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs index f152d4e000..13e02004d1 100644 --- a/crates/io/src/xml.rs +++ b/crates/io/src/xml.rs @@ -24,24 +24,28 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result /// Does a DOCTYPE have an internal subset (``)? Every `` in the XML /// declaration must not hide it. One inside a comment may be refused needlessly; that fails safe. +/// +/// Each `` ends a DOCTYPE without one. Scans in +/// the same quote state go on alike, so one pass keeps just three flags (outside quotes, in `"`, +/// in `'`) and stays linear however many ` bool { const DOCTYPE: &[u8] = b"` ends a DOCTYPE without one. - let mut quote = None; - for &b in xml.iter().skip(at.saturating_add(DOCTYPE.len())) { - match quote { - Some(q) if b == q => quote = None, - Some(_) => {} - None if b == b'"' || b == b'\'' => quote = Some(b), - None if b == b'[' => return true, - None if b == b'>' => return false, - None => {} - } + let (mut bare, mut double, mut single) = (false, false, false); + for (at, &b) in xml.iter().enumerate() { + if at.checked_sub(DOCTYPE.len()).and_then(|start| xml.get(start..at)) == Some(DOCTYPE) { + bare = true; } - false - }) + if bare && b == b'[' { + return true; + } + (bare, double, single) = ( + (bare && !matches!(b, b'"' | b'\'' | b'>')) || (double && b == b'"') || (single && b == b'\''), + (double && b != b'"') || (bare && b == b'"'), + (single && b != b'\'') || (bare && b == b'\''), + ); + } + false } #[cfg(test)] @@ -82,6 +86,54 @@ mod tests { assert!(parse(&xml, ParsingOptions::default()).is_ok()); } + /// The scan per ` bool { + const DOCTYPE: &[u8] = b" quote = None, + Some(_) => {} + None if b == b'"' || b == b'\'' => quote = Some(b), + None if b == b'[' => return true, + None if b == b'>' => return false, + None => {} + } + } + false + }) + } + + #[test] + fn the_one_pass_doctype_scan_agrees_with_a_scan_per_doctype() { + let parts: [&[u8]; 7] = [b"", b"a", b"", "\n\n"; From fa4269af98c18168678d2e65192597b60d8d83ff Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 14:09:13 +0100 Subject: [PATCH 64/73] Automation: refuse to replace a non-image file in the write root (#9439) `doc.save {"path": "src/main.rs", "format": "png"}` and `doc.render {"path": "Cargo.toml"}` renamed image bytes over whatever file was there. `AuthorizedWorkspace::write` now replaces an existing file only when its extension is a format PhotoCraft writes or its bytes are an image; new files of any name are still created. docs/mcp.md says what a granted root allows and recommends a dedicated output folder. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/rpc.rs | 38 ++++++++++++++++++++++++++++++ crates/automation/src/workspace.rs | 26 ++++++++++++++++++++ docs/mcp.md | 11 ++++++++- 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index b98094eb5d..d85fae874c 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -771,6 +771,44 @@ mod tests { std::fs::remove_dir_all(base).unwrap(); } + /// A save or render never turns a file PhotoCraft doesn't write (source, settings, notes) + /// into image bytes, whatever `format` says; images and new files are written as before (#9439). + #[test] + fn workspace_writes_refuse_to_replace_a_file_that_is_not_an_image() { + let root = std::env::temp_dir().join(format!("pc-no-replace-foreign-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("src")).unwrap(); + let foreign = [("src/main.rs", "fn main() {}\n"), ("Cargo.toml", "[package]\n"), (".env", "TOKEN=x\n"), ("Makefile", "all:\n")]; + for (name, text) in foreign { + std::fs::write(root.join(name), text).unwrap(); + } + std::fs::write(root.join("old.png"), b"not yet a png").unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + for (name, text) in foreign { + let saved = h.handle("doc.save", json!({"path": name, "format": "png"})).unwrap_err().to_string(); + assert!(saved.contains("already exists"), "doc.save over {name}: {saved}"); + let rendered = h.handle("doc.render", json!({"path": name})).unwrap_err().to_string(); + assert!(rendered.contains("already exists"), "doc.render over {name}: {rendered}"); + assert_eq!(std::fs::read_to_string(root.join(name)).unwrap(), text, "{name} is untouched"); + } + // An existing image is replaced, and a new file of any name is created. + h.handle("doc.save", json!({"path": "old.png"})).unwrap(); + assert!(std::fs::read(root.join("old.png")).unwrap().starts_with(b"\x89PNG")); + h.handle("doc.save", json!({"path": "fresh.txt", "format": "png"})).unwrap(); + assert!(std::fs::read(root.join("fresh.txt")).unwrap().starts_with(b"\x89PNG")); + h.handle("doc.render", json!({"path": "old.png"})).unwrap(); + std::fs::write(root.join("OLD.TIF"), b"x").unwrap(); + h.handle("doc.save", json!({"path": "OLD.TIF"})).unwrap(); + // An image saved under a name without an image extension is recognised by its bytes. + h.handle("doc.save", json!({"path": "out", "format": "png"})).unwrap(); + h.handle("doc.save", json!({"path": "out", "format": "png"})).unwrap(); + h.handle("doc.render", json!({"path": "fresh.txt"})).unwrap(); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id())); diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index e8566b439e..ba10120858 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -88,6 +88,15 @@ impl AuthorizedWorkspace { let relative = request_path(path, self.write.as_ref())?; let root = self.write.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: write authority is absent")))?; let leaf = relative.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + // The bytes are an image or document whatever the name says (`format` picks them), so + // only a file of a kind PhotoCraft writes is replaced: never source, settings or notes + // that share the root (`src/main.rs`, `.env`; #9439). A new file may have any name, and + // an image saved under one (`out` with `format: png`) can be saved over again. + if root.dir.symlink_metadata(&relative).is_ok() && !written_kind(&leaf) && !holds_image(&root.dir, &relative) { + return Err(AutomationError::BadRequest(format!( + "automation write refused: `{path}` already exists and is not an image or document file PhotoCraft writes; save to a new name" + ))); + } let parent = relative.parent().map(Path::to_path_buf).unwrap_or_default(); let tmp = parent.join(photocraft_format::atomic::temp_name(&leaf)); let mut options = OpenOptions::new(); @@ -124,6 +133,23 @@ impl AuthorizedWorkspace { } } +/// Whether `name`'s extension is one of the formats PhotoCraft saves or exports. +fn written_kind(name: &str) -> bool { + let Some((_, ext)) = name.rsplit_once('.') else { return false }; + let ext = ext.to_ascii_lowercase(); + ["psd", "psb", "ora", "pdf", photocraft_format::EXTENSION].contains(&ext.as_str()) || photocraft_codecs::from_extension(&ext).is_some() +} + +/// Whether the file at `relative` starts like an image PhotoCraft reads (PSD/PSB or a codec's +/// magic). Containers that also hold other things (zip, PDF) are judged by name only. +fn holds_image(dir: &Dir, relative: &Path) -> bool { + let mut head = [0u8; 64]; + let Ok(mut file) = dir.open(relative) else { return false }; + let Ok(n) = file.read(&mut head) else { return false }; + let head = &head[..n]; + head.starts_with(b"8BPS") || photocraft_codecs::detect(head).is_some() +} + fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Result, AutomationError> { // Do not reserve from a potentially stale or attacker-controlled metadata length. Read in // chunks, and reject growth beyond the length observed on the opened file before appending. diff --git a/docs/mcp.md b/docs/mcp.md index 75cacd6e41..8846a3be1c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -57,6 +57,15 @@ Paths are relative to the corresponding root, or absolute paths beneath it; with filesystem authority is absent. Bridge mode uses `--bridge` and `--control-token-file` as described in [development.md](development.md). UI tools require a running desktop app. +A client has the full rights of the roots it is given: it can read any file below the read +root, and `doc_save`, `doc_export` and the export tools can create files anywhere below the +write root. `doc_save` and `doc_export` replace an existing file only when its extension is an +image or document format PhotoCraft writes (PNG, JPEG, TIFF, PSD, PSB, .pcraft, OpenRaster, +PDF, …) or its bytes are an image; anything else (`src/main.rs`, `.env`) is refused and left +untouched. The multi-file exports (layers, data sets) never replace a file. An agent reads +text from documents (layer names, metadata) that may try to steer it, so prefer a dedicated +output folder as the write root over a whole project. + Use absolute root paths in MCP client configurations, since a relative root is resolved from the client's launch directory. In bridge mode, configure roots on the **desktop app**; root flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and @@ -89,7 +98,7 @@ protocol messages. For `serve`, explicit credential flags require `--port` (or Existing document/session/job/UI tools remain listed, including the documented `doc_render_preview` spelling. There are no hidden legacy aliases. Every tool has a title and all four annotation hints. Generic command/control tools conservatively advertise writes; -file saves may replace existing targets. Hints do not grant permission. +file saves may replace existing image and document files. Hints do not grant permission. After a failed batch, `completed` and per-step `results` report successful steps, not a rolled-back transaction. Inspect the document and its history with `doc_inspect`; commands From 52359ada45eafec288b850eb0d01de204ccdf897 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 14:55:57 +0100 Subject: [PATCH 65/73] Address CodeRabbit review: refuse a non-regular write target before opening it An existing FIFO at the write target reached holds_image (and the Unix xattr copy), whose read-only open blocks until a writer appears, stalling every request behind the Headless lock. Check the target's type first, following links, and refuse directories, FIFOs, sockets and devices. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/workspace.rs | 49 +++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index ba10120858..a78a71987f 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -92,7 +92,14 @@ impl AuthorizedWorkspace { // only a file of a kind PhotoCraft writes is replaced: never source, settings or notes // that share the root (`src/main.rs`, `.env`; #9439). A new file may have any name, and // an image saved under one (`out` with `format: png`) can be saved over again. - if root.dir.symlink_metadata(&relative).is_ok() && !written_kind(&leaf) && !holds_image(&root.dir, &relative) { + let exists = root.dir.symlink_metadata(&relative).is_ok(); + // Only a regular file is ever opened below (its head here, its attributes on Unix): a + // FIFO would block that open until a writer appears, and with it every other request. + // Links are followed for this check; a dangling one falls through to the name rule. + if exists && root.dir.metadata(&relative).is_ok_and(|m| !m.is_file()) { + return Err(AutomationError::BadRequest(format!("automation write refused: `{path}` already exists and is not a regular file"))); + } + if exists && !written_kind(&leaf) && !holds_image(&root.dir, &relative) { return Err(AutomationError::BadRequest(format!( "automation write refused: `{path}` already exists and is not an image or document file PhotoCraft writes; save to a new name" ))); @@ -634,6 +641,46 @@ mod tests { assert!(temp_files(&inside).is_empty()); } + /// A directory at the target is refused before anything is opened, even under an image name. + #[test] + fn write_refuses_a_directory_target_before_opening_it() { + let (inside, _, workspace) = roots("dir-target"); + for name in ["adir", "adir.png"] { + std::fs::create_dir_all(inside.join(name)).unwrap(); + let error = workspace.write(name, b"x").unwrap_err().to_string(); + assert!(error.contains("is not a regular file"), "{name}: {error}"); + assert!(inside.join(name).is_dir()); + } + assert!(temp_files(&inside).is_empty()); + } + + /// A FIFO at the target is refused at once: opening it to sniff its head or copy its + /// attributes would block until a writer appears, stalling every other request. + #[cfg(unix)] + #[test] + fn write_refuses_a_fifo_target_without_blocking() { + let (inside, _, workspace) = roots("fifo-target"); + for name in ["pipe", "out.png"] { + let made = std::process::Command::new("mkfifo").arg(inside.join(name)).status(); + if !made.is_ok_and(|s| s.success()) { + return; // no mkfifo on this system: nothing to assert + } + } + std::os::unix::fs::symlink("pipe", inside.join("link")).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for name in ["pipe", "out.png", "link"] { + let _ = tx.send((name, workspace.write(name, b"x").map_err(|e| e.to_string()))); + } + }); + for _ in 0..3 { + let (name, result) = rx.recv_timeout(std::time::Duration::from_secs(5)).expect("write blocked on a FIFO"); + let error = result.unwrap_err(); + assert!(error.contains("is not a regular file"), "{name}: {error}"); + } + assert!(temp_files(&inside).is_empty()); + } + /// #7095: replacing a file through the automation path keeps the old file's extended /// attributes, the same as a save through `atomic_write` does. #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] From 50028953ff6204a48ee2de14213ee5d504361fbd Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 15:14:48 +0100 Subject: [PATCH 66/73] Address CodeRabbit review: a hidden Work Path is neither resumed nor flashed in another tile (#6079) A Pen press on an endpoint of the Work Path that Make Selection hid no longer carries it on; with no path selected the new path replaces it, as in Photoshop. The path overlay checks the hide against the document it draws, so the frame a click into another arranged tile activates that document doesn't draw the old document's hidden Work Path. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/path_selection_tests.rs | 48 ++++++++++++++++++++++ crates/ui-egui/src/pen_variants_tests.rs | 36 ++++++++++++++++ crates/ui-egui/src/vector_ui.rs | 20 +++++++-- 3 files changed, 100 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/path_selection_tests.rs b/crates/ui-egui/src/path_selection_tests.rs index 9ec4732602..8cab12747a 100644 --- a/crates/ui-egui/src/path_selection_tests.rs +++ b/crates/ui-egui/src/path_selection_tests.rs @@ -447,3 +447,51 @@ fn loading_a_path_after_hiding_extras_restores_outline() { assert_eq!(selection(&h), Some([10, 10, 50, 40])); assert!(h.state().ui.view.shows(h.state().ui.view.show.selection_edges)); } + +/// #6079 review: in an arranged view, the frame a click into another tile activates its document +/// still draws the old active document's overlays. The Work Path Make Selection hid there must not +/// flash up in that frame. +#[test] +fn a_hidden_work_path_stays_hidden_when_another_tile_is_clicked() { + // Path outlines (accent lines) in the right tile in the frame a click into the left tile makes. + let right_outlines_on_switch = |hide: bool| { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + } + app.sync_views(); + app.ui.view.arrange = "tileAllVertically".into(); + app.ui.tool = Tool::Pen; + app.run("path.set", json!({"name": "work", "path": rect_path(40.0, 30.0, 100.0, 80.0)})).unwrap(); + crate::vector_ui::path_to_selection(&mut app, json!({})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert!(!crate::vector_ui::work_path_shown(&app), "Make Selection hid the second document's Work Path"); + if !hide { + app.ui.hidden_work_path = None; + } + let mut h = Harness::builder().with_size(vec2(1000.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let area = h.state().last_canvas_rect; + let at = egui::pos2(area.left() + area.width() / 4.0, area.center().y); + h.event(Event::PointerMoved(at)); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert_eq!(h.state().session.active_index(), Some(0), "the click activated the left document"); + let accent = crate::theme::Tokens::get(&h.ctx).accent; + let outlines = h.output().shapes.iter().filter(|s| { + matches!(&s.shape, egui::Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(accent) && p.visual_bounding_rect().min.x > area.center().x) + }); + outlines.count() + }; + assert!(right_outlines_on_switch(false) > 0, "a shown Work Path is drawn in that frame"); + assert_eq!(right_outlines_on_switch(true), 0, "the hidden one isn't"); +} diff --git a/crates/ui-egui/src/pen_variants_tests.rs b/crates/ui-egui/src/pen_variants_tests.rs index cee8e37bbd..330f2bc6f3 100644 --- a/crates/ui-egui/src/pen_variants_tests.rs +++ b/crates/ui-egui/src/pen_variants_tests.rs @@ -273,3 +273,39 @@ fn undo_in_a_resumed_draft_stops_at_the_paths_own_anchors() { assert!(app.ui.direct_selection.anchors.is_empty()); assert_eq!(work_path(&app), before, "the path is as it was"); } + +/// #6079 review: Make Selection hides the Work Path. A Pen press on its old endpoint then starts a +/// new Work Path that replaces it, as Photoshop does with no path selected, instead of carrying on +/// the hidden one. A shown Work Path and a selected saved path still carry on. +#[test] +fn the_pen_does_not_carry_on_a_work_path_hidden_by_make_selection() { + let mut app = app(Tool::Pen); + let anchors = |p: &Path| -> Vec> { p.subpaths.iter().map(|s| s.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect()).collect() }; + click(&mut app, 20.0, 20.0); + click(&mut app, 80.0, 20.0); + crate::vector_ui::pen_commit(&mut app, false); + crate::vector_ui::path_to_selection(&mut app, json!({})).unwrap(); + assert!(!crate::vector_ui::work_path_shown(&app), "Make Selection hid the Work Path"); + click(&mut app, 80.0, 20.0); + click(&mut app, 80.0, 80.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(anchors(&work_path(&app)), [vec![[80.0, 20.0], [80.0, 80.0]]], "a new Work Path, not the hidden one carried on"); + // The new Work Path is shown and selected: it carries on as before. + click(&mut app, 80.0, 80.0); + click(&mut app, 140.0, 80.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(anchors(&work_path(&app)), [vec![[80.0, 20.0], [80.0, 80.0], [140.0, 80.0]]]); + // A saved path selected in the Paths panel carries on while the Work Path is hidden. + let open = json!({"subpaths": [{"closed": false, "knots": [{"anchor": [150.0, 150.0]}, {"anchor": [200.0, 150.0]}]}]}); + app.run("path.set", json!({"name": "Saved", "path": open})).unwrap(); + crate::vector_ui::path_to_selection(&mut app, json!({})).unwrap(); + assert!(!crate::vector_ui::work_path_shown(&app)); + app.ui.selected_path = Some("Saved".into()); + click(&mut app, 200.0, 150.0); + click(&mut app, 200.0, 190.0); + crate::vector_ui::pen_commit(&mut app, false); + let st = app.session.active().unwrap(); + let saved = st.doc.paths.iter().find(|p| p.name == "Saved").unwrap(); + assert_eq!(anchors(&saved.path), [vec![[150.0, 150.0], [200.0, 150.0], [200.0, 190.0]]], "the saved path carried on"); + assert_eq!(anchors(&work_path(&app)).len(), 1, "the hidden Work Path untouched"); +} diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index dce8d7a0d3..01bb49342e 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -612,6 +612,10 @@ fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { let st = app.session.active()?; let doc = st.doc.id.0; let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); + // A Work Path hidden by Make Selection isn't carried on: a new path replaces it (#6079). + if name == "work" && !work_path_shown(app) { + return None; + } let near = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y) < tol; doc_path(&st.doc, &name)?.subpaths.iter().enumerate().filter(|(_, s)| !s.closed).find_map(|(i, s)| { let reversed = if s.knots.last().is_some_and(near) { @@ -905,11 +909,19 @@ pub(crate) fn deselect_loaded_path(app: &mut PhotocraftApp, name: &str) { /// ends the hide; a saved path or a layer's path doesn't show it) or it changes (a new one drawn, Make Work Path, /// `path.set`…) (#6079). pub(crate) fn work_path_shown(app: &PhotocraftApp) -> bool { - if app.ui.selected_path.as_deref() == Some("work") { + app.session.active().is_none_or(|st| work_path_shown_in(app, &st.doc)) +} + +/// [`work_path_shown`] for `doc`, which the canvas may draw while another document is already +/// active (the frame a click into another arranged tile activates it). The Paths panel's +/// selection belongs to the active document only. +pub(crate) fn work_path_shown_in(app: &PhotocraftApp, doc: &Document) -> bool { + let active = app.session.active().is_some_and(|st| st.doc.id == doc.id); + if active && app.ui.selected_path.as_deref() == Some("work") { return true; } - let Some((doc, hidden)) = &app.ui.hidden_work_path else { return true }; - app.session.active().is_none_or(|st| st.doc.id.0 != *doc || st.doc.work_path.as_ref() != Some(hidden)) + let Some((id, hidden)) = &app.ui.hidden_work_path else { return true }; + doc.id.0 != *id || doc.work_path.as_ref() != Some(hidden) } // --------------------------------------------------------------------------------------------- @@ -1234,7 +1246,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform // a path tool is active, as in Photoshop: a Work Path left unselected (one a PSD arrived // with, or after Ctrl-click Load as Selection) would otherwise cover the marching ants (#6551). let anchors = shows_anchors(tool); - if let Some(wp) = doc.work_path.as_ref().filter(|_| work_path_shown(app)) + if let Some(wp) = doc.work_path.as_ref().filter(|_| work_path_shown_in(app, doc)) && (anchors || app.ui.selected_path.as_deref() == Some("work")) { draw_path(wp, anchors); From 68c0f034d507d104a3aff2ed46f01bd800a0af6a Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 14:30:56 +0100 Subject: [PATCH 67/73] Plug-ins: refuse a code section with no functions but many bytes instead of panicking (#9679) wasmi 2.0's strict limits divide the code section's size by its function count before validating it, so a module whose code section declares 0 functions but more than 1000 bytes (crafted, truncated inside the section, or a duplicate code section) panicked in Plugin::load. Check every code section for that one case before handing the bytes to wasmi and return Error::Module; everything else is still left to wasmi. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/plugins/src/runtime.rs | 37 +++++++++++++++++++++++++++++++++++ crates/plugins/tests/abi.rs | 19 ++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index c82171a5ac..9f66b545ba 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -115,6 +115,42 @@ fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } +/// Reads an unsigned LEB128 `u32` at the start of `bytes`: the value and its length. +fn leb_u32(bytes: &[u8]) -> Option<(u32, usize)> { + let mut value = 0u32; + for (i, &b) in bytes.iter().take(5).enumerate() { + value |= u32::from(b & 0x7f).checked_shl(7 * i as u32)?; + if b & 0x80 == 0 { + return Some((value, i + 1)); + } + } + None +} + +/// Refuses a code section that declares no functions but more bytes than that count. The spec +/// makes the count the whole section then; wasmi 2.0's strict limits divide the section size by +/// the function count before validating it, so such a module (crafted or truncated) panicked. +/// Every code section is checked, since a duplicate one also reaches that division before +/// validation refuses it. Anything else, malformed or not, is left to wasmi. +fn check_code_section(bytes: &[u8]) -> Result<()> { + if bytes.get(4..8) != Some(&[1, 0, 0, 0][..]) { + return Ok(()); + } + let mut pos = 8usize; + while let Some(&id) = bytes.get(pos) { + let Some((size, len)) = bytes.get(pos + 1..).and_then(leb_u32) else { return Ok(()) }; + let start = pos + 1 + len; + if id == 10 + && let Some((0, count_len)) = bytes.get(start..).and_then(leb_u32) + && size as usize > count_len + { + return Err(Error::Module(format!("the code section declares no functions but {size} bytes"))); + } + pos = start.saturating_add(size as usize); + } + Ok(()) +} + impl Plugin { /// Validates and loads a module: checks the ABI version and reads the manifest. pub fn load(bytes: &[u8], limits: Limits) -> Result { @@ -124,6 +160,7 @@ impl Plugin { if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } + check_code_section(bytes)?; let mut config = Config::default(); config.consume_fuel(true).enforced_limits(EnforcedLimits::strict()).set_max_recursion_depth(limits.max_recursion_depth.max(16)); let engine = Engine::new(&config); diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 61ee32791f..17e352982e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -219,6 +219,25 @@ fn malformed_and_oversized_modules_are_refused() { assert!(matches!(e, Error::Abi(_)), "{e}"); } +#[test] +fn a_code_section_claiming_no_functions_but_many_bytes_is_refused() { + // Header, then a code section (id 10) declaring 2000 bytes whose function count is 0, cut off + // after the count (a truncated download) or padded to its full size. The spec makes the + // count's own byte the whole section; wasmi's strict limits divided the size by the count. + let truncated = b"\0asm\x01\0\0\0\x0a\xd0\x0f\x00".to_vec(); + let mut padded = truncated.clone(); + padded.resize(padded.len() + 1999, 0); + // The same section after a valid empty one: a duplicate reaches the division before validation. + let mut second = b"\0asm\x01\0\0\0\x0a\x01\x00".to_vec(); + second.extend_from_slice(&padded[8..]); + for (name, bytes) in [("truncated", truncated), ("padded", padded), ("second", second)] { + assert!(matches!(Plugin::load(&bytes, Limits::default()), Err(Error::Module(_))), "{name}"); + } + // An empty code section (count 0, nothing after it) is valid; it fails only for the missing ABI exports. + let empty = b"\0asm\x01\0\0\0\x0a\x01\x00"; + assert!(matches!(Plugin::load(empty, Limits::default()), Err(Error::Abi(_)))); +} + #[test] fn budgets_stop_runaway_plugins() { let spin = ok_module("(loop $l (br $l)) (i32.const 0)"); From 4850487ecf9b315186a3c0906a8dbf56c7e369cd Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 15:01:52 +0100 Subject: [PATCH 68/73] =?UTF-8?q?History=20panel=20menu:=20History=20Optio?= =?UTF-8?q?ns=E2=80=A6=20opens=20its=20dialog=20(#3535)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main's History panel menu (#2966) showed History Options… greyed until the dialog existed; it now runs history.options, which without params opens the dialog. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/history_menu_ui.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/history_menu_ui.rs index 6e3e197662..245fa986d8 100644 --- a/crates/ui-egui/src/history_menu_ui.rs +++ b/crates/ui-egui/src/history_menu_ui.rs @@ -19,8 +19,8 @@ pub const ITEMS: &[(&str, Option<&str>)] = &[ ("Clear History", Some("history.clear")), ("New Document", Some("history.newDocument")), ("---", None), - // The History Options dialog is not built yet. - ("History Options…", None), + // Without params `history.options` opens the History Options dialog (#3535). + ("History Options…", Some("history.options")), ("---", None), ("Close", Some("window.panel.close")), ]; @@ -63,7 +63,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let Some(cmd) = clicked else { return }; ui.close(); let (cmd, params) = resolve(cmd, snapshot); - if let Err(e) = app.run(cmd, params) { + // History Options… opens its dialog, as the menu bar's command does. + let result = crate::history_options_ui::menu(app, cmd, ¶ms).unwrap_or_else(|| app.run(cmd, params)); + if let Err(e) = result { app.ui.status = e; app.ui.status_error = true; } @@ -109,7 +111,7 @@ mod tests { let mut h = harness(app()); assert_eq!(states(&h), (4, 0)); assert!(is_disabled(&h, "Step Forward") && !is_disabled(&h, "Step Backward")); - assert!(is_disabled(&h, "History Options…"), "not built yet: greyed"); + assert!(!is_disabled(&h, "History Options…")); assert!(!is_disabled(&h, "New Snapshot…")); click(&mut h, "Step Backward"); assert_eq!(states(&h), (3, 1)); @@ -126,6 +128,9 @@ mod tests { click(&mut h, "New Document"); assert_eq!(h.state().session.documents().len(), 2); assert!(!h.state().ui.status_error); + click(&mut h, "History Options…"); + assert_eq!(h.state().ui.dialogs.len(), 1, "History Options… opens its dialog"); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); } #[test] @@ -188,10 +193,12 @@ mod tests { } #[test] - fn without_a_document_only_close_is_enabled() { + fn without_a_document_only_close_and_history_options_are_enabled() { let h = harness(PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())); for &(label, cmd) in ITEMS.iter().filter(|(l, _)| *l != "---") { - assert_eq!(is_disabled(&h, label), cmd != Some("window.panel.close"), "{label}"); + // History Options are preferences, not part of a document. + let on = matches!(cmd, Some("window.panel.close" | "history.options")); + assert_eq!(is_disabled(&h, label), !on, "{label}"); } } } From 4531fabc75ec1ba3d1edbc82505fd4ba348a063c Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 26 Oct 2026 15:45:02 +0100 Subject: [PATCH 69/73] CMYK: the test reference keeps a fully covered type pixel's ink exact (#9688) The per-pixel reference mixed a type layer's fully covering pixel through the type gamma round trip, which leaves white one float step short of no ink (1 - 0.99999994). Vivid Light jumps exactly there (a source at full brightness gives full brightness, anything below over no brightness gives none), so a white glyph clipped onto a Vivid Light group over magenta became full magenta in the reference, while the compositor (which keeps covered pixels exact, like normal_gamma) gave no ink. The reference now treats a fully covering source like the compositor and the identity it is: the source's ink exactly. Adds a named regression test with the shrunk document and a neighbour test over Vivid/Linear/Pin Light, Hard Mix, Color Dodge/Burn, Normal, Multiply and Screen with type or pixels clipped, plus the proptest seed. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../proptest-regressions/cmyk_tests.txt | 1 + crates/compose/src/cmyk_tests.rs | 64 ++++++++++++++++++- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/compose/proptest-regressions/cmyk_tests.txt b/crates/compose/proptest-regressions/cmyk_tests.txt index 2f3a9c3fb8..2498f3013c 100644 --- a/crates/compose/proptest-regressions/cmyk_tests.txt +++ b/crates/compose/proptest-regressions/cmyk_tests.txt @@ -7,3 +7,4 @@ cc a795914e4492bef1e662315563d48d54f09030c48e046df95329465c86dde4b4 # shrinks to s = Spec { w: 4, h: 6, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [1.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 1.0105422, 0.0, 0.7] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }] } cc e14b02709a87770da2637c28678c4fa761b5628f402e0c6d60fe66f1aa4d4bfa # shrinks to s = Spec { w: 3, h: 2, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Group { children: [Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 0.3, 0.0, 0.7] }), blend: Dissolve, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.8972109, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } cc 4eeba1f8db987228717b932b82d043d61e82fd897a33ea9e2ce68d6c61d7f491 # shrinks to s = Spec { w: 3, h: 5, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 0.026626235, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Invert), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } +cc 33fb5c528e97f31669a82a4634930230f903c97e58ce59fc88fd733ac097089c # shrinks to s = Spec { w: 6, h: 4, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 5, y1: 3 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: VividLight, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Text, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: true, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } diff --git a/crates/compose/src/cmyk_tests.rs b/crates/compose/src/cmyk_tests.rs index 3e28fccd7e..44b265c8dd 100644 --- a/crates/compose/src/cmyk_tests.rs +++ b/crates/compose/src/cmyk_tests.rs @@ -105,8 +105,10 @@ fn over_text(b: Cmyka, s: Cmyka, opacity: f32) -> Cmyka { let dec = |v: f32| 1.0 - photocraft_color::convert::linear_to_srgb(v.max(0.0).powf(gamma)); let mut o = [0.0; 5]; for i in 0..4 { - // Mixing an ink with itself (or with nothing) leaves it exactly as it is. - o[i] = if b[4] <= 0.0 || b[i] == s[i] { s[i] } else { dec((1.0 - sa) * b[4] / a * enc(b[i]) + sa / a * enc(s[i])) }; + // Mixing an ink with itself, with nothing, or over a backdrop it covers fully leaves it + // exactly as it is (the round trip through the gamma space can move it by a rounding + // step, which a mode that jumps at no ink or full ink turns into a whole ink). + o[i] = if b[4] <= 0.0 || sa >= 1.0 || b[i] == s[i] { s[i] } else { dec((1.0 - sa) * b[4] / a * enc(b[i]) + sa / a * enc(s[i])) }; } o[4] = a; o @@ -394,6 +396,64 @@ fn isolated_groups_keep_the_special_fill_rule() { } } +/// White type clipped onto an isolated Vivid Light group over full magenta (#9688): the glyph +/// covers its pixel, so the group shows exactly no ink there, and Vivid Light with no ink (full +/// brightness) gives no ink whatever the backdrop. Mixing the covered pixel through the type +/// gamma would leave a rounding step of ink, which Vivid Light turns into full magenta. +#[test] +fn type_clipped_to_a_vivid_light_group_covers_exactly() { + let mut inner = Layer::new("f", LayerContent::Fill(photocraft_doc::Fill::Solid(cmyk_color([0.0, 1.0, 0.0, 0.0], 1.0)))); + inner.blend = BlendMode::Normal; + let mut vivid = Layer::group("vivid", vec![inner]); + vivid.blend = BlendMode::VividLight; + let mut glyph = text_layer(&[(Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 0.0, 1.0])]); + glyph.clipped = true; + let outer = Layer::group("outer", vec![layer(&[(Rect::new(0, 0, 5, 3), [0.0, 1.0, 0.0, 0.0, 1.0])]), vivid, glyph]); + let mut d = doc(6, 4); + d.layers.push(outer); + assert!(supports(&d)); + let got = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported")); + assert_eq!(got.px[0], [0.0, 0.0, 0.0, 0.0, 1.0], "white glyph in Vivid Light"); + // Magenta in Vivid Light onto magenta stays magenta. + assert_eq!(got.px[1], [0.0, 1.0, 0.0, 0.0, 1.0], "beside the glyph"); + assert_matches_reference(&d); +} + +/// The same structure in the neighbouring modes, with type or pixels clipped (fully covering and +/// at a partly covered edge), onto inks that sit at the jumps of the modes that have them. +#[test] +fn layers_clipped_to_isolated_groups_match_the_reference_in_every_mode() { + use BlendMode as B; + for mode in [B::VividLight, B::LinearLight, B::PinLight, B::HardMix, B::ColorDodge, B::ColorBurn, B::Normal, B::Multiply, B::Screen] { + for text in [false, true] { + for (backdrop, ink) in [([0.0, 1.0, 0.0, 0.0], [0.0; 4]), ([1.0, 0.0, 1.0, 1.0], [1.0; 4]), ([0.0, 1.0, 0.0, 0.0], [0.0, 0.3, 1.0, 0.0])] { + let mut inner = Layer::new("f", LayerContent::Fill(photocraft_doc::Fill::Solid(cmyk_color(backdrop, 1.0)))); + inner.blend = BlendMode::Normal; + let mut group = Layer::group("g", vec![inner]); + group.blend = mode; + let [c, m, y, k] = ink; + let rects = [(Rect::new(0, 0, 2, 2), [c, m, y, k, 1.0]), (Rect::new(2, 0, 3, 2), [c, m, y, k, 0.5])]; + let mut clip = if text { text_layer(&rects) } else { layer(&rects) }; + clip.clipped = true; + let [bc, bm, by, bk] = backdrop; + let outer = Layer::group("outer", vec![layer(&[(Rect::new(0, 0, 4, 2), [bc, bm, by, bk, 1.0])]), group, clip]); + let mut d = doc(4, 3); + d.layers.push(outer); + assert!(supports(&d), "{mode:?}"); + assert_matches_reference(&d); + } + } + } + // Onto a pass-through group, clipped layers take the RGB compositor's isolated rendering. + let mut pass = Layer::group("pass", vec![layer(&[(Rect::new(0, 0, 2, 2), [0.0, 1.0, 0.0, 0.0, 1.0])])]); + pass.blend = BlendMode::PassThrough; + let mut clip = text_layer(&[(Rect::new(0, 0, 1, 1), [0.0; 5])]); + clip.clipped = true; + let mut d = doc(2, 2); + d.layers.extend([pass, clip]); + assert!(!supports(&d)); +} + #[test] fn unsupported_documents_fall_back() { let simple = || { From 3b6e93b8f13204a238383035113edb7a3f3c586e Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 27 Oct 2026 02:51:30 +0100 Subject: [PATCH 70/73] Adapt to main: color wheel test uses the craft-ui dock area Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/color_panel_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/color_panel_tests.rs b/crates/ui-egui/src/color_panel_tests.rs index 204d07e5aa..5dd64cb77b 100644 --- a/crates/ui-egui/src/color_panel_tests.rs +++ b/crates/ui-egui/src/color_panel_tests.rs @@ -424,7 +424,7 @@ fn color_wheel_fits_the_default_color_group() { let mut h = Harness::builder().with_size(vec2(1440.0, 1200.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - crate::panels::right_dock(app, ui); + crate::panels::dock_area(app, ui); egui::CentralPanel::default().show(ui, |_| {}); } }, @@ -432,7 +432,7 @@ fn color_wheel_fits_the_default_color_group() { ); PhotocraftApp::setup_context(&h.ctx, kind); h.run_steps(4); - let group = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == Group::Color).unwrap().1; + let group = crate::panel_docking::probe::native_group_rect(h.state(), &h.ctx, Group::Color).unwrap(); assert!((group.height() - Group::Color.default_height()).abs() < 0.5, "{kind:?}: Color group {group:?}"); let wheel = h.query_by_label("Color Wheel").unwrap_or_else(|| panic!("{kind:?}: no Color Wheel")).rect(); // The group's scroll area ends at least 8 pt above its bottom edge (the card's bottom margin). From f3afeaaf540b1bc73e092cc3638592afd538e615 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 26 Oct 2026 23:39:59 -0700 Subject: [PATCH 71/73] Refresh the open Print dialog after spooler contention ends Retry printer enumeration after a busy result and restore the available printer controls without reopening the dialog. Cover opening and drawing the dialog while the spooler is held, then drawing it after release. --- crates/engine/src/cmd/print_cmds/tests.rs | 20 +++++---- crates/ui-egui/src/dialogs/file_ui/print.rs | 28 +++++++++--- crates/ui-egui/src/dialogs/file_ui/tests.rs | 44 ++++++++++++++++++- crates/ui-egui/tests/it/custom_print_paper.rs | 2 +- 4 files changed, 78 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index 052aba8f2d..6208b53ec5 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -881,15 +881,17 @@ fn uncached_listings_do_not_wait(cache_other: bool) { assert_eq!(asked.load(Ordering::SeqCst), 0); assert_eq!(listed, printers_answer(Vec::new())); assert_eq!(listed_rgb, Err(craft_print::rgb::PrintError::Unsupported)); - let listed = printers_without_waiting(&mut s); - let listed_rgb = rgb_printers_without_waiting(&s); - assert_eq!(listed["printers"], json!([{"name": "Proofing", "default": true}])); - let names = listed_rgb.map(|list| list.into_iter().map(|p| p.name).collect::>()); - if cfg!(windows) { - assert_eq!(names, Ok(vec!["Proofing".to_string()])); - } else { - assert_eq!(names, Err(craft_print::rgb::PrintError::Unsupported)); - } + with_spooler(|| { + let listed = printers_without_waiting(&mut s); + let listed_rgb = rgb_printers_without_waiting(&s); + assert_eq!(listed["printers"], json!([{"name": "Proofing", "default": true}])); + let names = listed_rgb.map(|list| list.into_iter().map(|p| p.name).collect::>()); + if cfg!(windows) { + assert_eq!(names, Ok(vec!["Proofing".to_string()])); + } else { + assert_eq!(names, Err(craft_print::rgb::PrintError::Unsupported)); + } + }); } /// Spooling tests run in a child process: `disable_printing` is process-wide and a test above diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index fb5d63796d..9a826611e6 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -31,8 +31,6 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { let mut f = Map::new(); f.insert("__print".into(), json!(true)); f.insert("__label".into(), json!("PhotoCraft Print Settings")); - let printers = photocraft_engine::print_cmds::printers_without_waiting(&mut app.session); - f.insert("__systemPrinters".into(), printers["printers"].clone()); // The settings of the last print, also from an earlier session (#7410). if let Some(Value::Object(m)) = photocraft_engine::print_cmds::last_print(&app.session) { f.extend(m); @@ -62,17 +60,31 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { ] { f.entry(k.to_string()).or_insert(v); } - // Windows: the system's printers, and the paper from the chosen printer's driver settings. + refresh_printers(app, &mut f); + app.ui.open_dialog(DialogKind::Command, f) +} + +fn refresh_printers(app: &mut PhotocraftApp, f: &mut Map) { + if photocraft_engine::print_cmds::try_with_spooler(|| take_printer_lists(app, f)).is_some() { + f.remove("__printerListingPending"); + } else { + take_printer_lists(app, f); + f.insert("__printerListingPending".into(), json!(true)); + } +} + +fn take_printer_lists(app: &mut PhotocraftApp, f: &mut Map) { + let printers = photocraft_engine::print_cmds::printers_without_waiting(&mut app.session); + f.insert("__systemPrinters".into(), printers["printers"].clone()); if let Ok(list) = photocraft_engine::print_cmds::rgb_printers_without_waiting(&app.session) { f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); let known = |n: &str| list.iter().any(|p| p.name == n); - if !known(&s(&f, "printer", "")) { + if !known(&s(f, "printer", "")) { let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default(); f.insert("printer".into(), json!(fallback)); f.remove("printerSettings"); } } - app.ui.open_dialog(DialogKind::Command, f) } /// Whether the driver's paper, as `driver_page` took it, is wider than tall: the Orientation @@ -288,6 +300,12 @@ pub(super) fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, /// Dragging the visible image updates dialog offsets live from a fixed gesture origin; /// the position row stays present while centered so switching to manual cannot move the page. pub(super) fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { + if b(f, "__printerListingPending", false) { + refresh_printers(app, f); + if b(f, "__printerListingPending", false) { + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } + } let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; // PDF exports and previews retain editable paper on Windows too. Only a real native diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index d68adc24eb..77a0619df2 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1,5 +1,47 @@ use super::*; +#[test] +fn print_dialog_retries_an_uncached_printer_list_after_the_spooler_is_released() { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + let (mut app, ctx) = app(); + let asked = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&asked); + app.session.printer_source = Some(Arc::new(move || { + counted.fetch_add(1, Ordering::SeqCst); + vec![craft_print::Printer { name: "Retry printer".into(), default: true, two_sided: None, description: String::new() }] + })); + let (held_tx, held) = std::sync::mpsc::channel(); + let (release, released_rx) = std::sync::mpsc::channel::<()>(); + let released = Arc::new(AtomicBool::new(false)); + let done = Arc::clone(&released); + let holder = std::thread::spawn(move || { + photocraft_engine::print_cmds::with_spooler(|| { + held_tx.send(()).unwrap(); + let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); + done.store(true, Ordering::SeqCst); + }); + }); + held.recv().unwrap(); + let id = open_print(&mut app); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.insert("dryRun".into(), json!(true)); + ctx.run_ui(Default::default(), |ui| print_body(&mut app, ui, &mut fields, id)).textures_delta.clear(); + let waited = released.load(Ordering::SeqCst); + let calls_while_busy = asked.load(Ordering::SeqCst); + let _ = release.send(()); + holder.join().unwrap(); + assert!(!waited, "opening or drawing Print waited for the spooler"); + assert_eq!(calls_while_busy, 0); + assert_eq!(fields["__systemPrinters"], json!([])); + photocraft_engine::print_cmds::with_spooler(|| { + ctx.run_ui(Default::default(), |ui| print_body(&mut app, ui, &mut fields, id)).textures_delta.clear(); + assert_eq!(fields["__systemPrinters"], json!([{"name": "Retry printer", "default": true}])); + assert_eq!(fields.get("__printers"), cfg!(windows).then(|| json!(["Retry printer"])).as_ref()); + assert!(!fields.contains_key("__printerListingPending")); + assert!(asked.load(Ordering::SeqCst) > 0); + }); +} + #[test] fn driver_calls_do_not_wait_while_the_spooler_is_busy() { use std::sync::atomic::{AtomicBool, Ordering}; @@ -471,7 +513,7 @@ fn printer_menu_lists_the_spooler_printers_after_the_default() { assert_eq!(printer_options(None, "").len(), 1); // The dialog asks the engine, and the list never reaches file.print's params. let (mut app, ctx) = app(); - let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let id = photocraft_engine::print_cmds::with_spooler(|| crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap()); let f = &app.ui.dialog_mut(id).unwrap().fields; assert_eq!(f["__systemPrinters"], json!([{"name": "Test printer", "default": true}])); assert_eq!(f.get("__printers"), cfg!(windows).then(|| json!(["Test printer"])).as_ref()); diff --git a/crates/ui-egui/tests/it/custom_print_paper.rs b/crates/ui-egui/tests/it/custom_print_paper.rs index afba9d0177..d6c66a21e3 100644 --- a/crates/ui-egui/tests/it/custom_print_paper.rs +++ b/crates/ui-egui/tests/it/custom_print_paper.rs @@ -11,7 +11,7 @@ fn app() -> (PhotocraftApp, u64) { vec![craft_print::Printer { name: "Test native printer".into(), default: true, two_sided: None, description: String::new() }] })); app.run("file.new", json!({"width": 120, "height": 80, "name": "Custom paper"})).unwrap(); - let id = open_print(&mut app); + let id = photocraft_engine::print_cmds::with_spooler(|| open_print(&mut app)); assert_no_system_listing(); let fields = &mut app.ui.dialog_mut(id).unwrap().fields; // Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog. From 7e4aa1f5cfb2c2f1698bb3b4e12e6e6b74cb235d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 06:38:33 -0700 Subject: [PATCH 72/73] Preserve print settings when the cached printer list is empty --- crates/ui-egui/src/dialogs/file_ui/print.rs | 2 +- crates/ui-egui/src/dialogs/file_ui/tests.rs | 47 +++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 9a826611e6..72037c85a2 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -79,7 +79,7 @@ fn take_printer_lists(app: &mut PhotocraftApp, f: &mut Map) { if let Ok(list) = photocraft_engine::print_cmds::rgb_printers_without_waiting(&app.session) { f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); let known = |n: &str| list.iter().any(|p| p.name == n); - if !known(&s(f, "printer", "")) { + if !list.is_empty() && !known(&s(f, "printer", "")) { let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default(); f.insert("printer".into(), json!(fallback)); f.remove("printerSettings"); diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index 77a0619df2..534796fbff 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1,5 +1,52 @@ use super::*; +#[cfg(windows)] +#[test] +fn print_dialog_keeps_saved_settings_when_the_cached_printer_list_is_empty() { + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut app, ctx) = app(); + let available = Arc::new(AtomicBool::new(false)); + let listed = Arc::clone(&available); + app.session.printer_source = Some(Arc::new(move || { + if listed.load(Ordering::SeqCst) { + vec![craft_print::Printer { name: "Saved printer".into(), default: true, two_sided: None, description: String::new() }] + } else { + Vec::new() + } + })); + app.session.prefs.edit(|p| { + p.dialogs.insert(photocraft_engine::print_cmds::REMEMBERED.into(), json!({"printer": "Saved printer", "printerSettings": "0011"})); + }); + let mut lister = photocraft_engine::Session::new(); + lister.printer_source = app.session.printer_source.clone(); + let (held_tx, held) = std::sync::mpsc::channel(); + let (release, released_rx) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + photocraft_engine::print_cmds::with_spooler(|| { + assert!(photocraft_engine::print_cmds::rgb_printers(&lister).unwrap().is_empty()); + available.store(true, Ordering::SeqCst); + held_tx.send(()).unwrap(); + let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); + }); + }); + held.recv().unwrap(); + let id = open_print(&mut app); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + let before_retry = (fields.get("printer").cloned(), fields.get("printerSettings").cloned()); + let pending = fields.get("__printerListingPending").cloned(); + let _ = release.send(()); + holder.join().unwrap(); + assert_eq!(pending, Some(json!(true))); + assert_eq!(before_retry, (Some(json!("Saved printer")), Some(json!("0011")))); + fields.insert("dryRun".into(), json!(true)); + photocraft_engine::print_cmds::with_spooler(|| { + ctx.run_ui(Default::default(), |ui| print_body(&mut app, ui, &mut fields, id)).textures_delta.clear(); + assert_eq!(fields["printer"], "Saved printer"); + assert_eq!(fields["printerSettings"], "0011"); + assert!(!fields.contains_key("__printerListingPending")); + }); +} + #[test] fn print_dialog_retries_an_uncached_printer_list_after_the_spooler_is_released() { use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; From 0a8dcd07af8e8285ad5e78f3cfcb2a41f9e1389d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 08:04:02 -0700 Subject: [PATCH 73/73] Retry printer page setup after spooler contention --- crates/ui-egui/src/dialogs/file_ui/print.rs | 8 +++-- crates/ui-egui/src/dialogs/file_ui/tests.rs | 33 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 72037c85a2..0a596a307b 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -317,8 +317,12 @@ pub(super) fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map None }; if printers.is_some() { - if !b(f, "__driverPageInitialized", false) && driver_page(f) { - f.insert("__driverPageInitialized".into(), json!(true)); + if !b(f, "__driverPageInitialized", false) { + if driver_page(f) { + f.insert("__driverPageInitialized".into(), json!(true)); + } else { + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } } } else { // PDF output and previews have no driver page: Scale to Fit Media uses the paper. diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index 534796fbff..19f7b1ceff 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -1,5 +1,38 @@ use super::*; +#[test] +fn busy_driver_page_requests_a_retry_without_input() { + let (mut app, ctx) = app(); + let mut fields = json!({"printer": "Test printer", "__printers": ["Test printer"], "paper": "letter"}).as_object().unwrap().clone(); + let (held_tx, held) = std::sync::mpsc::channel(); + let (release, released_rx) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + photocraft_engine::print_cmds::with_spooler(|| { + held_tx.send(()).unwrap(); + let _ = released_rx.recv_timeout(std::time::Duration::from_secs(5)); + }); + }); + held.recv().unwrap(); + let mut delay = std::time::Duration::MAX; + for _ in 0..6 { + let mut output = ctx.run_ui(Default::default(), |ui| print_body(&mut app, ui, &mut fields, 1)); + delay = output.viewport_output[&egui::ViewportId::ROOT].repaint_delay; + output.textures_delta.clear(); + } + let busy = fields.get("__pageError").cloned(); + let initialized = fields.get("__driverPageInitialized").cloned(); + let _ = release.send(()); + holder.join().unwrap(); + assert_eq!(busy, Some(json!(photocraft_engine::print_cmds::SPOOLER_BUSY))); + assert_ne!(initialized, Some(json!(true))); + assert!(delay <= std::time::Duration::from_millis(100), "busy driver repaint delay: {delay:?}"); + photocraft_engine::print_cmds::with_spooler(|| { + ctx.run_ui(Default::default(), |ui| print_body(&mut app, ui, &mut fields, 1)).textures_delta.clear(); + assert_eq!(fields.get("__driverPageInitialized"), Some(&json!(true))); + assert_ne!(fields.get("__pageError"), Some(&json!(photocraft_engine::print_cmds::SPOOLER_BUSY))); + }); +} + #[cfg(windows)] #[test] fn print_dialog_keeps_saved_settings_when_the_cached_printer_list_is_empty() {