Split the command table into per-owner fragments

Fragments live in cmd/table/<owner>/<menu>.rs, one directory per future crate
(core, model, store, paint, image). SPECS names each fragment so the order test
can say which one a misplaced command comes from. scripts/engine_split/table_fragments.py
moves a branch's edits of the old inline table into the fragments.
This commit is contained in:
aiongg committed 2026-11-19 16:35:19 +00:00
1 parent 687e714ea5
commit 1c97abb475
25 files changed
+647 -366

No files matched your search

+132 -152
View File
@@ -27,27 +27,6 @@ pub struct CommandSpec {
pub journal: bool,
}
/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100.
pub(crate) fn desaturate_adjustment() -> Adjustment {
Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() }
}
/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move).
fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Value> {
if let Some(d) = s.active() {
let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height));
// Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point
// lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`).
let half = photocraft_geom::Affine::translate(0.5, 0.5);
s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
}
s.edit(label, |doc, _| {
crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t));
Ok(())
})?;
Ok(Value::Null)
}
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 }
@@ -58,7 +37,6 @@ pub mod actions_cmds;
pub mod actions_edit_cmds;
pub mod adjust_cmds;
mod adjust_params;
mod adjustments;
pub mod align_cmds;
pub mod analysis_cmds;
pub mod artboard_cmds;
@@ -87,7 +65,6 @@ pub mod cutout_cmds;
pub mod distort_cmds;
pub mod document_preset_cmds;
pub mod edit_cmds;
mod edit_menu;
pub mod edit_menu_cmds;
mod enabled;
pub mod eraser_cmds;
@@ -96,7 +73,6 @@ pub mod exr_cmds;
pub mod extra_cmds;
pub mod face_cmds;
pub mod file_cmds;
mod file_menu;
pub mod fill_cmds;
pub mod fill_key_cmds;
pub mod float_cmds;
@@ -115,13 +91,11 @@ pub mod history_options_cmds;
pub mod history_select_cmds;
pub mod history_source_cmds;
pub mod image_cmds;
mod image_menu;
pub mod layer_copy_cmds;
pub mod layer_css_cmds;
pub mod layer_label_cmds;
pub mod layer_list_cmds;
pub mod layer_mask_props_cmds;
mod layer_menu;
pub mod layer_menu_cmds;
pub mod layer_multi_cmds;
pub mod layer_nav_cmds;
@@ -140,7 +114,6 @@ pub mod notes_cmds;
#[cfg(test)]
mod notes_stored_values_tests;
mod ops;
mod paint;
pub mod paint_cmds;
mod params;
pub(super) mod path_edit_cmds;
@@ -152,7 +125,6 @@ pub mod pick_cmds;
pub mod plugin_cmds;
pub mod preset_import_cmds;
pub mod print_cmds;
mod queries;
pub mod rasterize_style_cmds;
pub mod redeye_cmds;
pub mod render_cmds;
@@ -162,7 +134,6 @@ pub mod sample_cmds;
mod sample_zoom_box_tests;
pub mod sampler_cmds;
pub mod select_extra_cmds;
mod select_menu;
pub mod selection_cmds;
pub mod slice_cmds;
pub mod smart_cmds;
@@ -173,6 +144,7 @@ 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 transform_cmds;
pub(super) mod trap_cmds;
@@ -280,133 +252,141 @@ fn registry() -> &'static Registry {
// ---------- the table ----------
#[allow(clippy::too_many_lines)]
/// Register the core file, edit, layer and document commands.
const SPECS: &[fn() -> Vec<CommandSpec>] = &[
file_menu::specs,
edit_menu::specs,
select_menu::specs,
layer_menu::specs,
image_menu::specs,
paint::specs,
queries::specs,
adjustments::specs,
crate::layer_style::specs,
crate::contour_lib_cmds::specs,
crate::layer_list_cmds::specs,
crate::filters::specs,
crate::filters_ext::specs,
crate::color_to_alpha_cmds::specs,
crate::gallery_cmds::specs,
crate::gradient_fill_cmds::specs,
crate::solid_fill_cmds::specs,
crate::pattern_fill_cmds::specs,
crate::type_cmds::specs,
crate::type_mask_cmds::specs,
crate::transform_cmds::specs,
crate::float_cmds::specs,
crate::vector_cmds::specs,
crate::path_edit_cmds::specs,
crate::smartselect_cmds::specs,
crate::cutout_cmds::specs,
crate::symmetry_cmds::specs,
crate::edit_cmds::specs,
crate::smart_svg_cmds::specs,
crate::color_cmds::specs,
crate::brush_cmds::specs,
crate::brush_preset_cmds::specs,
crate::eraser_cmds::specs,
crate::preset_import_cmds::specs,
crate::style_asl_cmds::specs,
crate::atn_cmds::specs,
crate::actions_edit_cmds::specs,
crate::swatch_cmds::specs,
crate::retouch_cmds::specs,
crate::redeye_cmds::specs,
crate::image_cmds::specs,
crate::perspective_crop_cmds::specs,
crate::selection_cmds::specs,
crate::magnetic_cmds::specs,
crate::select_extra_cmds::specs,
crate::paint_cmds::specs,
crate::extra_cmds::specs,
crate::background_cmds::specs,
crate::file_cmds::specs,
crate::exr_cmds::specs,
crate::type_extra_cmds::specs,
crate::type_area_cmds::specs,
crate::type_styles_cmds::specs,
crate::type_spell_cmds::specs,
crate::type_caret_cmds::specs,
crate::smart_cmds::specs,
crate::layer_multi_cmds::specs,
crate::layer_copy_cmds::specs,
crate::prefs::specs,
crate::edit_menu_cmds::specs,
crate::fill_key_cmds::specs,
crate::sample_cmds::specs,
crate::face_cmds::specs,
crate::sampler_cmds::specs,
crate::brush_key_cmds::specs,
crate::stamp_cmds::specs,
crate::align_cmds::specs,
crate::photo_cmds::specs,
crate::lens_cmds::specs,
crate::vp_cmds::specs,
crate::channel_cmds::specs,
crate::adjust_cmds::specs,
crate::layer_menu_cmds::specs,
crate::layer_label_cmds::specs,
crate::layer_css_cmds::specs,
crate::layer_xmp_cmds::specs,
crate::mode_cmds::specs,
crate::multichannel_cmds::specs,
crate::pattern_cmds::specs,
crate::warp_cmds::specs,
crate::comps_cmds::specs,
crate::artboard_cmds::specs,
crate::distort_cmds::specs,
crate::analysis_cmds::specs,
crate::notes_cmds::specs,
crate::font_library_cmds::specs,
crate::history_cmds::specs,
crate::history_options_cmds::specs,
crate::history_menu_cmds::specs,
crate::history_source_cmds::specs,
crate::history_select_cmds::specs,
crate::proof_sim::specs,
crate::presets::specs,
crate::document_preset_cmds::specs,
crate::export_preset_cmds::specs,
crate::render_cmds::specs,
crate::slice_cmds::specs,
crate::web_cmds::specs,
crate::automate_cmds::specs,
crate::print_cmds::specs,
crate::installed_profiles::specs,
crate::pick_cmds::specs,
crate::layer_nav_cmds::specs,
crate::frame_cmds::specs,
crate::migrate_cmds::specs,
crate::trap_cmds::specs,
crate::timeline_cmds::specs,
crate::video_cmds::specs,
crate::jobs::specs,
crate::wia_cmds::specs,
crate::rasterize_style_cmds::specs,
crate::variables_cmds::specs,
crate::plugin_cmds::specs,
crate::group_view_cmds::specs,
crate::fx_view_cmds::specs,
crate::fx_visibility_cmds::specs,
crate::mask_view_cmds::specs,
crate::layer_mask_props_cmds::specs,
crate::actions_cmds::specs,
/// 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: &[(&str, fn() -> Vec<CommandSpec>)] = &[
("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());
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()));
+1 -1
View File
@@ -403,7 +403,7 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_
})?;
} else if kind == "desaturate" {
let mode = surf.format().mode;
if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() {
if crate::pixels::adjust_surface(&mut out, &super::table::image::image_menu::desaturate_adjustment(), None, mode).is_err() {
return Ok(None);
}
} else if kind == "equalize" {
+19 -3
View File
@@ -1,11 +1,27 @@
use super::command_specs;
use super::{SPECS, command_specs};
/// 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.
#[test]
fn registered_command_ids_keep_their_order() {
let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect();
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", ids[i], expected[i]);
panic!("command {i} is {} where {} was registered{}", ids[i], expected[i], fragment_of(i));
}
assert_eq!(ids.len(), expected.len(), "the number of registered commands changed");
assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}", fragment_of(ids.len().min(expected.len())));
}
/// Names the fragment that registers command `index`, for the failure message.
fn fragment_of(index: usize) -> String {
let mut first = 0;
for (name, specs) in SPECS {
let len = specs().len();
if index < first + len {
return format!(" (fragment `{name}`, commands {first}..{})", first + len);
}
first += len;
}
String::new()
}
-62
View File
@@ -1,62 +0,0 @@
use super::{CommandSpec, Value, can_redo, can_undo, has_pixel_or_channel, is_mask_target, json, layer_param};
/// Edit menu commands: Undo, Redo, Fill and Clear.
pub(super) 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()))),
cmd!(
"edit.fill",
"Fill…",
["Edit"],
Some("Shift+F5"),
r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##,
has_pixel_or_channel,
crate::fill_cmds::fill
),
cmd!(
"edit.clear",
"Clear",
["Edit"],
None,
r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##,
has_pixel_or_channel,
|s, p| {
let bg = s.tools.background;
// A targeted alpha channel or Quick Mask is filled instead (#2734).
let channel = if crate::channel_cmds::is_channel_target(p) {
Some(p.clone())
} else if p.get("target").is_none() {
crate::channel_cmds::targeted_channel(s)
} else {
None
};
if let Some(t) = channel {
s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?;
return Ok(Value::Null);
}
let id = layer_param(s, p)?;
if is_mask_target(p) {
s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?;
return Ok(Value::Null);
}
// A targeted colour channel clears that channel only (#2720).
if let Some(colors) = crate::color_channels::target(s, p)? {
s.edit("Clear", |doc, _| {
for k in colors.indices() {
crate::channel_cmds::clear_color_channel(doc, id, k, bg)?;
}
Ok(())
})?;
return Ok(Value::Null);
}
s.edit("Clear", |doc, _| {
let sel = doc.selection.clone();
let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());
crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg)
})?;
Ok(Value::Null)
}
),
]
}
+8
View File
@@ -0,0 +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.
pub(crate) mod core;
pub(crate) mod image;
pub(crate) mod model;
pub(crate) mod paint;
pub(crate) mod store;
+5
View File
@@ -0,0 +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;
@@ -0,0 +1,9 @@
use crate::cmd::{CommandSpec, can_redo, can_undo, json};
/// Edit menu: Undo and Redo.
pub(crate) 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()))),
]
}
@@ -0,0 +1,28 @@
use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc};
/// File menu: Close.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.close",
"Close",
["File"],
Some("Cmd+W"),
r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##,
has_doc,
|s, p| {
let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
match p.get("save").filter(|v| !v.is_null()) {
Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => {
return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them"));
}
Some(v) if v == "ask" => {}
// `false` (don't save) is the older spelling of discard.
Some(Value::Bool(false)) => {}
Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")),
_ => {}
}
s.close(i).ok_or(EngineError::NoDocument)?;
Ok(Value::Null)
}
)]
}
@@ -1,7 +1,7 @@
use super::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry};
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(super) fn specs() -> Vec<CommandSpec> {
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: "session.inspect",
@@ -1,8 +1,9 @@
use super::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds};
use crate::cmd::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds};
/// Select menu commands: All, Deselect, Inverse and rectangular selections.
pub(super) fn specs() -> Vec<CommandSpec> {
/// Select menu: All, Deselect, Inverse and rectangular selections.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
// Select
cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| {
// With the active layer on an artboard (the board itself or a layer inside it), Select
// All selects that board, as Photoshop does; otherwise the whole canvas (#10258).
@@ -1,17 +1,8 @@
use super::{CommandSpec, Value, always, cmyk_param, color_param, has_paintable};
use crate::cmd::{CommandSpec, Value, always, cmyk_param, color_param};
/// Painting commands: strokes and the foreground and background colors.
pub(super) fn specs() -> Vec<CommandSpec> {
/// Tool state: foreground and background colors.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"paint.stroke",
"Brush Stroke",
[],
None,
r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##,
has_paintable,
crate::brush_cmds::paint_stroke
),
cmd!(
"tools.setColors",
"Set Colors",
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod adjustments;
pub(crate) mod image_menu;
@@ -1,7 +1,7 @@
use super::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment};
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(super) fn specs() -> Vec<CommandSpec> {
pub(crate) 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),
@@ -0,0 +1,24 @@
use crate::cmd::{Adjustment, CommandSpec, Value, destructive_adjust};
/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100.
pub(crate) fn desaturate_adjustment() -> Adjustment {
Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() }
}
/// Image menu: Desaturate.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"image.adjustments.desaturate",
"Desaturate",
["Image", "Adjustments"],
Some("Cmd+Shift+U"),
r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##,
crate::adjust_cmds::has_adjustable,
|s, p| {
if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? {
return Ok(Value::Null);
}
destructive_adjust(s, "Desaturate", desaturate_adjustment(), p)
}
)]
}
+3
View File
@@ -0,0 +1,3 @@
pub(crate) mod edit_menu;
pub(crate) mod image_menu;
pub(crate) mod layer_menu;
@@ -0,0 +1,49 @@
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> {
vec![cmd!(
"edit.clear",
"Clear",
["Edit"],
None,
r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##,
has_pixel_or_channel,
|s, p| {
let bg = s.tools.background;
// A targeted alpha channel or Quick Mask is filled instead (#2734).
let channel = if crate::channel_cmds::is_channel_target(p) {
Some(p.clone())
} else if p.get("target").is_none() {
crate::channel_cmds::targeted_channel(s)
} else {
None
};
if let Some(t) = channel {
s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?;
return Ok(Value::Null);
}
let id = layer_param(s, p)?;
if is_mask_target(p) {
s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?;
return Ok(Value::Null);
}
// A targeted colour channel clears that channel only (#2720).
if let Some(colors) = crate::color_channels::target(s, p)? {
s.edit("Clear", |doc, _| {
for k in colors.indices() {
crate::channel_cmds::clear_color_channel(doc, id, k, bg)?;
}
Ok(())
})?;
return Ok(Value::Null);
}
s.edit("Clear", |doc, _| {
let sel = doc.selection.clone();
let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());
crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg)
})?;
Ok(Value::Null)
}
)]
}
@@ -1,7 +1,23 @@
use super::{CommandSpec, Value, desaturate_adjustment, destructive_adjust, has_doc, turn};
use crate::cmd::{CommandSpec, Result, Session, Value, has_doc};
/// Image menu commands: canvas rotations and flips, and Desaturate.
pub(super) fn specs() -> Vec<CommandSpec> {
/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move).
fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Value> {
if let Some(d) = s.active() {
let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height));
// Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point
// lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`).
let half = photocraft_geom::Affine::translate(0.5, 0.5);
s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
}
s.edit(label, |doc, _| {
crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t));
Ok(())
})?;
Ok(Value::Null)
}
/// Image menu: canvas rotations and flips.
pub(crate) 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)
@@ -18,19 +34,5 @@ pub(super) fn specs() -> Vec<CommandSpec> {
cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90)
}),
cmd!(
"image.adjustments.desaturate",
"Desaturate",
["Image", "Adjustments"],
Some("Cmd+Shift+U"),
r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##,
crate::adjust_cmds::has_adjustable,
|s, p| {
if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? {
return Ok(Value::Null);
}
destructive_adjust(s, "Desaturate", desaturate_adjustment(), p)
}
),
]
}
@@ -1,15 +1,18 @@
use super::{
Adjustment, BlendMode, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind,
arrange, bad, parse_blend, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param,
mask_new_layer, merge_group, move_mask, pixels, set_clipped, set_mask, set_mask_and_deselect,
use crate::cmd::{
Adjustment, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, arrange,
bad, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, mask_new_layer, merge_group, move_mask,
parse_blend, pixels, set_clipped, set_mask, set_mask_and_deselect,
};
use photocraft_color::BlendMode;
/// Layer menu commands, in registry order.
pub(super) fn specs() -> Vec<CommandSpec> {
[creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), fill_layers(), adjustments(), placement()]
.into_iter()
.flatten()
.collect()
/// Layer menu, first run: new layers and groups to the solid color fill layer.
pub(crate) 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> {
[adjustments(), placement()].into_iter().flatten().collect()
}
/// New layers and groups, and grouping the selected layers.
@@ -301,83 +304,38 @@ fn merging() -> Vec<CommandSpec> {
]
}
/// Solid color and gradient fill layers.
fn fill_layers() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.newFillLayer.solidColor",
"Solid Color…",
["Layer", "New Fill Layer"],
None,
r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##,
has_doc,
|s, p| {
let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?;
// The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead
// of what its sRGB stand-in converts back to through the document profile (#8568).
let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? {
Some(k) => Some(k),
None => s.tools.picked_cmyk([c[0], c[1], c[2]]),
/// Solid color fill layer.
fn solid_color_fill() -> Vec<CommandSpec> {
vec![cmd!(
"layer.newFillLayer.solidColor",
"Solid Color…",
["Layer", "New Fill Layer"],
None,
r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##,
has_doc,
|s, p| {
let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?;
// The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead
// of what its sRGB stand-in converts back to through the document profile (#8568).
let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? {
Some(k) => Some(k),
None => s.tools.picked_cmyk([c[0], c[1], c[2]]),
};
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
let id = s.edit("New Color Fill Layer", |doc, active| {
let fill = match inks {
Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }),
_ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode),
};
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
let id = s.edit("New Color Fill Layer", |doc, active| {
let fill = match inks {
Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }),
_ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode),
};
let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
),
cmd!(
"layer.newFillLayer.gradient",
"Gradient…",
["Layer", "New Fill Layer"],
None,
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##,
has_doc,
|s, p| {
let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?;
let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?;
let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?;
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
// The rest of a recorded Gradient Fill (a loaded action's Make): applied as
// `gradient.fill.set` would, in the same step.
let rest: serde_json::Map<String, Value> = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"]
.iter()
.filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone())))
.collect();
let (fg, bg) = (s.tools.foreground, s.tools.background);
let id = s.edit("New Gradient Fill Layer", |doc, active| {
let mut fill = Fill::gradient(
vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))],
angle,
1.0,
style,
reverse,
);
if !rest.is_empty() {
let l = Layer::new(String::new(), LayerContent::Fill(fill.clone()));
fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?;
}
let fill = fill.in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
),
]
let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
)]
}
/// Editing an adjustment layer's properties.
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod edit_menu;
pub(crate) mod stroke;
@@ -0,0 +1,14 @@
use crate::cmd::{CommandSpec, has_pixel_or_channel};
/// Edit menu: Fill.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.fill",
"Fill…",
["Edit"],
Some("Shift+F5"),
r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##,
has_pixel_or_channel,
crate::fill_cmds::fill
)]
}
@@ -0,0 +1,14 @@
use crate::cmd::{CommandSpec, has_paintable};
/// Painting: the stroke command.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"paint.stroke",
"Brush Stroke",
[],
None,
r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##,
has_paintable,
crate::brush_cmds::paint_stroke
)]
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod file_menu;
pub(crate) mod layer_menu;
@@ -1,8 +1,9 @@
use super::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, bad, has_doc, json, parse_hex};
use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex};
/// File menu commands: New and Close.
pub(super) fn specs() -> Vec<CommandSpec> {
/// File menu: New (new documents take their presets from the document preset store).
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
// File
cmd!(
"file.new",
"New…",
@@ -71,28 +72,5 @@ pub(super) fn specs() -> Vec<CommandSpec> {
Ok(json!({ "document": i }))
}
),
cmd!(
"file.close",
"Close",
["File"],
Some("Cmd+W"),
r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##,
has_doc,
|s, p| {
let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
match p.get("save").filter(|v| !v.is_null()) {
Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => {
return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them"));
}
Some(v) if v == "ask" => {}
// `false` (don't save) is the older spelling of discard.
Some(Value::Bool(false)) => {}
Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")),
_ => {}
}
s.close(i).ok_or(EngineError::NoDocument)?;
Ok(Value::Null)
}
),
]
}
@@ -0,0 +1,43 @@
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> {
vec![cmd!(
"layer.newFillLayer.gradient",
"Gradient…",
["Layer", "New Fill Layer"],
None,
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##,
has_doc,
|s, p| {
let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?;
let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?;
let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?;
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
// The rest of a recorded Gradient Fill (a loaded action's Make): applied as
// `gradient.fill.set` would, in the same step.
let rest: serde_json::Map<String, Value> = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"]
.iter()
.filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone())))
.collect();
let (fg, bg) = (s.tools.foreground, s.tools.background);
let id = s.edit("New Gradient Fill Layer", |doc, active| {
let mut fill =
Fill::gradient(vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], angle, 1.0, style, reverse);
if !rest.is_empty() {
let l = Layer::new(String::new(), LayerContent::Fill(fill.clone()));
fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?;
}
let fill = fill.in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
)]
}
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""Move a branch's edits of the old inline command table into the table fragments.
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
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:
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
goes after the predecessor's id in command_ids.txt;
removed the entry and its id are deleted.
Running it twice gives the same result. Anything it cannot place is listed at the end.
Edits outside the table (imports, helper fns, test modules) are not touched.
"""
import argparse, os, re, subprocess, sys
CMD = "crates/engine/src/cmd.rs"
TABLE = "crates/engine/src/cmd/table"
IDS = "crates/engine/src/cmd/command_ids.txt"
ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"')
def skip(text, i):
"""Index after the comment, string or char literal starting at i, or None."""
if text.startswith("//", i):
j = text.find("\n", i)
return len(text) if j < 0 else j
m = re.match(r'r(#*)"', text[i:])
if m and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")):
end = text.index('"' + m.group(1), i + len(m.group(0)))
return end + 1 + len(m.group(1))
if text[i] == '"':
i += 1
while text[i] != '"':
i += 2 if text[i] == "\\" else 1
return i + 1
if text[i] == "'":
m = re.match(r"'(\\.[^']*|[^\\'])'", text[i:])
if m:
return i + len(m.group(0))
return None
def split_entries(body):
"""The top-level comma-separated entries of a `vec![...]` body."""
entries, depth, start, i = [], 0, 0, 0
while i < len(body):
j = skip(body, i)
if j is not None:
i = j
continue
c = body[i]
if c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
elif c == "," and depth == 0:
entries.append(body[start : i + 1])
start = i + 1
i += 1
if body[start:].strip():
entries.append(body[start:])
return entries
def entry_id(entry):
code = "\n".join(l for l in entry.splitlines() if not l.strip().startswith("//"))
m = ID_RE.search(code)
return m.group(1) if m else None
def build_entries(source):
"""Entries of the `vec![` that starts `fn build()` in the old cmd.rs."""
start = source.index("vec![", source.index("fn build()")) + len("vec![")
depth, i = 1, start
while depth:
j = skip(source, i)
if j is not None:
i = j
continue
depth += source[i] == "["
depth -= source[i] == "]"
i += 1
return split_entries(source[start : i - 1])
def git_show(ref, path):
return subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True, check=True).stdout
class Fragments:
"""Every `vec![...]` of the fragment files, with its entries."""
def __init__(self):
self.files = {}
for d, _, names in os.walk(TABLE):
for n in names:
if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != TABLE:
p = os.path.join(d, n)
if "vec![" in open(p).read():
self.files[p] = open(p).read()
def find(self, cid):
"""(path, entry text) of the entry for a command id, or None."""
for p, t in self.files.items():
for e in self.entries(t):
if entry_id(e) == cid:
return p, e
return None
@staticmethod
def spans(t):
"""(start, end) of each vec! body in a fragment file."""
out, pos = [], 0
while True:
k = t.find("vec![", pos)
if k < 0:
return out
s, depth, i = k + 5, 1, k + 5
while depth:
j = skip(t, i)
if j is not None:
i = j
continue
depth += t[i] == "["
depth -= t[i] == "]"
i += 1
out.append((s, i - 1))
pos = i
def entries(self, t):
return [e for s, f in self.spans(t) for e in split_entries(t[s:f])]
def replace(self, path, old, new):
t = self.files[path]
assert t.count(old) == 1, (path, "entry not unique")
self.files[path] = t.replace(old, new)
def insert_after(self, path, old, new):
self.replace(path, old, old + new)
def delete(self, path, old):
self.replace(path, old, "")
def save(self):
for p, t in self.files.items():
open(p, "w").write(t)
def tidy(e):
"""Entry text as a fragment stores it: starts at its own line, ends with a comma."""
e = e.strip("\n")
return e if e.rstrip().endswith(",") else e.rstrip() + ","
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()
base = {entry_id(e): e for e in build_entries(git_show(a.base, CMD)) if entry_id(e)}
head_list = [e for e in build_entries(git_show(a.head, CMD)) if entry_id(e)]
head = {entry_id(e): e for e in head_list}
fr = Fragments()
ids = open(IDS).read().split("\n")
if ids and ids[-1] == "":
ids.pop()
report = []
for pos, e in enumerate(head_list):
cid = entry_id(e)
text = tidy(e)
here = fr.find(cid)
if here:
path, cur = here
if cid in base and tidy(base[cid]) == text:
continue # the branch did not touch it
if tidy(cur) == text:
continue
if cid in base and tidy(cur) != tidy(base[cid]):
report.append(f"CONFLICT {cid} in {path}: the fragment differs from BASE too; merge by hand")
continue
fr.replace(path, cur, ("\n" if cur.startswith("\n") else "") + text)
report.append(f"changed {cid} in {path}")
continue
if cid in base:
report.append(f"MISSING {cid}: edited by the branch, but no fragment holds it")
continue
pred = next((entry_id(head_list[k]) for k in range(pos - 1, -1, -1) if fr.find(entry_id(head_list[k]))), None)
if pred is None:
report.append(f"UNPLACED {cid}: no predecessor in the fragments")
continue
path, pe = fr.find(pred)
fr.insert_after(path, pe, "\n" + text)
ids.insert(ids.index(pred) + 1, cid) if cid not in ids else None
report.append(f"added {cid} after {pred} in {path}")
for cid, e in base.items():
if cid not in head and (here := fr.find(cid)):
fr.delete(*here)
ids = [i for i in ids if i != cid]
report.append(f"removed {cid} from {here[0]}")
fr.save()
open(IDS, "w").write("\n".join(ids) + "\n")
print("\n".join(report) or "nothing to do")
return 1 if any(r.startswith(("MISSING", "UNPLACED", "CONFLICT")) for r in report) else 0
if __name__ == "__main__":
sys.exit(main())