From 80d7c000a00abcfb737fe03f55e1a7c02e82c903 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 22:18:14 +0000 Subject: [PATCH 1/2] Engine split step 4: damage helpers to crates/engine-core/src/damage.rs The redraw-area helpers (step_damage and the rest of cmd/layer_multi_cmds/damage.rs) are pipeline logic that dispatch, edit, undo and redo use, so they leave the module the model crate will take. layer_multi_cmds keeps its public re-exports. --- crates/engine-core/src/cmd/layer_multi_cmds.rs | 8 ++------ .../engine-core/src/cmd/layer_multi_cmds/align.rs | 2 +- .../engine-core/src/cmd/layer_multi_cmds/tests.rs | 2 +- .../src/{cmd/layer_multi_cmds => }/damage.rs | 6 +++--- crates/engine-core/src/doc_state.rs | 6 +++--- crates/engine-core/src/jobs.rs | 6 +++--- crates/engine-core/src/lib.rs | 1 + crates/engine-core/src/session.rs | 3 +-- crates/engine-core/src/session/execute.rs | 13 +++++-------- crates/engine-core/src/session/history.rs | 8 ++++---- crates/engine-core/src/session/layers.rs | 4 ++-- 11 files changed, 26 insertions(+), 33 deletions(-) rename crates/engine-core/src/{cmd/layer_multi_cmds => }/damage.rs (99%) diff --git a/crates/engine-core/src/cmd/layer_multi_cmds.rs b/crates/engine-core/src/cmd/layer_multi_cmds.rs index be2bfa4ce3..109a7204c8 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds.rs @@ -6,7 +6,7 @@ //! changing it never adds a history step. Every structural change below is one history step. use photocraft_color::PixelFormat; -use photocraft_doc::{Document, Layer, LayerContent, LayerId, VideoData}; +use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -14,16 +14,12 @@ use crate::commands::{CommandSpec, int_i32}; use crate::{DocState, EngineError, Result, Session}; mod align; -mod damage; mod moves; mod selection; mod structure; +pub use crate::damage::{layer_bounds, same_pixels, selection_only_change, step_damage}; use align::{align, distribute}; -pub(crate) use damage::grow_hint; -#[cfg(any(test, debug_assertions))] -pub(crate) use damage::{hint_misses, small_change_pct}; -pub use damage::{layer_bounds, same_pixels, selection_only_change, step_damage}; use moves::link_groups; pub(crate) use moves::shift_surface; #[cfg(test)] diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index e33b11b24a..07fcdf4f03 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -1,7 +1,7 @@ -use super::damage::align_bounds; use super::moves::{move_layers, with_links}; use super::selection::{selected, top_level}; use super::{Document, EngineError, LayerId, Rect, Result, Session, Value, bad, json}; +use crate::damage::align_bounds; #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Edge { diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs index 69918e5b9a..0c579d74a3 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/tests.rs @@ -1,7 +1,7 @@ use photocraft_color::SampleType; -use super::damage::{align_bounds, shape_pixel_bounds}; use super::*; +use crate::damage::{align_bounds, shape_pixel_bounds}; #[test] fn merge_with_background_preserves_background() { diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/damage.rs b/crates/engine-core/src/damage.rs similarity index 99% rename from crates/engine-core/src/cmd/layer_multi_cmds/damage.rs rename to crates/engine-core/src/damage.rs index 83ea69e2f0..9897e3e54e 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine-core/src/damage.rs @@ -1,7 +1,7 @@ use photocraft_color::{PixelFormat, SampleType}; use photocraft_compose::Ancestors; - -use super::{Document, Layer, LayerContent, LayerId, Rect, VideoData}; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, VideoData}; +use photocraft_geom::Rect; /// Calls `f` with the rect of every tile that differs between two surfaces of the same format and /// default pixel: a tile only one side has, or a different copy-on-write tile pointer at the same @@ -853,7 +853,7 @@ const SHAPE_BOUNDS_BAND_PX: u64 = 1 << 20; /// everything it can draw (its path, stroke and feather), unclipped, and measured from that. A fill /// that shows everywhere (an inverted path, or below 100 % density) has no extent of its own and /// keeps the canvas-clipped measure (`None`). -pub(super) fn shape_pixel_bounds(sh: &photocraft_doc::ShapeLayer, canvas: Rect, sample: SampleType) -> Option { +pub(crate) fn shape_pixel_bounds(sh: &photocraft_doc::ShapeLayer, canvas: Rect, sample: SampleType) -> Option { if unbounded_fill(sh) { return None; } diff --git a/crates/engine-core/src/doc_state.rs b/crates/engine-core/src/doc_state.rs index 8ed80a30df..cdf1593f7d 100644 --- a/crates/engine-core/src/doc_state.rs +++ b/crates/engine-core/src/doc_state.rs @@ -1,4 +1,4 @@ -use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, layer_multi_cmds, symmetry_cmds}; +use super::{Arc, Document, History, LayerId, LayerTarget, channel_cmds, float_cmds, history_cmds, symmetry_cmds}; /// Per-document editing state. Plain data: the session holds each in a `Tracked`, whose revision moves with every /// write, view state included. @@ -224,7 +224,7 @@ impl DocState { /// (marquee, lasso, Magic Wand, Quick / Object Selection, Select › …) is a history step but /// not an edit, so it neither marks the file modified nor makes closing ask to save. pub(crate) fn keeps_clean(&self, before: &Document) -> bool { - self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc) + self.saved_revision == self.revision && crate::damage::selection_only_change(before, &self.doc) } /// Damage since `revision`, or `None` when a revision is missing or has unknown damage. pub fn damage_since(&self, revision: u64) -> Option { @@ -285,7 +285,7 @@ impl DocState { if r.is_empty() { Some(r) } else if bounded(&self.doc.layers, 0) { - Some(layer_multi_cmds::grow_hint(&self.doc, r)) + Some(crate::damage::grow_hint(&self.doc, r)) } else { None } diff --git a/crates/engine-core/src/jobs.rs b/crates/engine-core/src/jobs.rs index 9f7227f106..b03e0eb36e 100644 --- a/crates/engine-core/src/jobs.rs +++ b/crates/engine-core/src/jobs.rs @@ -1911,7 +1911,7 @@ impl Session { /// The one place a command's redraw area spans more than one revision. A command that moved /// the active document's revision more than once (Paste Into, Stroke Path, a compound, a - /// script) reports what changed since it began, [`layer_multi_cmds::step_damage`] of the + /// script) reports what changed since it began, [`crate::damage::step_damage`] of the /// document before and after, measured from the revision before it. A single-revision command /// keeps the damage it reported. Debug and test builds also count a whole-document redraw of /// a small change ([`Session::whole_redraws`]). @@ -1922,13 +1922,13 @@ impl Session { } let Some(st) = self.active_mut() else { return }; if st.revision - from > 1 { - st.last_damage = crate::layer_multi_cmds::step_damage(before, &st.doc); + st.last_damage = crate::damage::step_damage(before, &st.doc); st.damage_span = Some((from, st.revision)); st.record_damage(); } #[cfg(any(test, debug_assertions))] if st.last_damage.is_none() - && let Some(pct) = crate::layer_multi_cmds::small_change_pct(before, &st.doc) + && let Some(pct) = crate::damage::small_change_pct(before, &st.doc) { eprintln!("warning: {id}: redraws the whole document but changed {pct}% of it"); self.whole_redraws += 1; diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 4bbdc0bc43..0137f329f8 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -16,6 +16,7 @@ mod channel_clip; mod clip_group; pub mod color_channels; mod crop_fill; +mod damage; pub mod display_color; pub mod doc_path; pub mod filters; diff --git a/crates/engine-core/src/session.rs b/crates/engine-core/src/session.rs index d1f360e573..8489892b5b 100644 --- a/crates/engine-core/src/session.rs +++ b/crates/engine-core/src/session.rs @@ -1,8 +1,7 @@ use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::{ - Arc, Document, LayerId, LayerTarget, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds, smart_cmds, - type_cmds, + Arc, Document, LayerId, LayerTarget, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, retouch_cmds, smart_cmds, type_cmds, }; mod documents; diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index 29d0b91d6f..438fe046c1 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -1,8 +1,5 @@ use super::history::{fix_selection, visibility_changes}; -use super::{ - Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, layer_multi_cmds, retouch_cmds, - smart_cmds, -}; +use super::{Arc, Document, EngineError, LayerId, Result, Session, Value, brush_cmds, channel_cmds, commands, hidden_target, jobs, retouch_cmds, smart_cmds}; use crate::color_channels; impl Session { @@ -346,7 +343,7 @@ impl Session { // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a // duplicate or a paste), and everything when that can't be bounded. A command may still // report its own, tighter damage after this. - let damage = layer_multi_cmds::step_damage(&before, &st.doc); + let damage = crate::damage::step_damage(&before, &st.doc); let keep_clean = st.keeps_clean(&before); #[cfg(any(test, debug_assertions))] let hint_before = before.clone(); @@ -386,7 +383,7 @@ impl Session { } /// A command's own rect for the pixels its latest [`Session::edit`] changed: sub-tile precise - /// for a brush dab, where the edit's own damage ([`layer_multi_cmds::step_damage`]) has tile + /// for a brush dab, where the edit's own damage ([`crate::layer_multi_cmds::step_damage`]) has tile /// precision. The redraw area becomes the intersection of the two, so a hint can only narrow /// it (or bound a change `step_damage` can't). The hint is first grown as `step_damage` grows /// a change (by a mask's feather and by effects, `grow_hint`), so the intersection keeps a @@ -398,7 +395,7 @@ impl Session { && let Some(st) = self.active() && st.doc.id == before.id { - let misses = layer_multi_cmds::hint_misses(&before, &st.doc, rect); + let misses = crate::damage::hint_misses(&before, &st.doc, rect); if misses > 0 { let step = st.history.undo_label().unwrap_or("?"); eprintln!("warning: `{step}` hinted damage {rect:?} that misses {misses} changed tile(s); the canvas may not redraw them"); @@ -406,7 +403,7 @@ impl Session { } } let Some(st) = self.active_mut() else { return }; - let rect = layer_multi_cmds::grow_hint(&st.doc, rect); + let rect = crate::damage::grow_hint(&st.doc, rect); st.last_damage = Some(st.last_damage.map_or(rect, |d| d.intersect(&rect))); st.record_damage(); } diff --git a/crates/engine-core/src/session/history.rs b/crates/engine-core/src/session/history.rs index bb20488f77..cbfd25691c 100644 --- a/crates/engine-core/src/session/history.rs +++ b/crates/engine-core/src/session/history.rs @@ -1,5 +1,5 @@ use super::documents::fix_active; -use super::{Arc, DocState, Document, LayerId, LayerTarget, Session, channel_cmds, layer_multi_cmds}; +use super::{Arc, DocState, Document, LayerId, LayerTarget, Session, channel_cmds}; impl Session { /// Undo a document step or restore Clear History's rows and source without editing pixels. @@ -51,7 +51,7 @@ impl Session { } // 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); + let damage = crate::damage::step_damage(&d, &st.doc); let before = std::mem::replace(st.doc_mut(), d); let keep_clean = st.keeps_clean(&before); restore_target(st, layers); @@ -91,7 +91,7 @@ impl Session { 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); + let damage = crate::damage::step_damage(&st.doc, &d); let before = std::mem::replace(st.doc_mut(), d); let keep_clean = st.keeps_clean(&before); restore_target(st, layers); @@ -141,7 +141,7 @@ impl Session { if keep_visibility { carry_visibility(&st.doc, &mut d, &changed); } - let damage = layer_multi_cmds::step_damage(&d, &st.doc); + let damage = crate::damage::step_damage(&d, &st.doc); let before = std::mem::replace(st.doc_mut(), d); // Taking back a selection-only step keeps a clean document clean, as Undo does (#6865). let keep_clean = st.keeps_clean(&before); diff --git a/crates/engine-core/src/session/layers.rs b/crates/engine-core/src/session/layers.rs index 882bf845f8..a28d3b2dfe 100644 --- a/crates/engine-core/src/session/layers.rs +++ b/crates/engine-core/src/session/layers.rs @@ -1,5 +1,5 @@ use super::history::fix_selection; -use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, layer_multi_cmds, type_cmds}; +use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, type_cmds}; use crate::TypeLayerRef; impl Session { @@ -95,7 +95,7 @@ impl Session { st.saved_revision = st.revision; } // Only the refreshed layers' caches changed: their changed tiles. - st.last_damage = layer_multi_cmds::step_damage(&before, &st.doc); + st.last_damage = crate::damage::step_damage(&before, &st.doc); st.record_damage(); } busy From f0477a595f0e27c11f8f55b960f75c2088691abf Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 22:21:04 +0000 Subject: [PATCH 2/2] Engine split step 4: pipeline hooks Core runs every command; the steps that belong to crates above core now run as hooks those crates register with their command tables (Install.hooks, crates/engine-core/src/hooks.rs): request params (batch open), redirect (Last Filter), parameter checks (file.new values, filter params, through validate_params in dispatch and precheck), before the command (the floating selection drops), run params (Shape Blur's path), after the command (mask view, Fade, script events and slices, preset store sync), recorded steps keyed by command id with a default, step origin, journal coalescing, recording flush and preferences applied. install.rs registers every hook, grouped by the crate that will own it. Before an install there are no hooks, as the registry lists no commands. The recording predicates replayable, tool_stroke, shell_view_command and shell_save_command, and recorded_params, move to actions_record, beside the rest of the recording normalisation; actions_cmds re-exports the public ones. --- crates/engine-core/src/actions_record.rs | 73 ++++++++++++++++- crates/engine-core/src/cmd/actions_cmds.rs | 73 +---------------- crates/engine-core/src/cmd/float_cmds.rs | 11 +++ crates/engine-core/src/cmd/mask_view_cmds.rs | 11 +++ crates/engine-core/src/filters.rs | 22 +++++ crates/engine-core/src/filters_ext.rs | 8 ++ crates/engine-core/src/hooks.rs | 83 +++++++++++++++++++ crates/engine-core/src/install.rs | 41 ++++++++++ crates/engine-core/src/jobs.rs | 85 +++++++------------- crates/engine-core/src/lib.rs | 1 + crates/engine-core/src/prefs.rs | 5 +- crates/engine-core/src/registry.rs | 41 +++++++--- crates/engine-core/src/session/execute.rs | 10 +-- 13 files changed, 314 insertions(+), 150 deletions(-) create mode 100644 crates/engine-core/src/hooks.rs diff --git a/crates/engine-core/src/actions_record.rs b/crates/engine-core/src/actions_record.rs index da12c76a5a..69e87b3d65 100644 --- a/crates/engine-core/src/actions_record.rs +++ b/crates/engine-core/src/actions_record.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use photocraft_doc::{DocId, Document, LayerContent, LayerId}; -use serde_json::Value; +use serde_json::{Value, json}; use crate::Session; @@ -165,5 +165,76 @@ pub(crate) fn fold_keystroke(s: &mut Session, id: &str, params: &Value, previous Keystroke::Folded } +/// Replay commands and named action calls, excluding edits to the action definitions and the +/// already-expanded Again wrapper. +pub fn replayable(id: &str) -> bool { + // Again and Again on a Copy journal their concrete steps (`edit.transform`, after + // `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in + // the journal, so they fail where no transform ran yet, e.g. an action played in a new session. + // A Conditional is recorded with its predicate, not the branch it happened to play (or none), + // so playback evaluates the condition again on the current document (#7198, #7238). + matches!(id, "actions.play" | "actions.conditional") + || (!id.starts_with("actions.") + // Browse executes its steps through Session::execute, so those concrete + // commands are already journaled. Recording the wrapper as well replays + // every script edit twice (#3057). + && !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse") + && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal))) +} + +/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop +/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and +/// droplets write to their destination folder instead. +pub fn shell_save_command(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs") +} + +/// View-only menu commands recorded by the desktop shell. Headless playback reports +/// them as unsupported instead of silently dropping them; Batch and droplets skip them. +pub fn shell_view_command(id: &str) -> bool { + matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut") +} + +/// The point-based painting tools committed by the canvas; fills and gradients remain commands. +pub(crate) fn tool_stroke(id: &str) -> bool { + matches!( + id, + "paint.stroke" + | "paint.pencil" + | "paint.mixerBrush" + | "paint.colorReplacement" + | "paint.blur" + | "paint.sharpen" + | "paint.smudge" + | "paint.dodge" + | "paint.burn" + | "paint.sponge" + | "paint.cloneStamp" + | "paint.healingBrush" + | "paint.historyBrush" + | "paint.artHistoryBrush" + | "paint.patternStamp" + | "paint.backgroundEraser" + | "paint.spotHealing" + | "paint.remove" + ) +} + +/// Visibility gestures name a layer for replay, since document-local ids change on another image. +pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value { + if s.actions.recording.is_none() || id != "layer.setProps" || p.get("visible").is_none() { + return p; + } + let Some(st) = s.active() else { return p }; + let Some(layer) = p.get("layer").and_then(Value::as_u64).map(LayerId).or(st.active_layer).and_then(|id| st.doc.layer(id)) else { return p }; + let ordinal = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).position(|(_, _, l)| l.id == layer.id).unwrap_or(0); + if let Some(object) = p.as_object_mut() { + object.remove("layer"); + object.remove("coalesce"); + object.insert("_actionLayer".into(), json!({"name": layer.name, "ordinal": ordinal})); + } + p +} + #[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index 20a09a19ce..75e2d56da0 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -27,6 +27,8 @@ use crate::{EngineError, Result, Session}; pub use craft::automation::actions::{Action, ActionColor, ActionList, ActionStep, ActionsFile, moved_index}; mod history; +pub(crate) use crate::actions_record::tool_stroke; +pub use crate::actions_record::{replayable, shell_save_command, shell_view_command}; pub(crate) use history::ActionHistory; pub use history::{ActionHistoryContinuation, finish_pending_history, suspend_history}; pub(crate) use history::{before_edit as before_action_edit, begin_document_history, finish_document_history, history_rows, reconcile_history_removal}; @@ -128,22 +130,6 @@ impl ActionState { } } -/// Visibility gestures name a layer for replay, since document-local ids change on another image. -pub(crate) fn recorded_params(s: &Session, id: &str, mut p: Value) -> Value { - if s.actions.recording.is_none() || id != "layer.setProps" || p.get("visible").is_none() { - return p; - } - let Some(st) = s.active() else { return p }; - let Some(layer) = p.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).and_then(|id| st.doc.layer(id)) else { return p }; - let ordinal = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).position(|(_, _, l)| l.id == layer.id).unwrap_or(0); - if let Some(object) = p.as_object_mut() { - object.remove("layer"); - object.remove("coalesce"); - object.insert("_actionLayer".into(), json!({"name": layer.name, "ordinal": ordinal})); - } - p -} - /// Resolve the recorded visibility target identically in engine and shell playback, and drop /// the `.atn` event or Custom descriptor remembered for Save Actions: the command, its journal /// entry (Last Filter), a smart filter and the step's dialog never see it. @@ -198,30 +184,6 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { Ok(p) } -/// Replay commands and named action calls, excluding edits to the action definitions and the -/// already-expanded Again wrapper. -pub fn replayable(id: &str) -> bool { - // Again and Again on a Copy journal their concrete steps (`edit.transform`, after - // `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in - // the journal, so they fail where no transform ran yet, e.g. an action played in a new session. - // A Conditional is recorded with its predicate, not the branch it happened to play (or none), - // so playback evaluates the condition again on the current document (#7198, #7238). - matches!(id, "actions.play" | "actions.conditional") - || (!id.starts_with("actions.") - // Browse executes its steps through Session::execute, so those concrete - // commands are already journaled. Recording the wrapper as well replays - // every script edit twice (#3057). - && !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse") - && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal))) -} - -/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop -/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and -/// droplets write to their destination folder instead. -pub fn shell_save_command(id: &str) -> bool { - matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs") -} - /// The failure for a played Save step whose document `target` (the one active when the step /// started) is no longer open: a Save Document script event closed it. Playback stops there, so /// the next step without a document, such as the Close half of an imported Close with Save: Yes, @@ -266,12 +228,6 @@ fn skipped_steps(action: &Action, from: usize) -> u64 { let disabled = action.disabled.range(from..len).count(); u64::try_from(from.saturating_add(disabled)).unwrap_or(u64::MAX) } -/// View-only menu commands recorded by the desktop shell. Headless playback reports -/// them as unsupported instead of silently dropping them; Batch and droplets skip them. -pub fn shell_view_command(id: &str) -> bool { - matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut") -} - /// Shared validation for headless and shell playback. Does not start playback. Returns the /// action's index in [`ActionState::playable`], the action and the step playback starts at. pub fn playback_plan(s: &Session, p: &Value) -> Result<(usize, Action, usize)> { @@ -605,31 +561,6 @@ pub fn pending_steps(s: &Session, action: usize) -> impl Iterator bool { - matches!( - id, - "paint.stroke" - | "paint.pencil" - | "paint.mixerBrush" - | "paint.colorReplacement" - | "paint.blur" - | "paint.sharpen" - | "paint.smudge" - | "paint.dodge" - | "paint.burn" - | "paint.sponge" - | "paint.cloneStamp" - | "paint.healingBrush" - | "paint.historyBrush" - | "paint.artHistoryBrush" - | "paint.patternStamp" - | "paint.backgroundEraser" - | "paint.spotHealing" - | "paint.remove" - ) -} - pub(crate) fn flush_recording(s: &mut Session) -> Result<()> { let Some((_, idx)) = s.actions.recording else { return Ok(()) }; if s.actions.list.action(idx).is_none() { diff --git a/crates/engine-core/src/cmd/float_cmds.rs b/crates/engine-core/src/cmd/float_cmds.rs index 9a06516353..37a6cbead8 100644 --- a/crates/engine-core/src/cmd/float_cmds.rs +++ b/crates/engine-core/src/cmd/float_cmds.rs @@ -424,6 +424,17 @@ pub(crate) fn before_command(s: &mut Session, id: &str) -> Result> } } +/// The `before_command` hook. A command that may not run leaves a floating selection floating +/// (#13169): it is refused before the piece drops, without a History step (dispatch checks one +/// that may run again once the piece has dropped, on the pixels and selection it will change). +/// Then [`before_command`]: the piece drops before any other command, and Undo puts it back. +pub(crate) fn before_dispatch(s: &mut Session, id: &str, spec: &CommandSpec, params: &Value) -> Result> { + if drops_for(s, id) { + s.admit(id, spec, params)?; + } + before_command(s, id) +} + pub fn specs() -> Vec { vec![ CommandSpec { diff --git a/crates/engine-core/src/cmd/mask_view_cmds.rs b/crates/engine-core/src/cmd/mask_view_cmds.rs index 4c23aa71b9..67dba3ba33 100644 --- a/crates/engine-core/src/cmd/mask_view_cmds.rs +++ b/crates/engine-core/src/cmd/mask_view_cmds.rs @@ -76,6 +76,17 @@ pub(crate) fn fix(st: &mut DocState) { } } +/// The `after_command` hook: a layer-mask view ends when another layer becomes active (#196). +/// Borrowed to change only when it does: the borrow moves the document's `Tracked` revision, and +/// this runs after every command. +pub(crate) fn after_command(s: &mut Session, _: &str, _: &Value) { + if s.active().is_some_and(stale) + && let Some(st) = s.active_mut() + { + st.channel_view.layer_mask = None; + } +} + /// Whether `st` keeps a layer-mask view that no longer applies ([`fix`] ends it). pub(crate) fn stale(st: &DocState) -> bool { st.channel_view.layer_mask.is_some() && current(st).is_none() diff --git a/crates/engine-core/src/filters.rs b/crates/engine-core/src/filters.rs index 9a48debb9b..b2096b0930 100644 --- a/crates/engine-core/src/filters.rs +++ b/crates/engine-core/src/filters.rs @@ -579,5 +579,27 @@ pub fn last_filter(s: &Session) -> Option<(String, Value)> { Some((id, params)) } +/// The `redirect` hook: Last Filter runs as the filter it repeats, journaled, recorded in an +/// action, faded and run as a job like that filter, so a recorded step replays the same filter +/// anywhere (#3089), as Transform Again records its transform (#1440). The `target` and `layer` it +/// was called with carry over. With no filter yet it runs itself and fails its precondition. +pub(crate) fn repeat_last_filter(s: &Session, id: &str, params: &Value) -> Option<(String, Value)> { + if id != "filter.lastFilter" { + return None; + } + let (filter, mut p) = last_filter(s).filter(|(f, _)| f != id)?; + for key in ["target", "layer"] { + if let Some(value) = params.get(key) { + if p.is_null() { + p = json!({}); + } + if let Some(object) = p.as_object_mut() { + object.insert(key.into(), value.clone()); + } + } + } + Some((filter, p)) +} + #[cfg(test)] mod tests; diff --git a/crates/engine-core/src/filters_ext.rs b/crates/engine-core/src/filters_ext.rs index ebe352a05b..f5baaed168 100644 --- a/crates/engine-core/src/filters_ext.rs +++ b/crates/engine-core/src/filters_ext.rs @@ -494,6 +494,14 @@ pub(crate) fn prepare(s: &Session, id: &str, p: &Value) -> Value { out } +/// The `run_params` hook: Shape Blur by an installed shape's id or name records the geometry it +/// ran with, as the filter's own prepared params carry it, so the journal (Last Filter, recorded +/// actions) replays where that shape is not installed. The run resolved it already, so it can't +/// fail here. +pub(crate) fn journal_shape_path(s: &Session, id: &str, p: &mut Value) { + let _ = resolve_shape_path(s, id, p); +} + /// Keep portable custom-shape geometry in recorded params. Kernel preparation stays in the job. pub(crate) fn resolve_shape_path(s: &Session, id: &str, p: &mut Value) -> Result<()> { if id == "filter.blur.shapeBlur" && p.get("shapePath").is_none() && ["shapeId", "shapeName"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) { diff --git a/crates/engine-core/src/hooks.rs b/crates/engine-core/src/hooks.rs new file mode 100644 index 0000000000..af7608a79c --- /dev/null +++ b/crates/engine-core/src/hooks.rs @@ -0,0 +1,83 @@ +//! Pipeline hooks: the engine crates' parts of running a command. +//! +//! Core runs every command (`Session::dispatch`, a job's apply, the bookkeeping after both). Where +//! a step belongs to a crate above core (a floating selection drops, Last Filter runs the filter it +//! repeats, an action records the step), core calls the functions that crate registered for that +//! stage. Each crate's `register` adds its hooks to the [`Install`](crate::registry::Install) that +//! also carries its command tables; the process installs both once. + +use photocraft_doc::LayerId; +use serde_json::Value; + +use crate::commands::CommandSpec; +use crate::{Result, Session}; + +/// Replaces a request's params before the authorization gates see them. +pub type RequestParams = fn(&Session, &str, &Value) -> Option; +/// Runs another command in this one's place, with its params. +pub type Redirect = fn(&Session, &str, &Value) -> Option<(String, Value)>; +/// Refuses params the command can't take. +pub type CheckParams = fn(&Session, &str, &Value) -> Result<()>; +/// Runs once the params are valid, before the command: `Some` is the command's result, and the +/// command itself doesn't run. +pub type BeforeCommand = fn(&mut Session, &str, &CommandSpec, &Value) -> Result>; +/// Rewrites the params of a command that ran, before a job or the journal takes them. +pub type RunParams = fn(&Session, &str, &mut Value); +/// Runs after every command or job apply that succeeded, with the params it ran with. +pub type AfterCommand = fn(&mut Session, &str, &Value); +/// The params a recording keeps for one command, given the layers selected before it ran; +/// `None` leaves the step to [`Hooks::recorded_step`]. +pub type RecordedStepFor = fn(&Session, &str, &Value, Option<&[LayerId]>) -> Option; +/// The params a recording keeps for any command without its own entry in +/// [`Hooks::recorded_steps`]. +pub type RecordedStep = fn(&Session, &str, Value, Option<&[LayerId]>) -> Value; +/// A step joined the recording; `true` when its request ran under automation's gate. +pub type StepRecorded = fn(&mut Session, bool, &str, &Value); +/// Folds the step into the journal's last entry instead of adding it; `true` when it did. +pub type CoalesceJournal = fn(&mut Session, &str, &Value) -> bool; +/// Commits the steps recorded so far to the action being recorded. +pub type FlushRecording = fn(&mut Session) -> Result<()>; +/// Applies the preferences to the crate's own state. +pub type PrefsApplied = fn(&mut Session); + +/// The hooks of every installed crate, per stage, in the order the crates registered them. +#[derive(Default)] +pub struct Hooks { + /// Before the authorization gates; the first `Some` replaces the params. + pub request_params: Vec, + /// Once authorized; the first `Some` names the command that runs instead. + pub redirect: Vec, + /// After the documented-keys check, in `dispatch` and `precheck`; the first error refuses. + pub check_params: Vec, + /// Before the command runs; the first `Some` finishes it. + pub before_command: Vec, + /// After a successful run, each in turn. + pub run_params: Vec, + /// After a successful command or job apply, each in turn. + pub after_command: Vec, + /// While recording: a command's own recorded step, by command id. + pub recorded_steps: Vec<(&'static str, RecordedStepFor)>, + /// While recording: the recorded step of every other command. None keeps the params. + pub recorded_step: Option, + /// While recording, once a step is journaled, each in turn. + pub step_recorded: Vec, + /// Before a step is journaled; the first `true` keeps it out of the journal. + pub coalesce_journal: Vec, + /// Before a job applies its step while a recording it didn't start runs, each in turn. + pub flush_recording: Vec, + /// After the preferences changed and core applied its own, each in turn. + pub prefs_applied: Vec, +} + +impl Hooks { + /// The params a recording keeps for command `id`: its own entry in + /// [`Self::recorded_steps`], else [`Self::recorded_step`]. + pub(crate) fn recorded(&self, s: &Session, id: &str, params: Value, pre_selected: Option<&[LayerId]>) -> Value { + let own = self.recorded_steps.iter().find(|(cmd, _)| *cmd == id).and_then(|(_, f)| f(s, id, ¶ms, pre_selected)); + match (own, self.recorded_step) { + (Some(p), _) => p, + (None, Some(f)) => f(s, id, params, pre_selected), + (None, None) => params, + } + } +} diff --git a/crates/engine-core/src/install.rs b/crates/engine-core/src/install.rs index 7e4f8cd43b..dcdeb9fe25 100644 --- a/crates/engine-core/src/install.rs +++ b/crates/engine-core/src/install.rs @@ -147,11 +147,52 @@ pub fn install() -> Result<()> { .get_or_init(|| { let mut install = Install::default(); install.commands.extend_from_slice(TABLES); + register(&mut install); registry::install(install) }) .clone() } +/// This crate's pipeline hooks, grouped by the crate that will own them. Until the engine crates are +/// cut out of this one, it holds every engine hook. A stage runs its hooks in the order written +/// here: store comes last so that `sync_preset_store` runs after the other after-command hooks. +fn register(install: &mut Install) { + let hooks = &mut install.hooks; + + // model + hooks.after_command.push(crate::mask_view_cmds::after_command); + hooks.recorded_steps.push(("layer.duplicate", |s, id, p, pre_selected| { + Some(crate::artboard_cmds::recorded_duplicate(s, crate::layer_multi_cmds::recorded_step(s, id, p.clone(), pre_selected))) + })); + hooks.recorded_step = Some(crate::layer_multi_cmds::recorded_step); + + // vector + hooks.before_command.push(crate::float_cmds::before_dispatch); + hooks.recorded_steps.push(("layerComp.apply", |s, _, p, _| Some(crate::comps_cmds::recorded_apply(s, p.clone())))); + hooks.recorded_steps.push(("edit.checkSpelling", |_, _, p, _| crate::type_spell_cmds::records(p).then(|| crate::type_spell_cmds::recorded_step(p)))); + hooks.prefs_applied.push(|s| crate::transform_cmds::set_budget(u64::from(s.prefs().performance.effective_memory_usage_mb()) << 20)); + + // paint + hooks.coalesce_journal.push(crate::brush_cmds::coalesce_journal); + + // image + hooks.redirect.push(crate::filters::repeat_last_filter); + hooks.check_params.push(|_, id, p| crate::filters::validate_params(id, p)); + hooks.run_params.push(crate::filters_ext::journal_shape_path); + hooks.after_command.push(crate::edit_menu_cmds::after_command); + hooks.prefs_applied.push(|s| crate::plugin_cmds::sync_prefs(s)); + + // files + hooks.request_params.push(crate::file_cmds::batch_open_params); + hooks.after_command.push(|s, id, _| crate::automate_cmds::after_command(s, id)); + hooks.step_recorded.push(crate::actions_cmds::note_step_origin); + hooks.flush_recording.push(crate::actions_cmds::flush_recording); + + // store + hooks.check_params.push(|s, id, p| if id == "file.new" { crate::document_preset_cmds::validate_new_params(s, p) } else { Ok(()) }); + hooks.after_command.push(|s, _, _| s.sync_preset_store()); +} + /// A session with this crate's commands installed: what this crate's tests start from. pub fn session() -> Session { // A conflicting install reports itself at the session's first command. diff --git a/crates/engine-core/src/jobs.rs b/crates/engine-core/src/jobs.rs index b03e0eb36e..4259a33946 100644 --- a/crates/engine-core/src/jobs.rs +++ b/crates/engine-core/src/jobs.rs @@ -1048,7 +1048,7 @@ pub struct PendingPsdPreflight { impl Session { /// A recording mode change must not reclassify an in-flight stroke from this take. pub(crate) fn tool_stroke_job_running(&self) -> bool { - self.jobs.running.iter().any(|job| job.started_in_take == Some(self.actions.take) && crate::actions_cmds::tool_stroke(&job.command)) + self.jobs.running.iter().any(|job| job.started_in_take == Some(self.actions.take) && crate::actions_record::tool_stroke(&job.command)) } /// Run the heavy part of inline (not background) job commands under `ctx`, so another thread @@ -1745,12 +1745,13 @@ impl Session { fn dispatch_with_commit(&mut self, id: &str, params: Value, background: bool, live_commit: Option) -> Result { let spec = crate::registry::spec(id)?; + let hooks = crate::registry::hooks(); // Params are named fields: anything but an object (or null, meaning none) is a caller // mistake, not "use every default". if !(params.is_object() || params.is_null()) { return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); } - let params = crate::file_cmds::batch_open_params(self, id, ¶ms).unwrap_or(params); + let params = hooks.request_params.iter().find_map(|f| f(self, id, ¶ms)).unwrap_or(params); // Untrusted sessions gate every command, including the ones a command runs on its own // behalf (`file.automate.conditionalModeChange` runs `image.mode.*`), before any side // effect. @@ -1762,35 +1763,14 @@ impl Session { let automation = self.authorize.is_some(); let _authorization = AuthorizationScope::enter(self.authorize); let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); - // Last Filter runs as the filter it repeats: journaled, recorded in an action, faded and - // run as a job like that filter, so a recorded step replays the same filter anywhere - // (#3089), as Transform Again records its transform (#1440). With no filter yet it falls - // through to its own precondition. - if id == "filter.lastFilter" - && let Some((filter, mut p)) = crate::filters::last_filter(self).filter(|(f, _)| f != id) - { - for key in ["target", "layer"] { - if let Some(value) = params.get(key) { - if p.is_null() { - p = serde_json::json!({}); - } - if let Some(object) = p.as_object_mut() { - object.insert(key.into(), value.clone()); - } - } - } - return self.dispatch(&filter, p, background); + if let Some((other, p)) = hooks.redirect.iter().find_map(|f| f(self, id, ¶ms)) { + return self.dispatch(&other, p, background); } self.validate_params(id, spec, ¶ms)?; - // A command that may not run leaves a floating selection floating (#13169): it is refused - // before the piece drops, without a History step. One that may run is checked again - // below, once the piece has dropped, on the pixels and selection it will change. - if crate::float_cmds::drops_for(self, id) { - self.admit(id, spec, ¶ms)?; - } - // A floating selection drops before any other command (Undo puts it back instead). - if let Some(v) = crate::float_cmds::before_command(self, id)? { - return Ok(Started::Done(v)); + for before in &hooks.before_command { + if let Some(v) = before(self, id, spec, ¶ms)? { + return Ok(Started::Done(v)); + } } // Pixel commands follow the Channels panel target unless the caller names one. let run_params = self.admit(id, spec, ¶ms)?; @@ -1825,7 +1805,7 @@ impl Session { // A replayable command is recorded as one step, so recording pauses while it runs: an // action it plays (a script step) must not flush the steps it ran so far into the action // being recorded, nor move the recording mark past the entries it is about to replace. - let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None }; + let recording = if spec.journal && crate::actions_record::replayable(id) { self.actions.recording.take() } else { None }; let before = self.active().map(|st| (st.doc.clone(), st.revision)); let docs_before: Vec<_> = self.docs.iter().map(|st| st.doc.id).collect(); // Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an @@ -1853,12 +1833,11 @@ impl Session { self.note_command_damage(id, doc, *revision); self.note_pixel_change(doc.id, *revision); } - // Shape Blur by an installed shape's id or name records the geometry it ran with, as the - // filter's own prepared params carry it: the journal (Last Filter, recorded actions) - // replays where that shape is not installed. The run resolved it already, so it can't fail. let mut params = params; if r.is_ok() { - let _ = crate::filters_ext::resolve_shape_path(self, id, &mut params); + for rewrite in &hooks.run_params { + rewrite(self, id, &mut params); + } } let out = match (r, pending) { (Err(e), Some(job)) => { @@ -1871,7 +1850,7 @@ impl Session { job.params = params; job.journal = spec.journal; job.started_in_take = self.actions.recording.map(|_| self.actions.take); - job.recorded_by = job.started_in_take.filter(|_| self.actions.record_tools || !crate::actions_cmds::tool_stroke(id)); + job.recorded_by = job.started_in_take.filter(|_| self.actions.record_tools || !crate::actions_record::tool_stroke(id)); job.automation = automation; job.pre_selected = pre_selected.clone(); job.before = std::mem::take(&mut record_before); @@ -1996,38 +1975,28 @@ impl Session { pre_selected: Option<&[LayerId]>, before: &crate::actions_record::Before, ) { - // A layer-mask view ends when another layer becomes active (#196). Borrowed to change only when it does: the - // borrow moves the document's `Tracked` revision, and this runs after every command. - if self.active().is_some_and(crate::mask_view_cmds::stale) - && let Some(st) = self.active_mut() - { - st.channel_view.layer_mask = None; + let hooks = crate::registry::hooks(); + for after in &hooks.after_command { + after(self, id, ¶ms); } - crate::edit_menu_cmds::after_command(self, id, ¶ms); - crate::automate_cmds::after_command(self, id); - self.sync_preset_store(); if !journal { return; } - if let Some(from) = nested_from.filter(|_| crate::actions_cmds::replayable(id)) { + if let Some(from) = nested_from.filter(|_| crate::actions_record::replayable(id)) { self.journal.truncate(from); } let typed = crate::actions_record::typed_layer(self, id, ¶ms); - let params = match id { - _ if self.actions.recording.is_none() => params, - "layer.duplicate" => crate::artboard_cmds::recorded_duplicate(self, crate::layer_multi_cmds::recorded_step(self, id, params, pre_selected)), - "layerComp.apply" => crate::comps_cmds::recorded_apply(self, params), - "edit.checkSpelling" if crate::type_spell_cmds::records(¶ms) => crate::type_spell_cmds::recorded_step(¶ms), - _ => crate::layer_multi_cmds::recorded_step(self, id, params, pre_selected), - }; - let params = crate::actions_cmds::recorded_params(self, id, params); + let params = if self.actions.recording.is_none() { params } else { hooks.recorded(self, id, params, pre_selected) }; + let params = crate::actions_record::recorded_params(self, id, params); let params = crate::actions_record::portable(self, id, params, before); // A step a control client runs while the user records keeps automation's gate. - crate::actions_cmds::note_step_origin(self, automation, id, ¶ms); + for recorded in &hooks.step_recorded { + recorded(self, automation, id, ¶ms); + } match crate::actions_record::fold_keystroke(self, id, ¶ms, self.typed_layer) { crate::actions_record::Keystroke::Folded => {} crate::actions_record::Keystroke::None => { - if !crate::brush_cmds::coalesce_journal(self, id, ¶ms) { + if !hooks.coalesce_journal.iter().any(|f| f(self, id, ¶ms)) { self.journal.push((id.to_string(), params)); } } @@ -2093,7 +2062,9 @@ impl Session { // goes into the journal past its start, so that recording doesn't get it. let foreign = self.actions.recording.is_some() && *recorded_by != Some(self.actions.take); if foreign { - crate::actions_cmds::flush_recording(self)?; + for flush in &crate::registry::hooks().flush_recording { + flush(self)?; + } } let prev_active = self.active; let target = match doc { @@ -2133,7 +2104,7 @@ impl Session { // Apply-time hooks can dispatch commands too. Keep the same single-step recording // contract as synchronous dispatch without truncating work done while the worker ran. let nested_from = self.journal.len(); - let recording = if *journal && crate::actions_cmds::replayable(command) { self.actions.recording.take() } else { None }; + let recording = if *journal && crate::actions_record::replayable(command) { self.actions.recording.take() } else { None }; let applied_from = target.and_then(|i| self.docs.get(i)).map(|st| (st.doc.id, st.revision)); let r = match apply { Some(f) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self, payload))) diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index 0137f329f8..1834686d4f 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -24,6 +24,7 @@ pub mod filters_ext; mod group_options; pub mod guide_layout; pub mod hidden_target; +mod hooks; pub mod inspect; pub mod installed_profiles; pub mod jobs; diff --git a/crates/engine-core/src/prefs.rs b/crates/engine-core/src/prefs.rs index 137ca478b5..47f1e74bb2 100644 --- a/crates/engine-core/src/prefs.rs +++ b/crates/engine-core/src/prefs.rs @@ -1982,10 +1982,11 @@ impl Session { } } photocraft_compose::set_effect_cache_budget(budget); - crate::transform_cmds::set_budget(u64::from(self.prefs().performance.effective_memory_usage_mb()) << 20); // Without waiting for the system font scan: this runs on the UI thread at launch. photocraft_text::set_shared_missing_glyph_protection(self.prefs().type_.missing_glyph_protection()); - crate::plugin_cmds::sync_prefs(self); + for applied in &crate::registry::hooks().prefs_applied { + applied(self); + } } /// Re-apply History's byte limit after the scratch disk paused (a write, create or diff --git a/crates/engine-core/src/registry.rs b/crates/engine-core/src/registry.rs index 8b93e30c81..e077991b8c 100644 --- a/crates/engine-core/src/registry.rs +++ b/crates/engine-core/src/registry.rs @@ -1,10 +1,11 @@ //! The command registry: the command tables a process installs, in their order, looked up by id. use std::collections::HashMap; -use std::sync::OnceLock; +use std::sync::{LazyLock, OnceLock}; use serde_json::{Value, json}; +use crate::hooks::Hooks; use crate::{EngineError, Result, Session}; type Run = fn(&mut Session, &Value) -> Result; @@ -36,11 +37,15 @@ pub struct Install { /// Registry order: these tables in turn, each in its own order. Menus, the Command Palette /// and `command.list` list commands in it. pub commands: Vec, + /// The pipeline hooks of the crates whose tables these are. + pub(crate) hooks: Hooks, } /// Install `install` for this process. Installing the same tables again (the same names in the /// same order) does nothing. Different tables are refused with [`EngineError::InstallConflict`], /// and from then on every command fails with it and the registry lists nothing. +/// Only the tables are compared: each crate's `register` adds its hooks with its tables, so the +/// same tables come with the same hooks. pub fn install(install: Install) -> Result<()> { INSTALLED.install(install) } @@ -55,6 +60,12 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { INSTALLED.registry().ok()?.get(id) } +/// The installed pipeline hooks (none before an install, or after a conflicting one). +pub(crate) fn hooks() -> &'static Hooks { + static NO_HOOKS: LazyLock = LazyLock::new(Hooks::default); + INSTALLED.installed().map_or(&*NO_HOOKS, |install| &install.hooks) +} + /// The installed command `id`, for running it: [`EngineError::NotInstalled`] before an install, /// [`EngineError::UnknownCommand`] for an id no table has. pub fn spec(id: &str) -> Result<&'static CommandSpec> { @@ -103,23 +114,23 @@ pub fn list_entry_matches(entry: &Value, needle: &str) -> bool { static INSTALLED: InstallCell = InstallCell::new(); -/// A process's install: the first install's tables, the registry built from them on first use, +/// A process's install: the first install, the registry built from its tables on first use, /// and the conflict a later install with other tables raised. struct InstallCell { - tables: OnceLock>, + installed: OnceLock, registry: OnceLock, conflict: OnceLock, } impl InstallCell { const fn new() -> Self { - Self { tables: OnceLock::new(), registry: OnceLock::new(), conflict: OnceLock::new() } + Self { installed: OnceLock::new(), registry: OnceLock::new(), conflict: OnceLock::new() } } fn install(&self, install: Install) -> Result<()> { - let mut requested = Some(install.commands); - let installed = self.tables.get_or_init(|| requested.take().unwrap_or_default()); - let Some(requested) = requested else { return Ok(()) }; + let mut requested = Some(install); + let installed = &self.installed.get_or_init(|| requested.take().unwrap_or_default()).commands; + let Some(Install { commands: requested, .. }) = requested else { return Ok(()) }; let name = |tables: &[Table], at: usize| tables.get(at).map_or_else(|| "(none)".to_string(), |t| t.0.to_string()); let Some(at) = (0..installed.len().max(requested.len())).find(|&at| installed.get(at).map(|t| t.0) != requested.get(at).map(|t| t.0)) else { return Ok(()); @@ -129,12 +140,16 @@ impl InstallCell { Err(conflict) } - fn registry(&self) -> Result<&Registry> { + fn installed(&self) -> Result<&Install> { if let Some(conflict) = self.conflict.get() { return Err(conflict.clone()); } - let tables = self.tables.get().ok_or(EngineError::NotInstalled)?; - Ok(self.registry.get_or_init(|| Registry::new(build(tables)))) + self.installed.get().ok_or(EngineError::NotInstalled) + } + + fn registry(&self) -> Result<&Registry> { + let install = self.installed()?; + Ok(self.registry.get_or_init(|| Registry::new(build(&install.commands)))) } } @@ -202,12 +217,12 @@ mod tests { let cell = InstallCell::new(); assert!(matches!(cell.registry(), Err(EngineError::NotInstalled))); - cell.install(Install { commands: vec![a] }).unwrap(); + cell.install(Install { commands: vec![a], ..Install::default() }).unwrap(); assert!(cell.registry().unwrap().get("a.one").is_some()); - cell.install(Install { commands: vec![a] }).unwrap(); + cell.install(Install { commands: vec![a], ..Install::default() }).unwrap(); assert!(cell.registry().unwrap().get("a.one").is_some(), "the same tables again change nothing"); - let conflict = cell.install(Install { commands: vec![a, b] }).unwrap_err(); + let conflict = cell.install(Install { commands: vec![a, b], ..Install::default() }).unwrap_err(); assert_eq!(conflict, EngineError::InstallConflict { at: 1, installed: "(none)".into(), requested: "b".into() }); assert_eq!(cell.registry().err(), Some(conflict), "every later lookup reports the conflict"); } diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index 438fe046c1..58e32a799e 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -56,13 +56,11 @@ impl Session { self.live_commit = None; } - /// The per-command value checks `dispatch` and `precheck` share, in the order `dispatch` runs them. + /// The per-command value checks `dispatch` and `precheck` share: the documented keys, then the + /// `check_params` hooks. pub(crate) fn validate_params(&self, id: &str, spec: &crate::registry::CommandSpec, params: &Value) -> Result<()> { - if id == "file.new" { - crate::document_preset_cmds::validate_new_params(self, params)?; - } crate::param_check::check(spec, params)?; - crate::filters::validate_params(id, params) + crate::registry::hooks().check_params.iter().try_for_each(|check| check(self, id, params)) } /// Check a call without running it: the command exists, its params have the shape @@ -413,7 +411,7 @@ impl Session { /// Image › Adjustments, all but Invert (#10484), filter plug-ins included (`plugin.run`; the /// other `plugin.*` commands manage plug-ins). Catalogue queries still answer. fn bitmap_mode_refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> { - let edits = (id.starts_with("filter.") || id.starts_with("image.adjustments.") || id == crate::plugin_cmds::RUN) + let edits = (id.starts_with("filter.") || id.starts_with("image.adjustments.") || id == "plugin.run") && id != "image.adjustments.invert" && !id.ends_with(".list") // Only the Filter Gallery answers `{"list": true}` with its catalogue; other commands ignore it.