Merge pull request #15782 from aiongg/engine-split-registry

Engine install registry (#15710)
This commit is contained in:
aiongg authored and GitHub committed 2026-11-19 18:16:25 -05:00
commit f63ed56fe8
35 files changed
+599 -340

No files matched your search

+12 -274
View File
@@ -1,4 +1,5 @@
//! The command registry. Ids follow Photoshop's menu structure (see the parity checklist).
//! The engine's commands and the helpers they share. Ids follow Photoshop's menu structure (see
//! the parity checklist).
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size};
@@ -8,25 +9,6 @@ use serde_json::{Value, json};
use crate::{EngineError, Result, Session, inspect, pixels};
type Run = fn(&mut Session, &Value) -> Result<Value>;
type Enabled = fn(&Session) -> std::result::Result<(), String>;
/// Metadata + implementation for one command.
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement, e.g. `["Layer", "New"]`. Empty = not in menus.
pub menu: &'static [&'static str],
/// Default shortcut in egui-style notation (`Cmd+Shift+N`), mapped per platform by the UI.
pub shortcut: Option<&'static str>,
/// Human/agent-readable parameter description (JSON-ish).
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
/// Record in the session journal (false for queries).
pub journal: bool,
}
macro_rules! cmd {
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
@@ -49,8 +31,6 @@ pub mod brush_preset_cmds;
pub mod channel_cmds;
pub mod color_cmds;
pub mod color_to_alpha_cmds;
#[cfg(test)]
mod command_order_tests;
pub mod comps_cmds;
pub mod contour_lib_cmds;
#[cfg(test)]
@@ -105,7 +85,7 @@ pub mod layer_xmp_cmds;
pub mod lens_cmds;
pub mod magnetic_cmds;
pub mod mask_view_cmds;
pub(super) mod migrate_cmds;
pub mod migrate_cmds;
pub mod mode_cmds;
pub mod multichannel_cmds;
#[cfg(test)]
@@ -116,7 +96,7 @@ mod notes_stored_values_tests;
mod ops;
pub mod paint_cmds;
mod params;
pub(super) mod path_edit_cmds;
pub mod path_edit_cmds;
pub mod pattern_cmds;
pub mod pattern_fill_cmds;
pub mod perspective_crop_cmds;
@@ -151,10 +131,10 @@ pub mod stamp_cmds;
pub mod style_asl_cmds;
pub mod swatch_cmds;
pub mod symmetry_cmds;
mod table;
pub(super) mod timeline_cmds;
pub mod table;
pub mod timeline_cmds;
pub mod transform_cmds;
pub(super) mod trap_cmds;
pub mod trap_cmds;
pub mod type_area_cmds;
pub mod type_caret_cmds;
pub mod type_cmds;
@@ -164,14 +144,14 @@ mod type_indexed_mode_tests;
pub mod type_mask_cmds;
pub mod type_spell_cmds;
pub mod type_styles_cmds;
pub(super) mod variables_cmds;
pub mod variables_cmds;
mod vector_clipboard;
pub mod vector_cmds;
pub(super) mod video_cmds;
pub mod video_cmds;
pub mod vp_cmds;
pub mod warp_cmds;
pub mod web_cmds;
pub(super) mod wia_cmds;
pub mod wia_cmds;
pub(crate) use adjust_params::inject_kind;
use adjust_params::{adjust_mode, destructive_adjust, doc_mode, new_adjustment};
@@ -186,250 +166,8 @@ use params::{bad, set_clipped};
pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param};
pub use photocraft_color::blend::parse_blend;
pub fn command_specs() -> &'static [CommandSpec] {
&registry().specs
}
/// One `command.list` / `engine.commands` row for `c`, given why it can't run now (`None` = it can).
/// `disabledReason` is that message; `needsDocument` is true when the reason is that no document is
/// open (#3664), so an agent can tell "open or create a document first" from a precondition that a
/// document alone won't meet (a selection, an empty clipboard).
pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value {
let needs_document =
s.active().is_none() && reason.as_deref().is_some_and(|r| ["no document", "no active document", "no open document"].iter().any(|p| r.starts_with(p)));
let mut entry = json!({
"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params,
"enabled": reason.is_none(), "disabledReason": reason, "needsDocument": needs_document,
});
if let (Some(k), Some(o)) = (search_keywords(c.id), entry.as_object_mut()) {
o.insert("keywords".into(), json!(k));
}
entry
}
/// Other names a command is looked for by, beyond its id and label: the Photoshop tools and
/// options it stands for (#5060). `select.rect` is also the Elliptical and Single Row/Column
/// Marquee, which an agent searches for as "ellipse" or "marquee". The RAW Develop filter and
/// RAW Defaults keep Photoshop's "Camera Raw" name as a search alias only: the menus and windows
/// say "RAW Develop" (#12403).
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[
("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"),
("filter.cameraRaw", "Camera Raw Filter"),
("edit.preferences.rawDefaults", "Camera Raw Defaults"),
];
/// [`SEARCH_KEYWORDS`] of command `id`, if it has any.
pub fn search_keywords(id: &str) -> Option<&'static str> {
SEARCH_KEYWORDS.iter().find(|(k, _)| *k == id).map(|(_, words)| *words)
}
/// Does a [`list_entry`] row match a command-list filter (`commands --filter`, `engine.commands`,
/// MCP `command_list`)? Its id, label or keywords contain `needle`, ignoring case.
pub fn list_entry_matches(entry: &Value, needle: &str) -> bool {
let needle = needle.to_lowercase();
["id", "label", "keywords"].iter().any(|k| entry.get(*k).and_then(Value::as_str).is_some_and(|v| v.to_lowercase().contains(&needle)))
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
let registry = registry();
registry.by_id.get(id).and_then(|&index| registry.specs.get(index))
}
struct Registry {
specs: Vec<CommandSpec>,
by_id: std::collections::HashMap<&'static str, usize>,
}
impl Registry {
fn new(specs: Vec<CommandSpec>) -> Self {
let mut by_id = std::collections::HashMap::with_capacity(specs.len());
for (index, spec) in specs.iter().enumerate() {
// Preserve the linear lookup's first-match behavior if an id is duplicated.
by_id.entry(spec.id).or_insert(index);
}
Self { specs, by_id }
}
}
/// The command registry, built on first use and shared for the rest of the process.
fn registry() -> &'static Registry {
static REGISTRY: std::sync::OnceLock<Registry> = std::sync::OnceLock::new();
REGISTRY.get_or_init(|| Registry::new(build()))
}
// ---------- the table ----------
/// A named group of commands: `SPECS` lists them in registry order.
type Fragment = (&'static str, fn() -> Vec<CommandSpec>);
/// Every table fragment with its name, in registry order. The order is part of the behaviour (menus
/// list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by the
/// crate that will own them; a menu split between owners has one fragment per contiguous run.
const SPECS: &[Fragment] = &[
("store::file_menu", table::store::file_menu::specs),
("core::file_menu", table::core::file_menu::specs),
("core::edit_menu", table::core::edit_menu::specs),
("paint::edit_menu", table::paint::edit_menu::specs),
("model::edit_menu", table::model::edit_menu::specs),
("core::select_menu", table::core::select_menu::specs),
("model::layer_menu", table::model::layer_menu::specs_before_gradient),
("store::layer_menu", table::store::layer_menu::specs),
("model::layer_menu", table::model::layer_menu::specs_after_gradient),
("model::image_menu", table::model::image_menu::specs),
("image::image_menu", table::image::image_menu::specs),
("paint::stroke", table::paint::stroke::specs),
("core::tools", table::core::tools::specs),
("core::queries", table::core::queries::specs),
("image::adjustments", table::image::adjustments::specs),
("layer_style", crate::layer_style::specs),
("contour_lib_cmds", crate::contour_lib_cmds::specs),
("layer_list_cmds", crate::layer_list_cmds::specs),
("filters", crate::filters::specs),
("filters_ext", crate::filters_ext::specs),
("color_to_alpha_cmds", crate::color_to_alpha_cmds::specs),
("gallery_cmds", crate::gallery_cmds::specs),
("gradient_fill_cmds", crate::gradient_fill_cmds::specs),
("solid_fill_cmds", crate::solid_fill_cmds::specs),
("pattern_fill_cmds", crate::pattern_fill_cmds::specs),
("type_cmds", crate::type_cmds::specs),
("type_mask_cmds", crate::type_mask_cmds::specs),
("transform_cmds", crate::transform_cmds::specs),
("float_cmds", crate::float_cmds::specs),
("vector_cmds", crate::vector_cmds::specs),
("path_edit_cmds", crate::path_edit_cmds::specs),
("smartselect_cmds", crate::smartselect_cmds::specs),
("cutout_cmds", crate::cutout_cmds::specs),
("symmetry_cmds", crate::symmetry_cmds::specs),
("edit_cmds", crate::edit_cmds::specs),
("smart_svg_cmds", crate::smart_svg_cmds::specs),
("color_cmds", crate::color_cmds::specs),
("brush_cmds", crate::brush_cmds::specs),
("brush_preset_cmds", crate::brush_preset_cmds::specs),
("eraser_cmds", crate::eraser_cmds::specs),
("preset_import_cmds", crate::preset_import_cmds::specs),
("style_asl_cmds", crate::style_asl_cmds::specs),
("atn_cmds", crate::atn_cmds::specs),
("actions_edit_cmds", crate::actions_edit_cmds::specs),
("swatch_cmds", crate::swatch_cmds::specs),
("retouch_cmds", crate::retouch_cmds::specs),
("redeye_cmds", crate::redeye_cmds::specs),
("image_cmds", crate::image_cmds::specs),
("perspective_crop_cmds", crate::perspective_crop_cmds::specs),
("selection_cmds", crate::selection_cmds::specs),
("magnetic_cmds", crate::magnetic_cmds::specs),
("select_extra_cmds", crate::select_extra_cmds::specs),
("paint_cmds", crate::paint_cmds::specs),
("extra_cmds", crate::extra_cmds::specs),
("background_cmds", crate::background_cmds::specs),
("file_cmds", crate::file_cmds::specs),
("exr_cmds", crate::exr_cmds::specs),
("type_extra_cmds", crate::type_extra_cmds::specs),
("type_area_cmds", crate::type_area_cmds::specs),
("type_styles_cmds", crate::type_styles_cmds::specs),
("type_spell_cmds", crate::type_spell_cmds::specs),
("type_caret_cmds", crate::type_caret_cmds::specs),
("smart_cmds", crate::smart_cmds::specs),
("layer_multi_cmds", crate::layer_multi_cmds::specs),
("layer_copy_cmds", crate::layer_copy_cmds::specs),
("prefs", crate::prefs::specs),
("edit_menu_cmds", crate::edit_menu_cmds::specs),
("fill_key_cmds", crate::fill_key_cmds::specs),
("sample_cmds", crate::sample_cmds::specs),
("face_cmds", crate::face_cmds::specs),
("sampler_cmds", crate::sampler_cmds::specs),
("brush_key_cmds", crate::brush_key_cmds::specs),
("stamp_cmds", crate::stamp_cmds::specs),
("align_cmds", crate::align_cmds::specs),
("photo_cmds", crate::photo_cmds::specs),
("lens_cmds", crate::lens_cmds::specs),
("vp_cmds", crate::vp_cmds::specs),
("channel_cmds", crate::channel_cmds::specs),
("adjust_cmds", crate::adjust_cmds::specs),
("layer_menu_cmds", crate::layer_menu_cmds::specs),
("layer_label_cmds", crate::layer_label_cmds::specs),
("layer_css_cmds", crate::layer_css_cmds::specs),
("layer_xmp_cmds", crate::layer_xmp_cmds::specs),
("mode_cmds", crate::mode_cmds::specs),
("multichannel_cmds", crate::multichannel_cmds::specs),
("pattern_cmds", crate::pattern_cmds::specs),
("warp_cmds", crate::warp_cmds::specs),
("comps_cmds", crate::comps_cmds::specs),
("artboard_cmds", crate::artboard_cmds::specs),
("distort_cmds", crate::distort_cmds::specs),
("analysis_cmds", crate::analysis_cmds::specs),
("notes_cmds", crate::notes_cmds::specs),
("font_library_cmds", crate::font_library_cmds::specs),
("history_cmds", crate::history_cmds::specs),
("history_options_cmds", crate::history_options_cmds::specs),
("history_menu_cmds", crate::history_menu_cmds::specs),
("history_source_cmds", crate::history_source_cmds::specs),
("history_select_cmds", crate::history_select_cmds::specs),
("proof_sim", crate::proof_sim::specs),
("presets", crate::presets::specs),
("document_preset_cmds", crate::document_preset_cmds::specs),
("export_preset_cmds", crate::export_preset_cmds::specs),
("render_cmds", crate::render_cmds::specs),
("slice_cmds", crate::slice_cmds::specs),
("web_cmds", crate::web_cmds::specs),
("automate_cmds", crate::automate_cmds::specs),
("print_cmds", crate::print_cmds::specs),
("installed_profiles", crate::installed_profiles::specs),
("pick_cmds", crate::pick_cmds::specs),
("layer_nav_cmds", crate::layer_nav_cmds::specs),
("frame_cmds", crate::frame_cmds::specs),
("migrate_cmds", crate::migrate_cmds::specs),
("trap_cmds", crate::trap_cmds::specs),
("timeline_cmds", crate::timeline_cmds::specs),
("video_cmds", crate::video_cmds::specs),
("jobs", crate::jobs::specs),
("wia_cmds", crate::wia_cmds::specs),
("rasterize_style_cmds", crate::rasterize_style_cmds::specs),
("variables_cmds", crate::variables_cmds::specs),
("plugin_cmds", crate::plugin_cmds::specs),
("group_view_cmds", crate::group_view_cmds::specs),
("fx_view_cmds", crate::fx_view_cmds::specs),
("fx_visibility_cmds", crate::fx_visibility_cmds::specs),
("mask_view_cmds", crate::mask_view_cmds::specs),
("layer_mask_props_cmds", crate::layer_mask_props_cmds::specs),
("actions_cmds", crate::actions_cmds::specs),
];
/// Every registered command, in the order of SPECS.
fn build() -> Vec<CommandSpec> {
let specs = SPECS.iter().flat_map(|(_, specs)| specs());
// The dispatch guard's unit test needs a command that panics on purpose (REL-3).
#[cfg(test)]
let specs = specs.chain(std::iter::once(test_panic_command()));
specs.collect()
}
/// A command whose `run` panics on purpose, so the last-resort guard in `jobs::dispatch`
/// can be tested (REL-3). Test builds only: `commands::build` pushes it under `cfg(test)`.
#[cfg(test)]
fn test_panic_command() -> CommandSpec {
#[allow(clippy::panic)]
fn run(_: &mut Session, _: &Value) -> Result<Value> {
panic!("test: this command panicked on purpose")
}
CommandSpec { id: "test.panic", label: "Test Panic", menu: &[], shortcut: None, params: r##"{}"##, enabled: |_: &Session| Ok(()), run, journal: false }
}
#[cfg(test)]
mod registry_tests {
use super::*;
#[test]
fn duplicate_ids_keep_the_first_spec_and_listing_order() {
let mut built = build().into_iter();
let first = built.next().unwrap();
let mut second = built.next().unwrap();
let id = first.id;
second.id = id;
let registry = Registry::new(vec![first, second]);
assert_eq!(registry.by_id.get(id), Some(&0));
assert_eq!(registry.specs.len(), 2);
}
}
pub use crate::install::{command_specs, find};
pub use crate::registry::{CommandSpec, list_entry, list_entry_matches, search_keywords};
#[cfg(test)]
mod set_props_tests {
+6 -6
View File
@@ -1,8 +1,8 @@
//! The command table's fragments, one directory per owner: the crate whose items the commands
//! call. Each directory moves whole into its crate; `SPECS` in `cmd.rs` fixes the order.
//! call. Each directory moves whole into its crate; `TABLES` in `install.rs` fixes the order.
pub(crate) mod core;
pub(crate) mod image;
pub(crate) mod model;
pub(crate) mod paint;
pub(crate) mod store;
pub mod core;
pub mod image;
pub mod model;
pub mod paint;
pub mod store;
+5 -5
View File
@@ -1,5 +1,5 @@
pub(crate) mod edit_menu;
pub(crate) mod file_menu;
pub(crate) mod queries;
pub(crate) mod select_menu;
pub(crate) mod tools;
pub mod edit_menu;
pub mod file_menu;
pub mod queries;
pub mod select_menu;
pub mod tools;
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, can_redo, can_undo, json};
/// Edit menu: Undo and Redo.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))),
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc};
/// File menu: Close.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.close",
"Close",
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry};
/// Commands that report session and document state or switch documents.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: "session.inspect",
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds};
/// Select menu: All, Deselect, Inverse and rectangular selections.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
// Select
cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| {
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, Value, always, cmyk_param, color_param};
/// Tool state: foreground and background colors.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"tools.setColors",
+2 -2
View File
@@ -1,2 +1,2 @@
pub(crate) mod adjustments;
pub(crate) mod image_menu;
pub mod adjustments;
pub mod image_menu;
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment};
/// The adjustment layers and the Image › Adjustments commands, generated from one table.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
let mut v = Vec::new();
// Adjustment layers + destructive adjustments, generated from one list.
// Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale),
@@ -6,7 +6,7 @@ pub(crate) fn desaturate_adjustment() -> Adjustment {
}
/// Image menu: Desaturate.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"image.adjustments.desaturate",
"Desaturate",
+3 -3
View File
@@ -1,3 +1,3 @@
pub(crate) mod edit_menu;
pub(crate) mod image_menu;
pub(crate) mod layer_menu;
pub mod edit_menu;
pub mod image_menu;
pub mod layer_menu;
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, Value, has_pixel_or_channel, is_mask_target, layer_param};
/// Edit menu: Clear (channel and mask targets).
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.clear",
"Clear",
@@ -17,7 +17,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Val
}
/// Image menu: canvas rotations and flips.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal)
@@ -6,12 +6,12 @@ use crate::cmd::{
use photocraft_color::BlendMode;
/// Layer menu, first run: new layers and groups to the solid color fill layer.
pub(crate) fn specs_before_gradient() -> Vec<CommandSpec> {
pub fn specs_before_gradient() -> Vec<CommandSpec> {
[creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), solid_color_fill()].into_iter().flatten().collect()
}
/// Layer menu, last run: adjustment layers, move and translate.
pub(crate) fn specs_after_gradient() -> Vec<CommandSpec> {
pub fn specs_after_gradient() -> Vec<CommandSpec> {
[adjustments(), placement()].into_iter().flatten().collect()
}
+2 -2
View File
@@ -1,2 +1,2 @@
pub(crate) mod edit_menu;
pub(crate) mod stroke;
pub mod edit_menu;
pub mod stroke;
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, has_pixel_or_channel};
/// Edit menu: Fill.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.fill",
"Fill…",
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::cmd::{CommandSpec, has_paintable};
/// Painting: the stroke command.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"paint.stroke",
"Brush Stroke",
+2 -2
View File
@@ -1,2 +1,2 @@
pub(crate) mod file_menu;
pub(crate) mod layer_menu;
pub mod file_menu;
pub mod layer_menu;
@@ -1,7 +1,7 @@
use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex};
/// File menu: New (new documents take their presets from the document preset store).
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![
// File
cmd!(
@@ -1,7 +1,7 @@
use crate::cmd::{Color, CommandSpec, Fill, Layer, LayerContent, Value, color_param, has_doc, json, layer_panel_option, mask_new_layer};
/// Layer menu: the gradient fill layer.
pub(crate) fn specs() -> Vec<CommandSpec> {
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"layer.newFillLayer.gradient",
"Gradient…",
+6
View File
@@ -6,6 +6,12 @@ pub enum EngineError {
/// Displays with the nearest registered ids, if any ([`command_hints`], #3674).
#[error("unknown command `{id}`{hint}", id = .0, hint = command_hints::unknown_command_hint(.0))]
UnknownCommand(String),
/// A session ran a command before the process installed any command tables.
#[error("no commands are installed in this process: create the session with `Session::new()`, which installs them")]
NotInstalled,
/// An install named other command tables than the one already in place; table `at` differs.
#[error("different command tables are already installed: table {at} is `{installed}`, not `{requested}`")]
InstallConflict { at: usize, installed: String, requested: String },
#[error("command `{0}` is not available right now: {1}")]
Disabled(String, String),
#[error("invalid parameters for `{cmd}`: {msg}")]
+168
View File
@@ -0,0 +1,168 @@
//! The engine's full command registry: every command table, in registry order, and the install
//! that puts it in place for the process.
use std::sync::OnceLock;
use crate::Result;
use crate::registry::{self, CommandSpec, Install, Table};
/// Every command table with its name, in registry order. The order is part of the behaviour
/// (menus list commands in it) and `command_ids.txt` pins it. The `table` fragments are grouped by
/// the crate that will own them; a menu split between owners has one fragment per contiguous run.
const TABLES: &[Table] = &[
("store::file_menu", crate::cmd::table::store::file_menu::specs),
("core::file_menu", crate::cmd::table::core::file_menu::specs),
("core::edit_menu", crate::cmd::table::core::edit_menu::specs),
("paint::edit_menu", crate::cmd::table::paint::edit_menu::specs),
("model::edit_menu", crate::cmd::table::model::edit_menu::specs),
("core::select_menu", crate::cmd::table::core::select_menu::specs),
("model::layer_menu", crate::cmd::table::model::layer_menu::specs_before_gradient),
("store::layer_menu", crate::cmd::table::store::layer_menu::specs),
("model::layer_menu", crate::cmd::table::model::layer_menu::specs_after_gradient),
("model::image_menu", crate::cmd::table::model::image_menu::specs),
("image::image_menu", crate::cmd::table::image::image_menu::specs),
("paint::stroke", crate::cmd::table::paint::stroke::specs),
("core::tools", crate::cmd::table::core::tools::specs),
("core::queries", crate::cmd::table::core::queries::specs),
("image::adjustments", crate::cmd::table::image::adjustments::specs),
("layer_style", crate::layer_style::specs),
("contour_lib_cmds", crate::contour_lib_cmds::specs),
("layer_list_cmds", crate::layer_list_cmds::specs),
("filters", crate::filters::specs),
("filters_ext", crate::filters_ext::specs),
("color_to_alpha_cmds", crate::color_to_alpha_cmds::specs),
("gallery_cmds", crate::gallery_cmds::specs),
("gradient_fill_cmds", crate::gradient_fill_cmds::specs),
("solid_fill_cmds", crate::solid_fill_cmds::specs),
("pattern_fill_cmds", crate::pattern_fill_cmds::specs),
("type_cmds", crate::type_cmds::specs),
("type_mask_cmds", crate::type_mask_cmds::specs),
("transform_cmds", crate::transform_cmds::specs),
("float_cmds", crate::float_cmds::specs),
("vector_cmds", crate::vector_cmds::specs),
("path_edit_cmds", crate::path_edit_cmds::specs),
("smartselect_cmds", crate::smartselect_cmds::specs),
("cutout_cmds", crate::cutout_cmds::specs),
("symmetry_cmds", crate::symmetry_cmds::specs),
("edit_cmds", crate::edit_cmds::specs),
("smart_svg_cmds", crate::smart_svg_cmds::specs),
("color_cmds", crate::color_cmds::specs),
("brush_cmds", crate::brush_cmds::specs),
("brush_preset_cmds", crate::brush_preset_cmds::specs),
("eraser_cmds", crate::eraser_cmds::specs),
("preset_import_cmds", crate::preset_import_cmds::specs),
("style_asl_cmds", crate::style_asl_cmds::specs),
("atn_cmds", crate::atn_cmds::specs),
("actions_edit_cmds", crate::actions_edit_cmds::specs),
("swatch_cmds", crate::swatch_cmds::specs),
("retouch_cmds", crate::retouch_cmds::specs),
("redeye_cmds", crate::redeye_cmds::specs),
("image_cmds", crate::image_cmds::specs),
("perspective_crop_cmds", crate::perspective_crop_cmds::specs),
("selection_cmds", crate::selection_cmds::specs),
("magnetic_cmds", crate::magnetic_cmds::specs),
("select_extra_cmds", crate::select_extra_cmds::specs),
("paint_cmds", crate::paint_cmds::specs),
("extra_cmds", crate::extra_cmds::specs),
("background_cmds", crate::background_cmds::specs),
("file_cmds", crate::file_cmds::specs),
("exr_cmds", crate::exr_cmds::specs),
("type_extra_cmds", crate::type_extra_cmds::specs),
("type_area_cmds", crate::type_area_cmds::specs),
("type_styles_cmds", crate::type_styles_cmds::specs),
("type_spell_cmds", crate::type_spell_cmds::specs),
("type_caret_cmds", crate::type_caret_cmds::specs),
("smart_cmds", crate::smart_cmds::specs),
("layer_multi_cmds", crate::layer_multi_cmds::specs),
("layer_copy_cmds", crate::layer_copy_cmds::specs),
("prefs", crate::prefs::specs),
("edit_menu_cmds", crate::edit_menu_cmds::specs),
("fill_key_cmds", crate::fill_key_cmds::specs),
("sample_cmds", crate::sample_cmds::specs),
("face_cmds", crate::face_cmds::specs),
("sampler_cmds", crate::sampler_cmds::specs),
("brush_key_cmds", crate::brush_key_cmds::specs),
("stamp_cmds", crate::stamp_cmds::specs),
("align_cmds", crate::align_cmds::specs),
("photo_cmds", crate::photo_cmds::specs),
("lens_cmds", crate::lens_cmds::specs),
("vp_cmds", crate::vp_cmds::specs),
("channel_cmds", crate::channel_cmds::specs),
("adjust_cmds", crate::adjust_cmds::specs),
("layer_menu_cmds", crate::layer_menu_cmds::specs),
("layer_label_cmds", crate::layer_label_cmds::specs),
("layer_css_cmds", crate::layer_css_cmds::specs),
("layer_xmp_cmds", crate::layer_xmp_cmds::specs),
("mode_cmds", crate::mode_cmds::specs),
("multichannel_cmds", crate::multichannel_cmds::specs),
("pattern_cmds", crate::pattern_cmds::specs),
("warp_cmds", crate::warp_cmds::specs),
("comps_cmds", crate::comps_cmds::specs),
("artboard_cmds", crate::artboard_cmds::specs),
("distort_cmds", crate::distort_cmds::specs),
("analysis_cmds", crate::analysis_cmds::specs),
("notes_cmds", crate::notes_cmds::specs),
("font_library_cmds", crate::font_library_cmds::specs),
("history_cmds", crate::history_cmds::specs),
("history_options_cmds", crate::history_options_cmds::specs),
("history_menu_cmds", crate::history_menu_cmds::specs),
("history_source_cmds", crate::history_source_cmds::specs),
("history_select_cmds", crate::history_select_cmds::specs),
("proof_sim", crate::proof_sim::specs),
("presets", crate::presets::specs),
("document_preset_cmds", crate::document_preset_cmds::specs),
("export_preset_cmds", crate::export_preset_cmds::specs),
("render_cmds", crate::render_cmds::specs),
("slice_cmds", crate::slice_cmds::specs),
("web_cmds", crate::web_cmds::specs),
("automate_cmds", crate::automate_cmds::specs),
("print_cmds", crate::print_cmds::specs),
("installed_profiles", crate::installed_profiles::specs),
("pick_cmds", crate::pick_cmds::specs),
("layer_nav_cmds", crate::layer_nav_cmds::specs),
("frame_cmds", crate::frame_cmds::specs),
("migrate_cmds", crate::migrate_cmds::specs),
("trap_cmds", crate::trap_cmds::specs),
("timeline_cmds", crate::timeline_cmds::specs),
("video_cmds", crate::video_cmds::specs),
("jobs", crate::jobs::specs),
("wia_cmds", crate::wia_cmds::specs),
("rasterize_style_cmds", crate::rasterize_style_cmds::specs),
("variables_cmds", crate::variables_cmds::specs),
("plugin_cmds", crate::plugin_cmds::specs),
("group_view_cmds", crate::group_view_cmds::specs),
("fx_view_cmds", crate::fx_view_cmds::specs),
("fx_visibility_cmds", crate::fx_visibility_cmds::specs),
("mask_view_cmds", crate::mask_view_cmds::specs),
("layer_mask_props_cmds", crate::layer_mask_props_cmds::specs),
("actions_cmds", crate::actions_cmds::specs),
];
/// Install every engine command for this process. Later calls return the first call's result.
pub fn install() -> Result<()> {
static INSTALLED: OnceLock<Result<()>> = OnceLock::new();
INSTALLED
.get_or_init(|| {
let mut install = Install::default();
install.commands.extend_from_slice(TABLES);
registry::install(install)
})
.clone()
}
/// Every engine command in registry order, installed first: for callers that read the registry
/// before any session exists (menus, docs, tests).
pub fn command_specs() -> &'static [CommandSpec] {
// A conflicting install leaves the registry empty, and every command reports the conflict.
let _ = install();
registry::command_specs()
}
/// The engine command `id`, installed first (see [`command_specs`]).
pub fn find(id: &str) -> Option<&'static CommandSpec> {
let _ = install();
registry::find(id)
}
#[cfg(test)]
mod order_tests;
@@ -1014,4 +1014,3 @@ actions.delete
actions.toggle
actions.rename
actions.setColor
test.panic
@@ -1,33 +1,33 @@
use super::{SPECS, command_specs};
use super::TABLES;
const HINT: &str = "\nadd the id to src/install/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff";
/// Menus, the Command Palette and the automation docs list commands in registry order, so the
/// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when
/// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS`
/// set, the test writes the file from the registry instead; review the diff before committing it.
const HINT: &str = "\nadd the id to src/cmd/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff";
/// set, the test writes the file from the tables instead; review the diff before committing it.
#[test]
fn registered_command_ids_keep_their_order() {
let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect();
let ids: Vec<&str> = TABLES.iter().flat_map(|(_, specs)| specs()).map(|c| c.id).collect();
if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/cmd/command_ids.txt");
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/install/command_ids.txt");
std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::<String>()).expect("write command_ids.txt");
return;
}
let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect();
if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) {
panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], fragment_of(i));
panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], table_of(i));
}
assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", fragment_of(ids.len().min(expected.len())));
assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", table_of(ids.len().min(expected.len())));
}
/// Names the fragment that registers command `index`, for the failure message.
fn fragment_of(index: usize) -> String {
/// Names the table that registers command `index`, for the failure message.
fn table_of(index: usize) -> String {
let mut first = 0;
for (name, specs) in SPECS {
for (name, specs) in TABLES {
let len = specs().len();
if index < first + len {
return format!(" (fragment `{name}`, commands {first}..{})", first + len);
return format!(" (table `{name}`, commands {first}..{})", first + len);
}
first += len;
}
+1 -1
View File
@@ -1721,7 +1721,7 @@ impl Session {
// authorization, validation, floating-selection and admission failures.
let live_commit = self.live_commit.take();
self.sync_scratch_state();
let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
let spec = crate::registry::spec(id)?;
// 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()) {
+9 -7
View File
@@ -62,6 +62,8 @@ pub use photocraft_paint::BrushSettings;
pub mod cmd;
mod doc_state;
mod error;
mod install;
pub mod registry;
mod session;
pub use cmd as commands;
@@ -121,12 +123,12 @@ pub use cmd::layer_xmp_cmds;
pub use cmd::lens_cmds;
pub use cmd::magnetic_cmds;
pub use cmd::mask_view_cmds;
use cmd::migrate_cmds;
pub use cmd::migrate_cmds;
pub use cmd::mode_cmds;
pub use cmd::multichannel_cmds;
pub use cmd::notes_cmds;
pub use cmd::paint_cmds;
use cmd::path_edit_cmds;
pub use cmd::path_edit_cmds;
pub use cmd::pattern_cmds;
pub use cmd::pattern_fill_cmds;
pub use cmd::perspective_crop_cmds;
@@ -152,9 +154,9 @@ pub use cmd::stamp_cmds;
pub use cmd::style_asl_cmds;
pub use cmd::swatch_cmds;
pub use cmd::symmetry_cmds;
use cmd::timeline_cmds;
pub use cmd::timeline_cmds;
pub use cmd::transform_cmds;
use cmd::trap_cmds;
pub use cmd::trap_cmds;
pub use cmd::type_area_cmds;
pub use cmd::type_caret_cmds;
pub use cmd::type_cmds;
@@ -162,13 +164,13 @@ pub use cmd::type_extra_cmds;
pub use cmd::type_mask_cmds;
pub use cmd::type_spell_cmds;
pub use cmd::type_styles_cmds;
use cmd::variables_cmds;
pub use cmd::variables_cmds;
pub use cmd::vector_cmds;
use cmd::video_cmds;
pub use cmd::video_cmds;
pub use cmd::vp_cmds;
pub use cmd::warp_cmds;
pub use cmd::web_cmds;
use cmd::wia_cmds;
pub use cmd::wia_cmds;
pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState, selected_in};
pub use error::{EngineError, Result};
pub use session::move_item;
+1 -1
View File
@@ -462,7 +462,7 @@ pub fn specs() -> Vec<CommandSpec> {
/// Run another command's implementation from inside a preset command (checks `enabled`, but
/// doesn't journal it: the outer command is what an action replays).
pub(crate) fn call(s: &mut Session, id: &str, p: Value) -> Result<Value> {
let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
let spec = crate::registry::spec(id)?;
(spec.enabled)(s).map_err(|why| EngineError::Disabled(id.to_string(), why))?;
// A nested command answers to the session's authorization hook like a direct call.
if let Some(gate) = s.authorize {
+214
View File
@@ -0,0 +1,214 @@
//! 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 serde_json::{Value, json};
use crate::{EngineError, Result, Session};
type Run = fn(&mut Session, &Value) -> Result<Value>;
type Enabled = fn(&Session) -> std::result::Result<(), String>;
/// Metadata + implementation for one command.
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement, e.g. `["Layer", "New"]`. Empty = not in menus.
pub menu: &'static [&'static str],
/// Default shortcut in egui-style notation (`Cmd+Shift+N`), mapped per platform by the UI.
pub shortcut: Option<&'static str>,
/// Human/agent-readable parameter description (JSON-ish).
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
/// Record in the session journal (false for queries).
pub journal: bool,
}
/// One command table: a module's or a table fragment's specs, under the name that identifies it
/// when two installs are compared and in the order test's messages.
pub type Table = (&'static str, fn() -> Vec<CommandSpec>);
/// What a process installs before its first session.
#[derive(Default)]
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>,
}
/// 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.
pub fn install(install: Install) -> Result<()> {
INSTALLED.install(install)
}
/// Every installed command, in registry order (none before an install).
pub fn command_specs() -> &'static [CommandSpec] {
INSTALLED.registry().map_or(&[][..], |r| r.specs.as_slice())
}
/// The installed command `id`, if any.
pub fn find(id: &str) -> Option<&'static CommandSpec> {
INSTALLED.registry().ok()?.get(id)
}
/// 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> {
INSTALLED.registry()?.get(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))
}
/// One `command.list` / `engine.commands` row for `c`, given why it can't run now (`None` = it can).
/// `disabledReason` is that message; `needsDocument` is true when the reason is that no document is
/// open (#3664), so an agent can tell "open or create a document first" from a precondition that a
/// document alone won't meet (a selection, an empty clipboard).
pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value {
let needs_document =
s.active().is_none() && reason.as_deref().is_some_and(|r| ["no document", "no active document", "no open document"].iter().any(|p| r.starts_with(p)));
let mut entry = json!({
"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params,
"enabled": reason.is_none(), "disabledReason": reason, "needsDocument": needs_document,
});
if let (Some(k), Some(o)) = (search_keywords(c.id), entry.as_object_mut()) {
o.insert("keywords".into(), json!(k));
}
entry
}
/// Other names a command is looked for by, beyond its id and label: the Photoshop tools and
/// options it stands for (#5060). `select.rect` is also the Elliptical and Single Row/Column
/// Marquee, which an agent searches for as "ellipse" or "marquee". The RAW Develop filter and
/// RAW Defaults keep Photoshop's "Camera Raw" name as a search alias only: the menus and windows
/// say "RAW Develop" (#12403).
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[
("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"),
("filter.cameraRaw", "Camera Raw Filter"),
("edit.preferences.rawDefaults", "Camera Raw Defaults"),
];
/// [`SEARCH_KEYWORDS`] of command `id`, if it has any.
pub fn search_keywords(id: &str) -> Option<&'static str> {
SEARCH_KEYWORDS.iter().find(|(k, _)| *k == id).map(|(_, words)| *words)
}
/// Does a [`list_entry`] row match a command-list filter (`commands --filter`, `engine.commands`,
/// MCP `command_list`)? Its id, label or keywords contain `needle`, ignoring case.
pub fn list_entry_matches(entry: &Value, needle: &str) -> bool {
let needle = needle.to_lowercase();
["id", "label", "keywords"].iter().any(|k| entry.get(*k).and_then(Value::as_str).is_some_and(|v| v.to_lowercase().contains(&needle)))
}
static INSTALLED: InstallCell = InstallCell::new();
/// A process's install: the first install's tables, the registry built from them on first use,
/// and the conflict a later install with other tables raised.
struct InstallCell {
tables: OnceLock<Vec<Table>>,
registry: OnceLock<Registry>,
conflict: OnceLock<EngineError>,
}
impl InstallCell {
const fn new() -> Self {
Self { tables: 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 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(());
};
let conflict = EngineError::InstallConflict { at, installed: name(installed.as_slice(), at), requested: name(requested.as_slice(), at) };
let _ = self.conflict.set(conflict.clone());
Err(conflict)
}
fn registry(&self) -> Result<&Registry> {
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))))
}
}
struct Registry {
specs: Vec<CommandSpec>,
by_id: HashMap<&'static str, usize>,
}
impl Registry {
fn new(specs: Vec<CommandSpec>) -> Self {
let mut by_id = HashMap::with_capacity(specs.len());
for (index, spec) in specs.iter().enumerate() {
// Preserve the linear lookup's first-match behavior if an id is duplicated.
by_id.entry(spec.id).or_insert(index);
}
Self { specs, by_id }
}
fn get(&self, id: &str) -> Option<&CommandSpec> {
self.by_id.get(id).and_then(|&index| self.specs.get(index))
}
}
/// Every command of `tables`, in their order.
fn build(tables: &[Table]) -> Vec<CommandSpec> {
let specs = tables.iter().flat_map(|(_, specs)| specs());
// The dispatch guard's unit test needs a command that panics on purpose (REL-3).
#[cfg(test)]
let specs = specs.chain(std::iter::once(test_panic_command()));
specs.collect()
}
/// A command whose `run` panics on purpose, so the last-resort guard in `jobs::dispatch`
/// can be tested (REL-3). Test builds only: [`build`] adds it under `cfg(test)`.
#[cfg(test)]
fn test_panic_command() -> CommandSpec {
#[allow(clippy::panic)]
fn run(_: &mut Session, _: &Value) -> Result<Value> {
panic!("test: this command panicked on purpose")
}
CommandSpec { id: "test.panic", label: "Test Panic", menu: &[], shortcut: None, params: r##"{}"##, enabled: |_: &Session| Ok(()), run, journal: false }
}
#[cfg(test)]
mod tests {
use super::*;
fn spec(id: &'static str) -> CommandSpec {
CommandSpec { id, label: id, menu: &[], shortcut: None, params: "{}", enabled: |_| Ok(()), run: |_, _| Ok(Value::Null), journal: true }
}
#[test]
fn duplicate_ids_keep_the_first_spec_and_listing_order() {
let mut second = spec("a.one");
second.label = "second";
let registry = Registry::new(vec![spec("a.one"), second]);
assert_eq!(registry.get("a.one").map(|c| c.label), Some("a.one"));
assert_eq!(registry.specs.len(), 2);
}
#[test]
fn lookups_before_an_install_fail_clearly_and_installs_must_agree() {
let a: Table = ("a", || vec![spec("a.one")]);
let b: Table = ("b", || vec![spec("b.one")]);
let cell = InstallCell::new();
assert!(matches!(cell.registry(), Err(EngineError::NotInstalled)));
cell.install(Install { commands: vec![a] }).unwrap();
assert!(cell.registry().unwrap().get("a.one").is_some());
cell.install(Install { commands: vec![a] }).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();
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");
}
}
+3
View File
@@ -17,6 +17,9 @@ pub fn move_item<T>(v: &mut Vec<T>, i: usize, to: usize) -> Option<usize> {
impl Session {
pub fn new() -> Self {
// Commands run through the process-wide registry; the first session installs it, and a
// conflicting install reports itself at the first command.
let _ = crate::install::install();
Self::default()
}
+5 -2
View File
@@ -67,7 +67,7 @@ impl Session {
/// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but
/// for the group nesting limit (a test holds the two together). For others it checks only what they share.
pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> {
let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
let spec = crate::registry::spec(id)?;
if !(params.is_object() || params.is_null()) {
return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() });
}
@@ -143,7 +143,10 @@ impl Session {
/// [`Self::disabled_reason`] for a call with `params`.
pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option<String> {
let Some(spec) = commands::find(id) else { return Some(EngineError::UnknownCommand(id.into()).to_string()) };
let spec = match crate::registry::spec(id) {
Ok(spec) => spec,
Err(e) => return Some(e.to_string()),
};
self.spec_disabled_reason(spec, id, params)
}
+1 -1
View File
@@ -990,7 +990,7 @@ fn command_list_filter_finds_the_raw_commands_by_their_photoshop_name() {
/// Every keyword entry names a real command, so a renamed id can't leave one behind.
#[test]
fn search_keywords_name_real_commands() {
for (id, words) in crate::commands::SEARCH_KEYWORDS {
for (id, words) in crate::registry::SEARCH_KEYWORDS {
assert!(crate::commands::find(id).is_some(), "keywords for unknown command {id}");
assert!(!words.trim().is_empty(), "{id}");
}
+1 -1
View File
@@ -15,7 +15,7 @@
1. **Find the id.** Search `crates/ui-egui/src/menu_catalog.rs` for the Photoshop menu item. Using its id makes the menu item live with no UI work. Commands without a Photoshop menu entry use a descriptive id in the same style (`layer.smartFilter.delete`) and an empty menu path.
2. **Algorithm** goes in the lowest crate that fits (`algo` for imaging, `paint`, `vector`, `text`; colour management is `craft-cms` in craft-libs), with unit tests. It takes depth-agnostic surfaces (`photocraft-raster`), works per tile, and is deterministic (seeded randomness).
3. **Command** goes in an engine module (`crates/engine/src/<area>_cmds.rs`) exposing `specs()`, registered with `v.extend(...)` in `commands.rs`. Fill in:
3. **Command** goes in an engine module (`crates/engine/src/<area>_cmds.rs`) exposing `specs()`, registered by adding `("<module>", crate::<module>::specs)` to `TABLES` in `crates/engine/src/install.rs` (after the table it follows in the menus) and its ids to `crates/engine/src/install/command_ids.txt` (the order test says how). A command in a core menu goes in the owner fragment `crates/engine/src/cmd/table/<owner>/<menu>.rs` instead. Fill in:
- `id`, `label`, `menu` path and Photoshop's default `shortcut`,
- a params doc string such as `{"radius":px=4,"mode":"a|b"="a"}` (this is what agents read through `commands` / `command_list`),
- an `enabled` predicate (greys the menu item out),
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Move a branch's added or removed command tables into the engine's install list.
The engine's command tables are listed, in registry order, in `TABLES` in
`crates/engine/src/install.rs`. Before that, `crates/engine/src/cmd.rs` listed them: first as
`v.extend(<module>::specs());` lines in `fn build()`, later as `("<name>", <path>),` entries in
`SPECS`. A branch that added or removed a table carries that edit in `cmd.rs`. This script applies
it to `TABLES`:
python3 scripts/engine_split/install_tables.py --base <merge-base> --head <branch>
Run it in a checkout of the new main (or of the branch rebased onto it, with its `cmd.rs` hunks
for the old list dropped). `--head` is the branch commit from before the rebase (`<branch>@{1}` or
`ORIG_HEAD` right after it): the rebased branch has no old list left to read, and its added tables
would be lost. Per table, compared between BASE and HEAD:
added the entry goes after its predecessor's entry in TABLES (the nearest earlier table of
HEAD's list that TABLES has; after the last table fragment when there is none);
removed the entry is deleted.
Running it twice gives the same result. Anything it cannot place is listed at the end. Edits of
inline commands are `table_fragments.py`'s; run both.
"""
import argparse, re, subprocess, sys
CMD = "crates/engine/src/cmd.rs"
INSTALL = "crates/engine/src/install.rs"
LIB = "crates/engine/src/lib.rs"
EXTEND_RE = re.compile(r"^\s*v\.extend\(((?:crate::)?(?:cmd::)?)([a-z0-9_:]+?)::([a-z0-9_]+)\(\)\);", re.M)
ENTRY_RE = re.compile(r'^\s*\("([^"]+)",\s*([A-Za-z0-9_:]+)\),', re.M)
def git_show(ref, path):
r = subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True)
return r.stdout if r.returncode == 0 else None
def block(source, start):
"""The text from `start` to the `];` that closes the list it opens."""
i = source.index(start)
return source[i : source.index("\n];", i)]
def tables(ref):
"""[(name, path as install.rs writes it)] of the table list in REF's cmd.rs, in order."""
source = git_show(ref, CMD)
if source is None:
sys.exit(f"{ref} has no {CMD}")
if "const SPECS:" in source:
out = []
for name, path in ENTRY_RE.findall(block(source, "const SPECS:")):
if not path.startswith("crate::"):
path = "crate::cmd::" + path
out.append((name, path))
return out
out = []
for prefix, module, fn in EXTEND_RE.findall(source[source.index("fn build()") :]):
# A path written relative to cmd.rs names a module of `cmd`.
path = ("crate::" + module if prefix == "crate::" else "crate::cmd::" + module) + "::" + fn
name = module.split("::")[-1] + ("" if fn == "specs" else "::" + fn)
out.append((name, path))
return out
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--base", required=True, help="the branch's merge-base with the old main")
ap.add_argument("--head", required=True, help="the branch")
a = ap.parse_args()
if git_show(a.head, INSTALL) is not None:
print(
f"warning: {a.head} is already on the install.rs layout; if you rebased, pass the "
"pre-rebase commit as --head (a rebased branch has lost its added tables)",
file=sys.stderr,
)
return 2
base = dict(tables(a.base))
head = tables(a.head)
head_names = {n for n, _ in head}
text = open(INSTALL).read()
start = text.index("const TABLES:")
end = text.index("\n];", start)
lines = text[start:end].split("\n")
header, rows = lines[0], lines[1:]
names = lambda: [m.group(1) if (m := ENTRY_RE.match(r)) else None for r in rows]
report = []
for pos, (name, path) in enumerate(head):
if name in base or name in names():
continue
pred = next((head[k][0] for k in range(pos - 1, -1, -1) if head[k][0] in names()), None)
current = names()
if pred is not None:
at = len(current) - current[::-1].index(pred)
else:
fragments = [i for i, r in enumerate(rows) if "crate::cmd::table::" in r]
if not fragments:
report.append(f"UNPLACED {name}: no predecessor in TABLES")
continue
at = fragments[-1] + 1
pred = "the last table fragment"
rows.insert(at, f' ("{name}", {path}),')
report.append(f"added {name} ({path}) after {pred}")
module = path.split("::")[-2]
lib = git_show(a.head, LIB) or ""
if not re.search(rf"^pub (?:use cmd::{module}|mod {module})\b", lib, re.M):
report.append(
f"WARNING module `{module}` of {name} is private in {LIB}; task 3 moves install.rs "
"to the top crate and needs it public"
)
for name in base:
if name not in head_names and name in names():
rows = [r for r, n in zip(rows, names()) if n != name]
report.append(f"removed {name}")
text = text[:start] + "\n".join([header] + rows) + text[end:]
open(INSTALL, "w").write(text)
print("\n".join(report) or "nothing to do")
if any(r.startswith("added") for r in report):
print(
"next: run the test `install::order_tests` with PHOTOCRAFT_WRITE_COMMAND_IDS=1 to regenerate "
"install/command_ids.txt, and review its diff"
)
return 1 if any(r.startswith("UNPLACED") for r in report) else 0
if __name__ == "__main__":
sys.exit(main())
+7 -5
View File
@@ -3,13 +3,14 @@
Before the table was split, `crates/engine/src/cmd.rs` held every core command in one `vec![...]`
inside `fn build()`. The entries now live in `crates/engine/src/cmd/table/<owner>/<menu>.rs`, and
`cmd/command_ids.txt` pins the registry order. A branch that edited the old table carries its
`install/command_ids.txt` pins the registry order. A branch that edited the old table carries its
edits in `cmd.rs`. This script applies them to the fragments:
python3 scripts/engine_split/table_fragments.py --base <merge-base> --head <branch>
Run it in a checkout of the new main (or of the branch rebased onto it, with its `cmd.rs` hunks
for the old table dropped). Per command id, compared between BASE and HEAD:
for the old table dropped). `--head` is the branch commit from before the rebase (`<branch>@{1}` or
`ORIG_HEAD` right after it). Per command id, compared between BASE and HEAD:
changed the entry in its fragment is replaced by HEAD's text (if the fragment still has
BASE's text; otherwise it is reported as a CONFLICT and left alone);
added the entry goes after its predecessor's entry, in the predecessor's fragment, and its id
@@ -17,7 +18,8 @@ for the old table dropped). Per command id, compared between BASE and HEAD:
removed the entry and its id are deleted (if the fragment still has BASE's text).
The adjustment table and its loop (`ADJ`, between the `vec![...]` and the `v.extend(...)` list) are
three-way merged into table/image/adjustments.rs. Any other change inside `build()` (the module
table list, the test-only command) is reported as UNHANDLED: edit `SPECS` in cmd.rs by hand.
table list, the test-only command) is reported as UNHANDLED: `install_tables.py` moves module
tables into `TABLES` in install.rs; edit anything else there by hand.
Entries are compared without comments and whitespace, so rustfmt does not matter. Names a new
entry uses from cmd.rs are added to its fragment's `use crate::cmd::{..}` list. Run
`cargo fmt --all` afterwards. Running the script twice gives the same result. CONFLICT, UNHANDLED,
@@ -28,7 +30,7 @@ import argparse, os, re, subprocess, sys, tempfile
CMD = "crates/engine/src/cmd.rs"
TABLE = "crates/engine/src/cmd/table"
IDS = "crates/engine/src/cmd/command_ids.txt"
IDS = "crates/engine/src/install/command_ids.txt"
ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"')
@@ -319,7 +321,7 @@ def main():
open(ADJ_FILE, "w").write(cur[:i] + merged.rstrip("\n") + cur[j:])
report.append(f"changed ADJ table in {ADJ_FILE}")
if norm(h_tail) != norm(b_tail):
report.append("UNHANDLED the branch edits the end of build() (module table list or test-only command): edit SPECS in cmd.rs by hand")
report.append("UNHANDLED the branch edits the end of build() (module table list or test-only command): run install_tables.py, or edit TABLES in install.rs by hand")
fr.save()
open(IDS, "w").write("\n".join(ids) + "\n")
print("\n".join(report) or "nothing to do")