diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index c519a07d2..d06721545 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -81,11 +81,17 @@ CommandSpec::new("render.preset.apply", "Apply Native Studio", studio_presets::a .params("Same reviewed input as render.preset.resolve, expected_revision required, replace_lighting_and_environment:true and replace_stage:true when an existing stage would change. Re-resolves the complete candidate and publishes one undo or no mutation; camera, optical bindings, geometry and engineering materials are preserved."), CommandSpec::new("render.quality.prepare", "Review Fixed Sampling Budget", studio_presets::quality).icon("settings").noundo().doc_only() .params("id: Q-*; variant:fixed_samples_png; acknowledge_omissions:true. Read-only bounded GPU still-budget projection, not full adaptive/convergence/linear-master quality acceptance. Returns dimensions/samples/depth/seed/denoise and explicit omissions. Never switches executor or mutates a shot."), -CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", shots::duplicate).icon("copy").doc_only() +CommandSpec::new("render.shot.duplicate", "Duplicate Render Shot", crate::checked!("render.shot.duplicate", shots::duplicate)).icon("copy").doc_only() + .contract(&shots::CONTRACT) + .output(crate::schema::output_schema_for::) .params("name, new_name, expected_revision:u64. Copies exact saved setup and resource references in one undo. Existing destinations refuse; captured jobs and camera navigation are unchanged."), -CommandSpec::new("render.shot.rename", "Rename Render Shot", shots::rename).icon("settings").doc_only() +CommandSpec::new("render.shot.rename", "Rename Render Shot", crate::checked!("render.shot.rename", shots::rename)).icon("settings").doc_only() + .contract(&shots::CONTRACT) + .output(crate::schema::output_schema_for::) .params("name, new_name, expected_revision:u64. Renames exact saved setup in one undo; an existing destination or stale review refuses."), -CommandSpec::new("render.shot.remove", "Remove Render Shot", shots::remove).icon("delete").doc_only() +CommandSpec::new("render.shot.remove", "Remove Render Shot", crate::checked!("render.shot.remove", shots::remove)).icon("delete").doc_only() + .contract(&shots::CONTRACT) + .output(crate::schema::output_schema_for::) .params("name, expected_revision:u64. Removes only that saved setup in one undo; retains resources, geometry and captured results."), CommandSpec::new("render.library.preview", "Inspect Original Surface Map", crate::checked!("render.library.preview", library::preview)).icon("appearance").noundo().doc_only() .contract(&library::PREVIEW_CONTRACT) diff --git a/crates/engine/src/cmd/render/shots.rs b/crates/engine/src/cmd/render/shots.rs index 791f375f6..0357d3d86 100644 --- a/crates/engine/src/cmd/render/shots.rs +++ b/crates/engine/src/cmd/render/shots.rs @@ -1,61 +1,65 @@ //! Named saved-shot management through the existing RenderSettings authority. //! No captured jobs, camera navigation, external files or engineering data are edited. +use crate::schema::TypedContract; +use crate::schema::render_shots::{ShotChange, ShotOperation, ShotParams}; use crate::{Result, Session, params::bad}; -use serde::Deserialize; -use serde_json::{Value, json}; +use serde_json::Value; use solidcraft_doc::render_settings::RenderSettings; use std::sync::Arc; -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Named { - name: String, - #[serde(default)] - new_name: Option, - expected_revision: u64, -} -fn change(s: &mut Session, params: &Value, operation: &str) -> Result { +pub(super) const CONTRACT: TypedContract = TypedContract::new(); + +fn change(s: &mut Session, params: &Value, operation: ShotOperation) -> Result { let command = match operation { - "duplicate" => "render.shot.duplicate", - "rename" => "render.shot.rename", - _ => "render.shot.remove", + ShotOperation::Duplicate => "render.shot.duplicate", + ShotOperation::Rename => "render.shot.rename", + ShotOperation::Remove => "render.shot.remove", }; - let input: Named = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: ShotParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.expected_revision != s.revision { return Err(bad(command, "saved shot changed after review; refresh before editing")); } RenderSettings::validate_name(&input.name).map_err(|e| bad(command, e.to_string()))?; let source = s.doc.render.setups.get(&input.name).cloned().ok_or_else(|| bad(command, "no saved shot with that name"))?; let mut settings = (*s.doc.render).clone(); - let output = if operation == "remove" { + let output = if operation == ShotOperation::Remove { if input.new_name.is_some() { return Err(bad(command, "remove does not accept a destination name")); } settings.setups.remove(&input.name); - Value::Null + None } else { - let destination = input.new_name.as_ref().ok_or_else(|| bad(command, "new_name is required"))?; - RenderSettings::validate_name(destination).map_err(|e| bad(command, e.to_string()))?; - if settings.setups.contains_key(destination) { + let destination = input.new_name.ok_or_else(|| bad(command, "new_name is required"))?; + RenderSettings::validate_name(&destination).map_err(|e| bad(command, e.to_string()))?; + if settings.setups.contains_key(&destination) { return Err(bad(command, "destination already exists; saved shots are never overwritten")); } settings.setups.insert(destination.clone(), source); - if operation == "rename" { + if operation == ShotOperation::Rename { settings.setups.remove(&input.name); } - json!(destination) + Some(destination) }; settings.validate().map_err(|e| bad(command, e.to_string()))?; s.doc_mut().render = Arc::new(settings); - Ok(json!({"operation":operation,"source":input.name,"name":output,"resources_preserved":true, - "camera_navigation_unchanged":true,"engineering_properties_unchanged":true,"captured_jobs_unchanged":true})) + let reply = ShotChange { + operation, + source: input.name, + name: output, + resources_preserved: true, + camera_navigation_unchanged: true, + engineering_properties_unchanged: true, + captured_jobs_unchanged: true, + param_warnings: Vec::new(), + }; + serde_json::to_value(reply).map_err(|e| bad(command, e.to_string())) } pub(super) fn duplicate(s: &mut Session, params: &Value) -> Result { - change(s, params, "duplicate") + change(s, params, ShotOperation::Duplicate) } pub(super) fn rename(s: &mut Session, params: &Value) -> Result { - change(s, params, "rename") + change(s, params, ShotOperation::Rename) } pub(super) fn remove(s: &mut Session, params: &Value) -> Result { - change(s, params, "remove") + change(s, params, ShotOperation::Remove) } diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 8b556b572..f7223e34f 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -79,6 +79,7 @@ pub mod print_face; pub mod render; pub mod render_library; pub mod render_lights; +pub mod render_shots; pub mod render_stage; pub mod render_ui; pub mod section; diff --git a/crates/engine/src/schema/render_shots.rs b/crates/engine/src/schema/render_shots.rs new file mode 100644 index 000000000..cc06cc3c4 --- /dev/null +++ b/crates/engine/src/schema/render_shots.rs @@ -0,0 +1,58 @@ +//! Contract and result type for the saved render shot commands in `cmd/render/shots.rs` +//! (#11450). The handlers read this same parameter type, so the contract is exactly what they +//! take; like them, it refuses unknown keys. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +/// Duplicate, rename or remove a saved render shot (a named render setup) in one undo step. The +/// resources it uses, the camera in the view, captured render results and the design's +/// engineering data stay as they are. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ShotParams { + /// The saved shot's exact name. + pub name: String, + /// The name for the copy or the renamed shot: 1 to 128 bytes, without spaces at either end or + /// control characters, and not in use. A name in use is refused, never replaced. Duplicate + /// and rename need it; remove refuses it. A design holds at most 32 shots. + #[serde(default)] + pub new_name: Option, + /// The design's revision when the caller last read it, as `document.inspect` gives it. If + /// the design changed since, the call is refused: read it again and retry. + pub expected_revision: u64, +} + +/// What `render.shot.duplicate`, `render.shot.rename` and `render.shot.remove` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ShotChange { + pub operation: ShotOperation, + /// The shot's name before the change. + pub source: String, + /// The copy's or the renamed shot's name; `null` after a removal. + pub name: Option, + /// Always true: the resources the shot uses are kept. + pub resources_preserved: bool, + /// Always true: the camera in the view doesn't move. + pub camera_navigation_unchanged: bool, + /// Always true: the design's engineering data doesn't change. + pub engineering_properties_unchanged: bool, + /// Always true: captured render results are kept. + pub captured_jobs_unchanged: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What was done to the shot. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ShotOperation { + Duplicate, + Rename, + Remove, +} + +#[cfg(test)] +#[path = "render_shots_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/render_shots_tests.rs b/crates/engine/src/schema/render_shots_tests.rs new file mode 100644 index 000000000..070b3adff --- /dev/null +++ b/crates/engine/src/schema/render_shots_tests.rs @@ -0,0 +1,75 @@ +use serde_json::{Value, json}; + +use super::{ShotChange, ShotParams}; +use crate::Session; +use crate::schema::tests::{assert_keys, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A design with one saved render shot, `Shot`, at the parameter-check level `level`. +fn with_a_shot(level: ParamCheck) -> Session { + let mut s = Session { param_check: level, ..Session::default() }; + s.execute("render.settings.set", &json!({"name": "Shot", "set": {"width": 96, "height": 64}})).unwrap_or_else(|e| panic!("{e}")); + s +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["expected_revision", "name", "new_name"]); +} + +/// The handler refuses these calls after reading them; strict refuses them with its message. +/// They need a saved shot and the design's revision, so the shared helper, which has neither, +/// doesn't fit. +#[test] +fn strict_keeps_todays_errors() { + let cases: [(&str, fn(u64) -> Value); 9] = [ + ("render.shot.duplicate", |_| json!({"name": "Shot", "new_name": "Copy", "expected_revision": 999_999})), + ("render.shot.duplicate", |r| json!({"name": " Shot", "new_name": "Copy", "expected_revision": r})), + ("render.shot.duplicate", |r| json!({"name": "Nope", "new_name": "Copy", "expected_revision": r})), + ("render.shot.duplicate", |r| json!({"name": "Shot", "expected_revision": r})), + ("render.shot.duplicate", |r| json!({"name": "Shot", "new_name": "x".repeat(129), "expected_revision": r})), + ("render.shot.duplicate", |r| json!({"name": "Shot", "new_name": "Shot", "expected_revision": r})), + ("render.shot.rename", |r| json!({"name": "Shot", "new_name": null, "expected_revision": r})), + ("render.shot.rename", |r| json!({"name": "Shot", "new_name": "a\u{7}b", "expected_revision": r})), + ("render.shot.remove", |r| json!({"name": "Shot", "new_name": "Other", "expected_revision": r})), + ]; + for (id, p) in cases { + let error = |level: ParamCheck| { + let mut s = with_a_shot(level); + let p = p(s.revision); + s.execute(id, &p).err().map(|e| e.to_string()) + }; + let off = error(ParamCheck::Off); + assert!(off.is_some(), "{id} {} should fail today", p(0)); + assert_eq!(error(ParamCheck::Strict), off, "{id} {}", p(0)); + } +} + +/// #11450: duplicating, renaming and removing a shot reply as the output schema says, in Warn +/// without warnings. Like the handler, warn and strict refuse a misspelt key. +#[test] +fn shot_commands_reply_with_their_schema() { + let schema = output_schema_for::(); + let schema = schema.as_value(); + let mut s = with_a_shot(ParamCheck::Warn); + let mut run = |id: &str, p: Value| { + let mut p = p; + p["expected_revision"] = json!(s.revision); + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + r + }; + let r = run("render.shot.duplicate", json!({"name": "Shot", "new_name": "Copy"})); + assert_eq!((r["operation"].as_str(), r["name"].as_str()), (Some("duplicate"), Some("Copy")), "{r}"); + let r = run("render.shot.rename", json!({"name": "Copy", "new_name": "Side"})); + assert_eq!((r["operation"].as_str(), r["source"].as_str()), (Some("rename"), Some("Copy")), "{r}"); + let r = run("render.shot.remove", json!({"name": "Side", "new_name": null})); + assert!(r["operation"] == "remove" && r["name"].is_null(), "{r}"); + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = with_a_shot(level); + let p = json!({"name": "Shot", "new_name": "Copy", "expected_revison": s.revision}); + let error = s.execute("render.shot.duplicate", &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("expected_revison"), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 32e671650..be6b92633 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -169,9 +169,6 @@ render.settings.apply render.settings.capture_hdr render.settings.get render.settings.set -render.shot.duplicate -render.shot.remove -render.shot.rename render.start render.status select.clear