Merge branch 'main' into feat/param-schema-dispatch

This commit is contained in:
FredApps committed 2026-11-23 08:04:41 +07:00
commit 7d433e98ef
21 files changed
+340 -183

No files matched your search

+72 -1
View File
@@ -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;
+2 -71
View File
@@ -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<Value> {
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<Item = &(Strin
s.journal.iter().skip(from).filter(|(id, p)| recorded(id, p) && (s.actions.record_tools || !tool_stroke(id)))
}
/// 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"
)
}
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() {
+11
View File
@@ -424,6 +424,17 @@ pub(crate) fn before_command(s: &mut Session, id: &str) -> Result<Option<Value>>
}
}
/// 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<Option<Value>> {
if drops_for(s, id) {
s.admit(id, spec, params)?;
}
before_command(s, id)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
@@ -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)]
@@ -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 {
@@ -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() {
@@ -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()
@@ -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<Rect> {
pub(crate) fn shape_pixel_bounds(sh: &photocraft_doc::ShapeLayer, canvas: Rect, sample: SampleType) -> Option<Rect> {
if unbounded_fill(sh) {
return None;
}
+3 -3
View File
@@ -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<photocraft_geom::Rect> {
@@ -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
}
+22
View File
@@ -583,5 +583,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;
+8
View File
@@ -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())) {
+83
View File
@@ -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<Value>;
/// 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<Option<Value>>;
/// 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<Value>;
/// 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<RequestParams>,
/// Once authorized; the first `Some` names the command that runs instead.
pub redirect: Vec<Redirect>,
/// After the documented-keys check, in `dispatch` and `precheck`; the first error refuses.
pub check_params: Vec<CheckParams>,
/// Before the command runs; the first `Some` finishes it.
pub before_command: Vec<BeforeCommand>,
/// After a successful run, each in turn.
pub run_params: Vec<RunParams>,
/// After a successful command or job apply, each in turn.
pub after_command: Vec<AfterCommand>,
/// 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<RecordedStep>,
/// While recording, once a step is journaled, each in turn.
pub step_recorded: Vec<StepRecorded>,
/// Before a step is journaled; the first `true` keeps it out of the journal.
pub coalesce_journal: Vec<CoalesceJournal>,
/// Before a job applies its step while a recording it didn't start runs, each in turn.
pub flush_recording: Vec<FlushRecording>,
/// After the preferences changed and core applied its own, each in turn.
pub prefs_applied: Vec<PrefsApplied>,
}
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, &params, pre_selected));
match (own, self.recorded_step) {
(Some(p), _) => p,
(None, Some(f)) => f(s, id, params, pre_selected),
(None, None) => params,
}
}
}
+41
View File
@@ -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.
+31 -60
View File
@@ -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<crate::brush_cmds::LiveCommit>) -> Result<Started> {
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, &params).unwrap_or(params);
let params = hooks.request_params.iter().find_map(|f| f(self, id, &params)).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, &params)) {
return self.dispatch(&other, p, background);
}
self.validate_params(id, spec, &params)?;
// 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, &params)?;
}
// 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, &params)? {
return Ok(Started::Done(v));
}
}
// Pixel commands follow the Channels panel target unless the caller names one.
let run_params = self.admit(id, spec, &params)?;
@@ -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);
@@ -1911,7 +1890,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 +1901,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;
@@ -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, &params);
}
crate::edit_menu_cmds::after_command(self, id, &params);
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, &params);
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(&params) => crate::type_spell_cmds::recorded_step(&params),
_ => 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, &params);
for recorded in &hooks.step_recorded {
recorded(self, automation, id, &params);
}
match crate::actions_record::fold_keystroke(self, id, &params, self.typed_layer) {
crate::actions_record::Keystroke::Folded => {}
crate::actions_record::Keystroke::None => {
if !crate::brush_cmds::coalesce_journal(self, id, &params) {
if !hooks.coalesce_journal.iter().any(|f| f(self, id, &params)) {
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)))
+2
View File
@@ -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;
@@ -23,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;
+3 -2
View File
@@ -1984,10 +1984,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
+28 -13
View File
@@ -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<Value>;
@@ -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<Table>,
/// 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<Hooks> = 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<Vec<Table>>,
installed: OnceLock<Install>,
registry: OnceLock<Registry>,
conflict: OnceLock<EngineError>,
}
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");
}
+1 -2
View File
@@ -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;
+9 -14
View File
@@ -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 {
@@ -59,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
@@ -346,7 +341,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 +381,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 +393,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 +401,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();
}
@@ -416,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.
+4 -4
View File
@@ -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);
+2 -2
View File
@@ -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