Agents and scripts: the view navigation and layout commands describe their exact parameters and reply (#12278) (#12353)
* Agents and scripts: the view navigation and layout commands describe their exact parameters and reply (#12278) describe_command now gives the exact parameters and reply of view.navigate, view.layout, view.history_layout, view.graphics_preset and view.ambient_occlusion, and the warn and strict parameter checks use them. The handlers still read their parameters from the raw JSON, so the new types read each key as its handler does and give its message. Keys the handlers refuse when left out (mode, preset, enabled, camera) are required in the schema but left to the handlers' messages. The replies are built from typed values instead of json! literals, with the same JSON as before. * view.navigate: the contract reads only the keys of the form the handler takes (#12278) The handler reads a motion's keys when motion is given (each motion its own), else direction, else degrees and action, and never the keys of another form. The contract is now read by hand in the same order, so a key of another form is not checked in warn or strict either, and a call that works with the check off works in both. --------- Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
1 parent
54b4bb3f44
commit
429520088a
4 files changed
+866
-38
No files matched your search
@@ -6,8 +6,10 @@ use solidcraft_render::{Camera, StandardView};
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, num, req_vec2, req_vec3, vec3};
|
||||
use crate::schema::view_navigation::{
|
||||
CameraReply, NavigatorParams, NormalToParams, RenderBrowser, RenderFocus, RenderLive, RenderSelect, RibbonTabsOnly, RibbonTabsOnlyParams,
|
||||
StandardViewParams, TabStep, TabStepParams, ZoomTool,
|
||||
AmbientOcclusionParams, AmbientOcclusionResult, CameraReply, GraphicsPreset, GraphicsPresetParams, GraphicsPresetResult, HistoryDock,
|
||||
HistoryLayoutParams, HistoryLayoutResult, LayoutMode, LayoutParams, LayoutResult, NavigateParams, NavigateResult, NavigatorParams,
|
||||
NormalToParams, PresetQuality, RenderBrowser, RenderFocus, RenderLive, RenderSelect, RibbonTabsOnly, RibbonTabsOnlyParams, StandardViewParams,
|
||||
TabStep, TabStepParams, ZoomTool,
|
||||
};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Sel, Session};
|
||||
@@ -21,6 +23,11 @@ const TAB_STEP_CONTRACT: TypedContract<TabStepParams> = TypedContract::new();
|
||||
const STANDARD_VIEW_CONTRACT: TypedContract<StandardViewParams> = TypedContract::new();
|
||||
const NORMAL_TO_CONTRACT: TypedContract<NormalToParams> = TypedContract::new();
|
||||
const RIBBON_TABS_ONLY_CONTRACT: TypedContract<RibbonTabsOnlyParams> = TypedContract::new();
|
||||
const LAYOUT_CONTRACT: TypedContract<LayoutParams> = TypedContract::new();
|
||||
const HISTORY_LAYOUT_CONTRACT: TypedContract<HistoryLayoutParams> = TypedContract::new();
|
||||
const GRAPHICS_PRESET_CONTRACT: TypedContract<GraphicsPresetParams> = TypedContract::new();
|
||||
const AMBIENT_OCCLUSION_CONTRACT: TypedContract<AmbientOcclusionParams> = TypedContract::new();
|
||||
const NAVIGATE_CONTRACT: TypedContract<NavigateParams> = TypedContract::new();
|
||||
|
||||
// Both existing request forms share the Browser command and its published schema.
|
||||
#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
|
||||
@@ -115,22 +122,24 @@ CommandSpec::new("view.render_dock", "Move Render Dock", crate::checked!("view.r
|
||||
.contract(&RENDER_DOCK_CONTRACT)
|
||||
.output(crate::schema::output_schema_for::<crate::schema::view_navigation::RenderDock>)
|
||||
.params("panel: inspector|browser; side: left|right → {panel, side}; Render dock UI preference; headless echo only, no document edits or undo"),
|
||||
CommandSpec::new("view.layout", "Workspace layout", layout)
|
||||
.icon("settings").noundo().doc_only().params("mode: floating|compact → validated workspace layout; display only, never opens a dialog"),
|
||||
CommandSpec::new("view.history_layout", "History layout", history_layout)
|
||||
.icon("settings").noundo().doc_only().params("width?: 1..1000000; dock?: bottom|left|under_browser|browser (browser: the history in the browser, no timeline); collapsed?: bool → validated layout request; display only, never opens a dialog"),
|
||||
CommandSpec::new("view.graphics_preset", "Graphics Preset", graphics_preset)
|
||||
.icon("settings").noundo().doc_only().params("preset: performance|quality → preset, enabled, display_quality, supersampling, supersampling_adaptive; Quality: AO, Fine, adaptive 2x SSAA; Performance: no AO, Normal, no SSAA"),
|
||||
CommandSpec::new("view.ambient_occlusion", "Ambient Occlusion", ambient_occlusion)
|
||||
.icon("settings").noundo().doc_only().params("enabled: bool → enabled; apply soft contact shading in the GPU viewport"),
|
||||
CommandSpec::new("view.layout", "Workspace layout", crate::checked!("view.layout", layout))
|
||||
.icon("settings").noundo().doc_only().contract(&LAYOUT_CONTRACT).output(output_schema_for::<LayoutResult>).params("mode: floating|compact → validated workspace layout; display only, never opens a dialog"),
|
||||
CommandSpec::new("view.history_layout", "History layout", crate::checked!("view.history_layout", history_layout))
|
||||
.icon("settings").noundo().doc_only().contract(&HISTORY_LAYOUT_CONTRACT).output(output_schema_for::<HistoryLayoutResult>).params("width?: 1..1000000; dock?: bottom|left|under_browser|browser (browser: the history in the browser, no timeline); collapsed?: bool → validated layout request; display only, never opens a dialog"),
|
||||
CommandSpec::new("view.graphics_preset", "Graphics Preset", crate::checked!("view.graphics_preset", graphics_preset))
|
||||
.icon("settings").noundo().doc_only().contract(&GRAPHICS_PRESET_CONTRACT).output(output_schema_for::<GraphicsPresetResult>).params("preset: performance|quality → preset, enabled, display_quality, supersampling, supersampling_adaptive; Quality: AO, Fine, adaptive 2x SSAA; Performance: no AO, Normal, no SSAA"),
|
||||
CommandSpec::new("view.ambient_occlusion", "Ambient Occlusion", crate::checked!("view.ambient_occlusion", ambient_occlusion))
|
||||
.icon("settings").noundo().doc_only().contract(&AMBIENT_OCCLUSION_CONTRACT).output(output_schema_for::<AmbientOcclusionResult>).params("enabled: bool → enabled; apply soft contact shading in the GPU viewport"),
|
||||
CommandSpec::new("view.perspective", "Perspective view", perspective)
|
||||
.icon("perspective").noundo().doc_only().params("enabled: bool → enabled; draw the view in perspective, or orthographic when false; a sketch being edited is always shown orthographic"),
|
||||
CommandSpec::new("view.angle_readout", "View Angles", crate::checked!("view.angle_readout", angle_readout))
|
||||
.icon("camera").noundo().doc_only().contract(&ANGLE_READOUT_CONTRACT).output(crate::schema::output_schema_for::<crate::schema::view_navigation::AngleReadoutResult>).params("enabled: bool → enabled; show the view's pitch, yaw and roll (degrees, as view.apply's camera in radians) and Ortho or Persp under the orientation gizmo; display only, never opens a dialog"),
|
||||
CommandSpec::new("view.navigate", "Navigate View", navigate)
|
||||
CommandSpec::new("view.navigate", "Navigate View", crate::checked!("view.navigate", navigate))
|
||||
.icon("orbit")
|
||||
.noundo()
|
||||
.doc_only()
|
||||
.contract(&NAVIGATE_CONTRACT)
|
||||
.output(output_schema_for::<NavigateResult>)
|
||||
.params("camera: Camera; direction?: [x,y,z] in the camera's up-axis frame; or action: left|right|up|down|clockwise|counterclockwise|home|fit, degrees?: 0..180 (how far left|right|up|down turn; default 90), fit?: bool (frame the whole model from the new direction as well, as home does; default false); or motion: pan|orbit|zoom, delta?: [dx,dy] (pixels, each ±10000), free_orbit?: bool (orbit through poles, default false), viewport?: [width,height] (1..1000000, required for pan or pivot), pivot?: [x,y,z], factor?: 0.05..20 (required for zoom), anchor?: [x,y,z] → camera, fit, continuous?"),
|
||||
CommandSpec::new("view.normal_to", "Normal to Selection", crate::checked!("view.normal_to", normal_to))
|
||||
.icon("camera")
|
||||
@@ -467,31 +476,39 @@ fn layout(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(Value::as_str)
|
||||
.filter(|mode| matches!(*mode, "floating" | "compact"))
|
||||
.ok_or_else(|| bad("view.layout", "mode must be floating or compact"))?;
|
||||
Ok(json!({"mode": mode}))
|
||||
let mode = if mode == "compact" { LayoutMode::Compact } else { LayoutMode::Floating };
|
||||
typed_reply("view.layout", LayoutResult { mode, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// A command's typed reply as the JSON it sends.
|
||||
fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn history_layout(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "view.history_layout";
|
||||
let mut result = serde_json::Map::new();
|
||||
let mut result = HistoryLayoutResult { width: None, dock: None, collapsed: None, param_warnings: Vec::new() };
|
||||
if let Some(value) = p.get("width") {
|
||||
let width = value
|
||||
.as_f64()
|
||||
.filter(|v| v.is_finite() && (1.0..=1_000_000.0).contains(v))
|
||||
.ok_or_else(|| bad(cmd, "width must be finite and within 1..1000000"))?;
|
||||
result.insert("width".into(), json!(width));
|
||||
result.width = Some(width);
|
||||
}
|
||||
if let Some(value) = p.get("dock") {
|
||||
let dock = value
|
||||
.as_str()
|
||||
.filter(|v| matches!(*v, "bottom" | "left" | "under_browser" | "browser"))
|
||||
.ok_or_else(|| bad(cmd, "dock must be bottom, left, under_browser or browser"))?;
|
||||
result.insert("dock".into(), json!(dock));
|
||||
let dock = match value.as_str() {
|
||||
Some("bottom") => HistoryDock::Bottom,
|
||||
Some("left") => HistoryDock::Left,
|
||||
Some("under_browser") => HistoryDock::UnderBrowser,
|
||||
Some("browser") => HistoryDock::Browser,
|
||||
_ => return Err(bad(cmd, "dock must be bottom, left, under_browser or browser")),
|
||||
};
|
||||
result.dock = Some(dock);
|
||||
}
|
||||
if let Some(value) = p.get("collapsed") {
|
||||
let collapsed = value.as_bool().ok_or_else(|| bad(cmd, "collapsed must be a boolean"))?;
|
||||
result.insert("collapsed".into(), json!(collapsed));
|
||||
result.collapsed = Some(value.as_bool().ok_or_else(|| bad(cmd, "collapsed must be a boolean"))?);
|
||||
}
|
||||
Ok(Value::Object(result))
|
||||
typed_reply(cmd, result)
|
||||
}
|
||||
|
||||
fn navigate(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -559,7 +576,7 @@ fn navigate(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, "unknown navigation action")),
|
||||
}
|
||||
}
|
||||
Ok(json!({"camera": cam, "fit": fit}))
|
||||
typed_reply(cmd, NavigateResult { camera: cam, fit, continuous: None, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// Direct manipulation is stateless, bounded and independent of document evaluation.
|
||||
@@ -611,7 +628,7 @@ fn continuous(mut cam: Camera, p: &Value) -> Result<Value> {
|
||||
if !cam.is_valid() {
|
||||
return Err(bad(cmd, "motion produced an invalid camera"));
|
||||
}
|
||||
Ok(json!({"camera":cam, "fit":false, "continuous":true}))
|
||||
typed_reply(cmd, NavigateResult { camera: cam, fit: false, continuous: Some(true), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// At a halfway tie prefer the heading nearer the front plan view.
|
||||
@@ -1060,7 +1077,7 @@ mod tests {
|
||||
|
||||
fn ambient_occlusion(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let enabled = p.get("enabled").and_then(Value::as_bool).ok_or_else(|| bad("view.ambient_occlusion", "enabled must be a boolean"))?;
|
||||
Ok(json!({"enabled": enabled}))
|
||||
typed_reply("view.ambient_occlusion", AmbientOcclusionResult { enabled, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
fn perspective(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1139,14 +1156,23 @@ mod ambient_occlusion_tests {
|
||||
|
||||
/// One preset for contact shading, tessellation and supersampling. MSAA stays independent.
|
||||
fn graphics_preset(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let preset = p.get("preset").and_then(Value::as_str);
|
||||
let enabled = match preset {
|
||||
Some("quality") => true,
|
||||
Some("performance") => false,
|
||||
let preset = match p.get("preset").and_then(Value::as_str) {
|
||||
Some("quality") => GraphicsPreset::Quality,
|
||||
Some("performance") => GraphicsPreset::Performance,
|
||||
_ => return Err(bad("view.graphics_preset", "preset must be performance or quality")),
|
||||
};
|
||||
Ok(json!({"preset": preset, "enabled": enabled, "display_quality": if enabled { "fine" } else { "normal" },
|
||||
"supersampling": if enabled { 2.0 } else { 1.0 }, "supersampling_adaptive": true}))
|
||||
let enabled = preset == GraphicsPreset::Quality;
|
||||
typed_reply(
|
||||
"view.graphics_preset",
|
||||
GraphicsPresetResult {
|
||||
preset,
|
||||
enabled,
|
||||
display_quality: if enabled { PresetQuality::Fine } else { PresetQuality::Normal },
|
||||
supersampling: if enabled { 2.0 } else { 1.0 },
|
||||
supersampling_adaptive: true,
|
||||
param_warnings: Vec::new(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -285,13 +285,8 @@ timeline.roll_to
|
||||
timeline.rollback
|
||||
timeline.suppress
|
||||
timeline.ungroup
|
||||
view.ambient_occlusion
|
||||
view.apply
|
||||
view.delete
|
||||
view.graphics_preset
|
||||
view.history_layout
|
||||
view.layout
|
||||
view.list
|
||||
view.navigate
|
||||
view.rename
|
||||
view.save
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Render shell requests. The UI applies validated echoes without design edits.
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::check::whole;
|
||||
use solidcore_record::{Vec2, Vec3};
|
||||
use solidcraft_geom::Vec3Geom;
|
||||
|
||||
use super::types::{CameraParam, present};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
@@ -316,6 +320,468 @@ fn nullable<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<String>>, D
|
||||
Option::<String>::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// A key's value as its handler reads it: `read` takes the raw JSON value, and anything it
|
||||
/// refuses gets the handler's own message, whole (no key put in front).
|
||||
fn read_with<'de, D: Deserializer<'de>, T>(d: D, message: &str, read: impl FnOnce(&Value) -> Option<T>) -> Result<Option<T>, D::Error> {
|
||||
let value = Value::deserialize(d)?;
|
||||
read(&value).map(Some).ok_or_else(|| serde::de::Error::custom(whole(message)))
|
||||
}
|
||||
|
||||
/// A value `T` deserializes from, or the handler's message.
|
||||
fn read_as<'de, D: Deserializer<'de>, T: serde::de::DeserializeOwned>(d: D, message: &str) -> Result<Option<T>, D::Error> {
|
||||
read_with(d, message, |v| serde_json::from_value(v.clone()).ok())
|
||||
}
|
||||
|
||||
/// A deserializer for a key, with the handler's message for a value it refuses.
|
||||
macro_rules! reads {
|
||||
($name:ident -> $ty:ty, $message:literal) => {
|
||||
fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
|
||||
read_as(d, $message)
|
||||
}
|
||||
};
|
||||
($name:ident -> $ty:ty, $message:literal, $read:expr) => {
|
||||
fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
|
||||
read_with(d, $message, $read)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// A key the handlers refuse when it is left out, with their message: optional in the type, so
|
||||
/// the check leaves the refusal to the handler, and required in the schema.
|
||||
fn require(schema: &mut Schema, key: &str) {
|
||||
super::motion::require(schema, key);
|
||||
}
|
||||
|
||||
fn mode_required(schema: &mut Schema) {
|
||||
require(schema, "mode");
|
||||
}
|
||||
|
||||
fn preset_required(schema: &mut Schema) {
|
||||
require(schema, "preset");
|
||||
}
|
||||
|
||||
fn enabled_required(schema: &mut Schema) {
|
||||
require(schema, "enabled");
|
||||
}
|
||||
|
||||
fn camera_required(schema: &mut Schema) {
|
||||
require(schema, "camera");
|
||||
}
|
||||
|
||||
/// How the workspace is drawn.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LayoutMode {
|
||||
Floating,
|
||||
Compact,
|
||||
}
|
||||
|
||||
reads!(layout_mode -> LayoutMode, "mode must be floating or compact");
|
||||
|
||||
/// `view.layout`: the workspace layout, floating or compact. A display preference the app keeps;
|
||||
/// the design, the camera and the active tool are not changed, and it never opens a dialog.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = mode_required)]
|
||||
pub struct LayoutParams {
|
||||
// Optional in the type and required in the schema (`mode_required`): left out, the handler
|
||||
// refuses it with its own message.
|
||||
/// `floating` or `compact`.
|
||||
#[serde(default, deserialize_with = "layout_mode", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "LayoutMode")]
|
||||
pub mode: Option<LayoutMode>,
|
||||
}
|
||||
|
||||
/// What `view.layout` returns: the layout asked for.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct LayoutResult {
|
||||
pub mode: LayoutMode,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// Where the history sits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum HistoryDock {
|
||||
Bottom,
|
||||
Left,
|
||||
UnderBrowser,
|
||||
/// The history in the browser, with no timeline.
|
||||
Browser,
|
||||
}
|
||||
|
||||
reads!(history_width -> f64, "width must be finite and within 1..1000000", |v| v.as_f64().filter(|w| w.is_finite() && (1.0..=1_000_000.0).contains(w)));
|
||||
reads!(history_dock -> HistoryDock, "dock must be bottom, left, under_browser or browser");
|
||||
reads!(history_collapsed -> bool, "collapsed must be a boolean");
|
||||
|
||||
/// `view.history_layout`: the history's width, dock and whether it is collapsed; each given
|
||||
/// key is checked and echoed, and a key left out stays as it is. A display preference the app
|
||||
/// keeps; the design is not changed and it never opens a dialog.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct HistoryLayoutParams {
|
||||
/// The history's width, 1 to 1000000.
|
||||
#[serde(default, deserialize_with = "history_width", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "f64", range(min = 1.0, max = 1000000.0))]
|
||||
pub width: Option<f64>,
|
||||
/// Where the history sits.
|
||||
#[serde(default, deserialize_with = "history_dock", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "HistoryDock")]
|
||||
pub dock: Option<HistoryDock>,
|
||||
/// True collapses the history, false opens it.
|
||||
#[serde(default, deserialize_with = "history_collapsed", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub collapsed: Option<bool>,
|
||||
}
|
||||
|
||||
/// What `view.history_layout` returns: the keys given, checked.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct HistoryLayoutResult {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dock: Option<HistoryDock>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub collapsed: Option<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<String>,
|
||||
}
|
||||
|
||||
/// A graphics preset.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum GraphicsPreset {
|
||||
Performance,
|
||||
Quality,
|
||||
}
|
||||
|
||||
/// The tessellation a graphics preset asks for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PresetQuality {
|
||||
Fine,
|
||||
Normal,
|
||||
}
|
||||
|
||||
reads!(graphics_preset_value -> GraphicsPreset, "preset must be performance or quality");
|
||||
|
||||
/// `view.graphics_preset`: one preset for ambient occlusion, tessellation and supersampling.
|
||||
/// Quality: ambient occlusion on, Fine, adaptive 2x supersampling. Performance: no ambient
|
||||
/// occlusion, Normal, no supersampling. MSAA stays independent. A display setting the app keeps;
|
||||
/// the design is not changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = preset_required)]
|
||||
pub struct GraphicsPresetParams {
|
||||
// Optional in the type and required in the schema (`preset_required`), as `mode` above.
|
||||
/// `performance` or `quality`.
|
||||
#[serde(default, deserialize_with = "graphics_preset_value", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "GraphicsPreset")]
|
||||
pub preset: Option<GraphicsPreset>,
|
||||
}
|
||||
|
||||
/// What `view.graphics_preset` returns: the preset and the settings it stands for.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct GraphicsPresetResult {
|
||||
pub preset: GraphicsPreset,
|
||||
/// Ambient occlusion on or off.
|
||||
pub enabled: bool,
|
||||
pub display_quality: PresetQuality,
|
||||
/// The supersampling factor: 2 for Quality, 1 for Performance.
|
||||
pub supersampling: f64,
|
||||
pub supersampling_adaptive: 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<String>,
|
||||
}
|
||||
|
||||
reads!(ambient_occlusion_enabled -> bool, "enabled must be a boolean");
|
||||
|
||||
/// `view.ambient_occlusion`: soft contact shading in the GPU viewport, on or off. A display
|
||||
/// setting the app keeps; the design is not changed.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = enabled_required)]
|
||||
pub struct AmbientOcclusionParams {
|
||||
// Optional in the type and required in the schema (`enabled_required`), as `mode` above.
|
||||
/// True turns it on, false off.
|
||||
#[serde(default, deserialize_with = "ambient_occlusion_enabled", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub enabled: Option<bool>,
|
||||
}
|
||||
|
||||
/// What `view.ambient_occlusion` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct AmbientOcclusionResult {
|
||||
/// Whether it is on now.
|
||||
pub enabled: 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<String>,
|
||||
}
|
||||
|
||||
/// What a navigation turns the camera by.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NavigateAction {
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
Clockwise,
|
||||
Counterclockwise,
|
||||
/// The isometric view, framed on the whole model.
|
||||
Home,
|
||||
/// Frame the whole model.
|
||||
Fit,
|
||||
}
|
||||
|
||||
/// A direct manipulation of the camera.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NavigateMotion {
|
||||
Pan,
|
||||
Orbit,
|
||||
Zoom,
|
||||
}
|
||||
|
||||
/// A point of finite numbers, `[x, y]` or `[x, y, z]` (or an object with those keys), each
|
||||
/// within `lo..=hi`.
|
||||
fn bounded_point(keys: &[&str], lo: f64, hi: f64) -> Schema {
|
||||
let n = keys.len();
|
||||
// `params::finite` takes numbers below 1e9 in size; the others' bounds are inclusive.
|
||||
let number = if hi >= 1e9 {
|
||||
json!({"type": "number", "exclusiveMinimum": lo, "exclusiveMaximum": hi})
|
||||
} else {
|
||||
json!({"type": "number", "minimum": lo, "maximum": hi})
|
||||
};
|
||||
let properties: serde_json::Map<String, Value> = keys.iter().map(|k| ((*k).to_string(), number.clone())).collect();
|
||||
json_schema!({
|
||||
"anyOf": [
|
||||
{"type": "array", "items": number, "minItems": n, "maxItems": n},
|
||||
{"type": "object", "properties": properties, "required": keys}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
fn degrees_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "Degrees, above 0 and at most 180.", "type": "number", "exclusiveMinimum": 0, "maximum": 180})
|
||||
}
|
||||
|
||||
fn point3_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let mut s = bounded_point(&["x", "y", "z"], -1e9, 1e9);
|
||||
s.insert("description".into(), "A point [x, y, z] or {\"x\", \"y\", \"z\"}, of numbers.".into());
|
||||
s
|
||||
}
|
||||
|
||||
fn delta_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let mut s = bounded_point(&["x", "y"], -1e4, 1e4);
|
||||
s.insert("description".into(), "Pixels [dx, dy] (or {\"x\", \"y\"}), each within ±10000.".into());
|
||||
s
|
||||
}
|
||||
|
||||
fn viewport_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
let mut s = bounded_point(&["x", "y"], 1.0, 1e6);
|
||||
s.insert("description".into(), "The viewport's size in pixels [width, height] (or {\"x\", \"y\"}), each 1 to 1000000.".into());
|
||||
s
|
||||
}
|
||||
|
||||
/// The camera `view.navigate` turns: as the other view commands read it, and also with yaw and
|
||||
/// roll within ±1e6 and pitch within ±π/2 (else "invalid camera"). Read before anything else.
|
||||
fn navigate_camera<'de, D: Deserializer<'de>>(d: D) -> Result<Option<CameraParam>, D::Error> {
|
||||
read_with(d, "invalid camera", |v| {
|
||||
crate::cmd::camera_form(v)
|
||||
.filter(|c| c.yaw.abs() <= 1e6 && c.roll.abs() <= 1e6 && c.pitch.abs() <= std::f64::consts::FRAC_PI_2)
|
||||
.map(CameraParam)
|
||||
})
|
||||
}
|
||||
|
||||
reads!(navigate_fit -> bool, "fit must be a boolean");
|
||||
reads!(
|
||||
navigate_direction -> Vec3,
|
||||
"direction must be a finite nonzero vector of length at most 2",
|
||||
|v| crate::params::vec3(v).filter(|v| v.is_finite() && v.len() <= 2.0 && v.normalized().is_some())
|
||||
);
|
||||
reads!(navigate_action -> NavigateAction, "unknown navigation action");
|
||||
reads!(
|
||||
navigate_degrees -> f64,
|
||||
"degrees must be a number above 0 and at most 180",
|
||||
|v| v.as_f64().filter(|d| d.is_finite() && *d > 0.0 && *d <= 180.0)
|
||||
);
|
||||
reads!(navigate_motion -> NavigateMotion, "unknown navigation motion");
|
||||
reads!(navigate_free_orbit -> bool, "free_orbit must be a boolean");
|
||||
/// A pan or orbit's `delta` and an orbit's `viewport` are read in two steps, as the handler
|
||||
/// does: a point, then its bounds, each with its own message.
|
||||
fn bounded_point_key<'de, D: Deserializer<'de>>(d: D, key: &str, in_bounds: fn(Vec2) -> bool, out_of_bounds: &str) -> Result<Option<Vec2>, D::Error> {
|
||||
let point = read_with(d, &format!("`{key}` must be a point [x, y]"), crate::params::vec2)?;
|
||||
match point {
|
||||
Some(p) if !in_bounds(p) => Err(serde::de::Error::custom(whole(out_of_bounds))),
|
||||
point => Ok(point),
|
||||
}
|
||||
}
|
||||
|
||||
fn navigate_delta<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec2>, D::Error> {
|
||||
bounded_point_key(d, "delta", |p| p.x.abs() <= 1e4 && p.y.abs() <= 1e4, "motion deltas must be within ±10000 pixels")
|
||||
}
|
||||
|
||||
fn navigate_viewport<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec2>, D::Error> {
|
||||
bounded_point_key(d, "viewport", |p| (1.0..=1e6).contains(&p.x) && (1.0..=1e6).contains(&p.y), "viewport dimensions must be in 1..1000000")
|
||||
}
|
||||
reads!(navigate_pivot -> Vec3, "`pivot` must be a point [x, y, z]", crate::params::vec3);
|
||||
reads!(navigate_anchor -> Vec3, "`anchor` must be a point [x, y, z]", crate::params::vec3);
|
||||
reads!(
|
||||
navigate_factor -> f64,
|
||||
"factor must be in 0.05..20",
|
||||
|v| v.as_f64().filter(|f| f.is_finite() && f.abs() < 1e9 && (0.05..=20.0).contains(f))
|
||||
);
|
||||
|
||||
/// `view.navigate`: turn, pan, orbit or zoom a camera without changing the design or adding to
|
||||
/// undo. `camera` is always needed, and then one of three: `direction` (look from it), `action`
|
||||
/// (a turn, a roll, home or fit) or `motion` (direct manipulation, which wins when given and
|
||||
/// does not take `fit`). Keys of the other forms are not used.
|
||||
// Deserialize is written out below rather than derived: the handler reads only the keys of the
|
||||
// form it takes, so a key of another form is neither read nor checked.
|
||||
#[derive(Debug, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields, transform = camera_required)]
|
||||
pub struct NavigateParams {
|
||||
// Optional in the type and required in the schema (`camera_required`), as `mode` above.
|
||||
/// The camera to move, as `ui.inspect` gives it. Its yaw and roll must also be within ±1e6
|
||||
/// and its pitch within ±π/2.
|
||||
#[serde(default, deserialize_with = "navigate_camera", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "CameraParam")]
|
||||
pub camera: Option<CameraParam>,
|
||||
/// Also frame the whole model from the new direction, as home does. Not with `motion`.
|
||||
/// Default: false.
|
||||
#[serde(default, deserialize_with = "navigate_fit", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub fit: Option<bool>,
|
||||
/// Look from this direction, in the camera's up-axis frame: a finite nonzero vector of
|
||||
/// length at most 2.
|
||||
#[serde(default, deserialize_with = "navigate_direction", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "point3_schema")]
|
||||
pub direction: Option<Vec3>,
|
||||
/// A turn without `direction`: left, right, up or down turn the view `degrees`, clockwise and
|
||||
/// counterclockwise roll it a quarter turn, home shows the isometric view framed, fit frames
|
||||
/// the model.
|
||||
#[serde(default, deserialize_with = "navigate_action", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "NavigateAction")]
|
||||
pub action: Option<NavigateAction>,
|
||||
/// How far left, right, up or down turn the view, above 0 and at most 180. Default: 90.
|
||||
#[serde(default, deserialize_with = "navigate_degrees", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "degrees_schema")]
|
||||
pub degrees: Option<f64>,
|
||||
/// Direct manipulation: pan and orbit need `delta`, pan and an orbit about a `pivot` need
|
||||
/// `viewport`, zoom needs `factor`.
|
||||
#[serde(default, deserialize_with = "navigate_motion", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "NavigateMotion")]
|
||||
pub motion: Option<NavigateMotion>,
|
||||
/// Pan or orbit by this many pixels.
|
||||
#[serde(default, deserialize_with = "navigate_delta", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "delta_schema")]
|
||||
pub delta: Option<Vec2>,
|
||||
/// Orbit through the poles. Default: false.
|
||||
#[serde(default, deserialize_with = "navigate_free_orbit", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "bool")]
|
||||
pub free_orbit: Option<bool>,
|
||||
/// The viewport's size in pixels, for a pan or an orbit about a pivot.
|
||||
#[serde(default, deserialize_with = "navigate_viewport", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "viewport_schema")]
|
||||
pub viewport: Option<Vec2>,
|
||||
/// Orbit about this point (mm) rather than the camera's target.
|
||||
#[serde(default, deserialize_with = "navigate_pivot", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "point3_schema")]
|
||||
pub pivot: Option<Vec3>,
|
||||
/// The zoom factor, 0.05 to 20.
|
||||
#[serde(default, deserialize_with = "navigate_factor", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(with = "f64", range(min = 0.05, max = 20.0))]
|
||||
pub factor: Option<f64>,
|
||||
/// Zoom towards this point (mm). Default: the camera's target.
|
||||
#[serde(default, deserialize_with = "navigate_anchor", skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(schema_with = "point3_schema")]
|
||||
pub anchor: Option<Vec3>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for NavigateParams {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let p = serde_json::Map::<String, Value>::deserialize(d)?;
|
||||
navigate_form(&p).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
/// A key's value through its reader, or `None` when the key is left out.
|
||||
fn navigate_key<'a, T>(
|
||||
p: &'a serde_json::Map<String, Value>,
|
||||
key: &str,
|
||||
read: impl FnOnce(&'a Value) -> Result<Option<T>, serde_json::Error>,
|
||||
) -> Result<Option<T>, serde_json::Error> {
|
||||
p.get(key).map_or(Ok(None), read)
|
||||
}
|
||||
|
||||
/// The keys `view.navigate`'s handler reads, in its order: the camera and `fit`, then those of
|
||||
/// a motion (each motion its own), of a direction, or of an action.
|
||||
fn navigate_form(p: &serde_json::Map<String, Value>) -> Result<NavigateParams, serde_json::Error> {
|
||||
let mut form = NavigateParams {
|
||||
camera: navigate_key(p, "camera", navigate_camera)?,
|
||||
fit: navigate_key(p, "fit", navigate_fit)?,
|
||||
direction: None,
|
||||
action: None,
|
||||
degrees: None,
|
||||
motion: None,
|
||||
delta: None,
|
||||
free_orbit: None,
|
||||
viewport: None,
|
||||
pivot: None,
|
||||
factor: None,
|
||||
anchor: None,
|
||||
};
|
||||
if p.contains_key("motion") {
|
||||
form.free_orbit = navigate_key(p, "free_orbit", navigate_free_orbit)?;
|
||||
form.motion = navigate_key(p, "motion", navigate_motion)?;
|
||||
match form.motion {
|
||||
Some(NavigateMotion::Pan) => {
|
||||
form.delta = navigate_key(p, "delta", navigate_delta)?;
|
||||
form.viewport = navigate_key(p, "viewport", navigate_viewport)?;
|
||||
}
|
||||
Some(NavigateMotion::Orbit) => {
|
||||
form.delta = navigate_key(p, "delta", navigate_delta)?;
|
||||
// An orbit needs the viewport only about a pivot.
|
||||
if p.contains_key("pivot") {
|
||||
form.pivot = navigate_key(p, "pivot", navigate_pivot)?;
|
||||
form.viewport = navigate_key(p, "viewport", navigate_viewport)?;
|
||||
}
|
||||
}
|
||||
Some(NavigateMotion::Zoom) => {
|
||||
form.factor = navigate_key(p, "factor", navigate_factor)?;
|
||||
form.anchor = navigate_key(p, "anchor", navigate_anchor)?;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
} else if p.contains_key("direction") {
|
||||
form.direction = navigate_key(p, "direction", navigate_direction)?;
|
||||
} else {
|
||||
form.degrees = navigate_key(p, "degrees", navigate_degrees)?;
|
||||
form.action = navigate_key(p, "action", navigate_action)?;
|
||||
}
|
||||
Ok(form)
|
||||
}
|
||||
|
||||
/// What `view.navigate` returns: the camera after the move, and whether the window should also
|
||||
/// frame the whole model. The window applies both; the design is not changed.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct NavigateResult {
|
||||
/// The camera now.
|
||||
#[schemars(with = "CameraParam")]
|
||||
pub camera: solidcraft_render::Camera,
|
||||
/// Frame the whole model from the new direction.
|
||||
pub fit: bool,
|
||||
/// True for a `motion`; absent for a turn.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub continuous: Option<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<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "view_navigation_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,6 +1,9 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{AngleReadoutParams, CameraReply, NormalToParams, StandardViewParams, TabStep, TabStepParams};
|
||||
use super::{
|
||||
AmbientOcclusionParams, AmbientOcclusionResult, AngleReadoutParams, CameraReply, GraphicsPresetParams, GraphicsPresetResult, HistoryLayoutParams,
|
||||
HistoryLayoutResult, LayoutParams, LayoutResult, NavigateParams, NavigateResult, NormalToParams, StandardViewParams, TabStep, TabStepParams,
|
||||
};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
|
||||
use crate::schema::types::CameraParam;
|
||||
@@ -11,6 +14,14 @@ fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<AngleReadoutParams>(), &["enabled"]);
|
||||
assert_keys(input_schema_for::<StandardViewParams>(), &["camera"]);
|
||||
assert_keys(input_schema_for::<NormalToParams>(), &["camera"]);
|
||||
assert_keys(input_schema_for::<LayoutParams>(), &["mode"]);
|
||||
assert_keys(input_schema_for::<HistoryLayoutParams>(), &["collapsed", "dock", "width"]);
|
||||
assert_keys(input_schema_for::<GraphicsPresetParams>(), &["preset"]);
|
||||
assert_keys(input_schema_for::<AmbientOcclusionParams>(), &["enabled"]);
|
||||
assert_keys(
|
||||
input_schema_for::<NavigateParams>(),
|
||||
&["action", "anchor", "camera", "degrees", "delta", "direction", "factor", "fit", "free_orbit", "motion", "pivot", "viewport"],
|
||||
);
|
||||
}
|
||||
|
||||
const STANDARD_VIEWS: [&str; 7] = ["view.front", "view.back", "view.left", "view.right", "view.top", "view.bottom", "view.isometric"];
|
||||
@@ -303,3 +314,333 @@ fn navigator_checks_and_echoes_its_settings_and_refuses_a_missing_body() {
|
||||
let spec = crate::find_command("view.navigator").unwrap();
|
||||
assert!(!spec.undoable && spec.contract.is_some() && spec.output.is_some());
|
||||
}
|
||||
|
||||
const LAYOUT_COMMANDS: [&str; 5] = ["view.layout", "view.history_layout", "view.graphics_preset", "view.ambient_occlusion", "view.navigate"];
|
||||
|
||||
/// A camera for `view.navigate`.
|
||||
fn nav_camera() -> Value {
|
||||
camera(json!({"target": [0, 0, 0], "yaw": 0.0, "pitch": 0.0, "distance": 100, "fov": 0.0}))
|
||||
}
|
||||
|
||||
/// A `view.navigate` call: the camera and `extra`'s keys.
|
||||
fn nav(extra: Value) -> Value {
|
||||
let mut p = json!({"camera": nav_camera()});
|
||||
if let (Some(o), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
|
||||
o.extend(extra.clone());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Each command publishes its input and output schemas with a contract, is display only, and its
|
||||
/// required keys are the ones its handler refuses a call without.
|
||||
#[test]
|
||||
fn the_commands_publish_contracts_and_schemas() {
|
||||
let mut s = Session::default();
|
||||
for id in LAYOUT_COMMANDS {
|
||||
let spec = crate::find_command(id).unwrap();
|
||||
assert!(spec.contract.is_some() && spec.output.is_some() && !spec.undoable, "{id}");
|
||||
let d = s.execute("engine.describe", &json!({"command": id})).unwrap();
|
||||
assert_eq!(d["input"]["additionalProperties"], false, "{id}");
|
||||
assert_eq!(d["output"]["type"], "object", "{id}");
|
||||
}
|
||||
let mut required = |id: &str| {
|
||||
let d = s.execute("engine.describe", &json!({"command": id})).unwrap();
|
||||
d["input"]["required"].clone()
|
||||
};
|
||||
assert_eq!(required("view.layout"), json!(["mode"]));
|
||||
assert_eq!(required("view.graphics_preset"), json!(["preset"]));
|
||||
assert_eq!(required("view.ambient_occlusion"), json!(["enabled"]));
|
||||
assert_eq!(required("view.navigate"), json!(["camera"]));
|
||||
assert_eq!(required("view.history_layout"), Value::Null);
|
||||
let d = Session::default().execute("engine.describe", &json!({"command": "view.history_layout"})).unwrap();
|
||||
assert_eq!(d["input"]["properties"]["width"]["minimum"], 1.0);
|
||||
assert_eq!(d["input"]["properties"]["width"]["maximum"], 1000000.0);
|
||||
let d = Session::default().execute("engine.describe", &json!({"command": "view.navigate"})).unwrap();
|
||||
assert_eq!(d["input"]["properties"]["degrees"]["exclusiveMinimum"], 0.0);
|
||||
assert_eq!(d["input"]["properties"]["degrees"]["maximum"], 180.0);
|
||||
assert_eq!(d["input"]["properties"]["factor"]["minimum"], 0.05);
|
||||
assert_eq!(d["input"]["properties"]["pivot"]["anyOf"][0]["items"]["exclusiveMaximum"], 1e9);
|
||||
let d = Session::default().execute("engine.describe", &json!({"command": "view.history_layout"})).unwrap();
|
||||
let dock = serde_json::to_string(&d["input"]).unwrap();
|
||||
for name in ["bottom", "left", "under_browser", "browser"] {
|
||||
assert!(dock.contains(&format!("\"{name}\"")), "dock {name}: {dock}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The replies are the JSON the handlers returned before the types: exactly these values.
|
||||
#[test]
|
||||
fn replies_are_todays_json() {
|
||||
let mut s = Session::default();
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
assert_eq!(run("view.layout", json!({"mode": "compact"})), json!({"mode": "compact"}));
|
||||
assert_eq!(run("view.layout", json!({"mode": "floating"})), json!({"mode": "floating"}));
|
||||
assert_eq!(run("view.history_layout", json!({})), json!({}));
|
||||
assert_eq!(
|
||||
run("view.history_layout", json!({"width": 320, "dock": "under_browser", "collapsed": false})),
|
||||
json!({"width": 320.0, "dock": "under_browser", "collapsed": false})
|
||||
);
|
||||
assert_eq!(run("view.history_layout", json!({"dock": "browser"})), json!({"dock": "browser"}));
|
||||
assert_eq!(
|
||||
run("view.graphics_preset", json!({"preset": "quality"})),
|
||||
json!({"preset": "quality", "enabled": true, "display_quality": "fine", "supersampling": 2.0, "supersampling_adaptive": true})
|
||||
);
|
||||
assert_eq!(
|
||||
run("view.graphics_preset", json!({"preset": "performance"})),
|
||||
json!({"preset": "performance", "enabled": false, "display_quality": "normal", "supersampling": 1.0, "supersampling_adaptive": true})
|
||||
);
|
||||
assert_eq!(run("view.ambient_occlusion", json!({"enabled": false})), json!({"enabled": false}));
|
||||
let cam: solidcraft_render::Camera = serde_json::from_value(nav_camera()).unwrap();
|
||||
let turned = run("view.navigate", json!({"camera": nav_camera(), "action": "fit"}));
|
||||
assert_eq!(turned, json!({"camera": cam, "fit": true}));
|
||||
let moved = run("view.navigate", json!({"camera": nav_camera(), "motion": "zoom", "factor": 2}));
|
||||
assert_eq!(moved["fit"], false);
|
||||
assert_eq!(moved["continuous"], true);
|
||||
assert_eq!(moved.as_object().map(|o| o.len()), Some(3));
|
||||
}
|
||||
|
||||
/// Real replies of each command, in Warn, match their output schema; a misspelt key's warning
|
||||
/// still matches.
|
||||
#[test]
|
||||
fn replies_match_the_output_schemas() {
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
|
||||
let calls: Vec<(&str, Value, schemars::Schema)> = vec![
|
||||
("view.layout", json!({"mode": "compact"}), output_schema_for::<LayoutResult>()),
|
||||
("view.layout", json!({"mode": "floating"}), output_schema_for::<LayoutResult>()),
|
||||
("view.history_layout", json!({}), output_schema_for::<HistoryLayoutResult>()),
|
||||
("view.history_layout", json!({"width": 250.5, "dock": "left", "collapsed": true}), output_schema_for::<HistoryLayoutResult>()),
|
||||
("view.graphics_preset", json!({"preset": "quality"}), output_schema_for::<GraphicsPresetResult>()),
|
||||
("view.graphics_preset", json!({"preset": "performance"}), output_schema_for::<GraphicsPresetResult>()),
|
||||
("view.ambient_occlusion", json!({"enabled": true}), output_schema_for::<AmbientOcclusionResult>()),
|
||||
("view.navigate", nav(json!({"direction": [1, 1, 1]})), output_schema_for::<NavigateResult>()),
|
||||
("view.navigate", nav(json!({"action": "left", "degrees": 15})), output_schema_for::<NavigateResult>()),
|
||||
("view.navigate", nav(json!({"action": "home"})), output_schema_for::<NavigateResult>()),
|
||||
("view.navigate", nav(json!({"action": "clockwise", "fit": true})), output_schema_for::<NavigateResult>()),
|
||||
("view.navigate", nav(json!({"motion": "pan", "delta": [10, -5], "viewport": [800, 600]})), output_schema_for::<NavigateResult>()),
|
||||
(
|
||||
"view.navigate",
|
||||
nav(json!({"motion": "orbit", "delta": [10, -5], "pivot": [1, 2, 3], "viewport": [800, 600]})),
|
||||
output_schema_for::<NavigateResult>(),
|
||||
),
|
||||
("view.navigate", nav(json!({"motion": "orbit", "delta": [10, -5], "free_orbit": true})), output_schema_for::<NavigateResult>()),
|
||||
("view.navigate", nav(json!({"motion": "zoom", "factor": 0.5, "anchor": [1, 2, 3]})), output_schema_for::<NavigateResult>()),
|
||||
];
|
||||
for (id, p, schema) in calls {
|
||||
let reply = run(id, p.clone());
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, &reply), "{id} {p}: {reply} doesn't match {schema}");
|
||||
assert!(reply.get("param_warnings").is_none(), "{id} {p}: {reply}");
|
||||
let again = run(id, {
|
||||
let mut q = p.clone();
|
||||
q["zoomm"] = json!(1);
|
||||
q
|
||||
});
|
||||
assert!(again["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{id}: {again}");
|
||||
assert!(conforms(schema, schema, &again), "{id}: {again} doesn't match {schema}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Strict refuses with the handler's own message whatever the handler refuses.
|
||||
#[test]
|
||||
fn view_layout_commands_keep_todays_errors() {
|
||||
let mut cases: Vec<(&str, Value)> = vec![
|
||||
("view.layout", json!({})),
|
||||
("view.layout", json!({"mode": "grid"})),
|
||||
("view.layout", json!({"mode": 1})),
|
||||
("view.layout", json!({"mode": null})),
|
||||
("view.history_layout", json!({"width": 0})),
|
||||
("view.history_layout", json!({"width": 1000001})),
|
||||
("view.history_layout", json!({"width": "300"})),
|
||||
("view.history_layout", json!({"width": null})),
|
||||
("view.history_layout", json!({"dock": "top"})),
|
||||
("view.history_layout", json!({"dock": 3})),
|
||||
("view.history_layout", json!({"collapsed": "yes"})),
|
||||
("view.history_layout", json!({"collapsed": null})),
|
||||
("view.graphics_preset", json!({})),
|
||||
("view.graphics_preset", json!({"preset": "fast"})),
|
||||
("view.graphics_preset", json!({"preset": true})),
|
||||
("view.graphics_preset", json!({"preset": null})),
|
||||
("view.ambient_occlusion", json!({})),
|
||||
("view.ambient_occlusion", json!({"enabled": 1})),
|
||||
("view.ambient_occlusion", json!({"enabled": "true"})),
|
||||
("view.ambient_occlusion", json!({"enabled": null})),
|
||||
("view.navigate", json!({})),
|
||||
("view.navigate", json!({"camera": null, "action": "fit"})),
|
||||
("view.navigate", json!({"camera": 5, "action": "fit"})),
|
||||
("view.navigate", json!({"action": "fit"})),
|
||||
];
|
||||
for c in [
|
||||
camera(json!({"yaw": 2e6})),
|
||||
camera(json!({"roll": -2e6})),
|
||||
camera(json!({"pitch": 2.0})),
|
||||
camera(json!({"distance": 0})),
|
||||
camera(json!({"fov": 4})),
|
||||
] {
|
||||
cases.push(("view.navigate", json!({"camera": c, "action": "fit"})));
|
||||
}
|
||||
for extra in [
|
||||
json!({"action": "fit", "fit": 1}),
|
||||
json!({"action": "fit", "fit": null}),
|
||||
json!({"direction": [0, 0, 0]}),
|
||||
json!({"direction": [3, 0, 0]}),
|
||||
json!({"direction": "front"}),
|
||||
json!({"direction": null}),
|
||||
json!({"action": "spin"}),
|
||||
json!({"action": 4}),
|
||||
json!({"action": null}),
|
||||
json!({"action": "left", "degrees": 0}),
|
||||
json!({"action": "left", "degrees": 181}),
|
||||
json!({"action": "left", "degrees": "90"}),
|
||||
json!({"motion": "slide"}),
|
||||
json!({"motion": null}),
|
||||
json!({"motion": "zoom", "fit": true, "factor": 2}),
|
||||
json!({"motion": "zoom", "factor": 0.01}),
|
||||
json!({"motion": "zoom", "factor": 21}),
|
||||
json!({"motion": "zoom", "factor": 2, "anchor": [1, 2]}),
|
||||
json!({"motion": "zoom", "factor": 2, "anchor": null}),
|
||||
json!({"motion": "pan", "delta": [20000, 0], "viewport": [800, 600]}),
|
||||
json!({"motion": "pan", "delta": [1], "viewport": [800, 600]}),
|
||||
json!({"motion": "pan", "viewport": [800, 600]}),
|
||||
json!({"motion": "pan", "delta": [1, 1], "viewport": [0, 600]}),
|
||||
json!({"motion": "pan", "delta": [1, 1], "viewport": [800, 2000000]}),
|
||||
json!({"motion": "pan", "delta": [1, 1]}),
|
||||
json!({"motion": "orbit", "delta": [1, 1], "free_orbit": "yes"}),
|
||||
json!({"motion": "orbit", "delta": [1, 1], "pivot": [1, 2]}),
|
||||
json!({"motion": "orbit", "delta": [1, 1], "pivot": null}),
|
||||
] {
|
||||
cases.push(("view.navigate", nav(extra)));
|
||||
}
|
||||
assert_strict_keeps_todays_errors(&cases);
|
||||
}
|
||||
|
||||
/// A value of a key is accepted by the type exactly when the handler accepts it (the other keys
|
||||
/// being fine): the schemas never say yes where today's reader says no, or the other way round.
|
||||
#[test]
|
||||
fn the_types_read_each_key_as_its_handler_does() {
|
||||
let accepts = |id: &str, p: &Value| Session::default().execute(id, p).is_ok();
|
||||
let check = |id: &str, base: Value, key: &str, values: Vec<Value>| {
|
||||
for v in values {
|
||||
let mut p = base.clone();
|
||||
p[key] = v.clone();
|
||||
let ok = accepts(id, &p);
|
||||
let typed = match id {
|
||||
"view.layout" => serde_json::from_value::<LayoutParams>(p.clone()).is_ok(),
|
||||
"view.history_layout" => serde_json::from_value::<HistoryLayoutParams>(p.clone()).is_ok(),
|
||||
"view.graphics_preset" => serde_json::from_value::<GraphicsPresetParams>(p.clone()).is_ok(),
|
||||
"view.ambient_occlusion" => serde_json::from_value::<AmbientOcclusionParams>(p.clone()).is_ok(),
|
||||
_ => serde_json::from_value::<NavigateParams>(p.clone()).is_ok(),
|
||||
};
|
||||
assert_eq!(typed, ok, "{id} {p}");
|
||||
}
|
||||
};
|
||||
let junk = || vec![json!(null), json!(true), json!(0), json!(1.5), json!("x"), json!([]), json!({})];
|
||||
let with = |mut v: Vec<Value>| {
|
||||
v.extend(junk());
|
||||
v
|
||||
};
|
||||
check("view.layout", json!({}), "mode", with(vec![json!("floating"), json!("compact"), json!("Compact")]));
|
||||
check("view.history_layout", json!({}), "width", with(vec![json!(1), json!(1e6), json!(0.5), json!(1000001), json!(-4), json!(300)]));
|
||||
check(
|
||||
"view.history_layout",
|
||||
json!({}),
|
||||
"dock",
|
||||
with(vec![json!("bottom"), json!("left"), json!("under_browser"), json!("browser"), json!("Left")]),
|
||||
);
|
||||
check("view.history_layout", json!({}), "collapsed", with(vec![json!(true), json!(false)]));
|
||||
check("view.graphics_preset", json!({}), "preset", with(vec![json!("quality"), json!("performance"), json!("Quality")]));
|
||||
check("view.ambient_occlusion", json!({}), "enabled", with(vec![json!(true), json!(false)]));
|
||||
let base = json!({"camera": nav_camera(), "action": "fit"});
|
||||
let all_actions: Vec<Value> =
|
||||
["left", "right", "up", "down", "clockwise", "counterclockwise", "home", "fit", "spin"].iter().map(|a| json!(a)).collect();
|
||||
check("view.navigate", json!({"camera": nav_camera()}), "action", with(all_actions));
|
||||
check("view.navigate", base.clone(), "fit", with(vec![json!(true), json!(false)]));
|
||||
check(
|
||||
"view.navigate",
|
||||
base.clone(),
|
||||
"direction",
|
||||
with(vec![
|
||||
json!([1, 0, 0]),
|
||||
json!([0, 0, 1]),
|
||||
json!([2, 0, 0]),
|
||||
json!([2.1, 0, 0]),
|
||||
json!([0, 0, 0]),
|
||||
json!({"x": 0, "y": 1, "z": 0}),
|
||||
json!([1, 2]),
|
||||
json!([1e10, 0, 0]),
|
||||
]),
|
||||
);
|
||||
check(
|
||||
"view.navigate",
|
||||
json!({"camera": nav_camera(), "action": "left"}),
|
||||
"degrees",
|
||||
with(vec![json!(1), json!(180), json!(90), json!(90.0), json!(0), json!(-1), json!(181), json!(0.001)]),
|
||||
);
|
||||
let all_keys = json!({"camera": nav_camera(), "delta": [1, 1], "viewport": [800, 600], "factor": 2});
|
||||
check("view.navigate", all_keys, "motion", with(vec![json!("zoom"), json!("pan"), json!("orbit")]));
|
||||
let pan = json!({"camera": nav_camera(), "motion": "pan", "viewport": [800, 600]});
|
||||
check(
|
||||
"view.navigate",
|
||||
pan.clone(),
|
||||
"delta",
|
||||
with(vec![json!([1, 2]), json!({"x": 1, "y": 2}), json!([10000, -10000]), json!([10001, 0]), json!([1, 2, 3]), json!([1e10, 0])]),
|
||||
);
|
||||
let pan = json!({"camera": nav_camera(), "motion": "pan", "delta": [1, 1]});
|
||||
check(
|
||||
"view.navigate",
|
||||
pan,
|
||||
"viewport",
|
||||
with(vec![json!([1, 1]), json!([1e6, 1e6]), json!([0.5, 5]), json!([5, 1000001]), json!({"x": 3, "y": 4}), json!([3])]),
|
||||
);
|
||||
let zoom = json!({"camera": nav_camera(), "motion": "zoom", "factor": 2});
|
||||
check("view.navigate", zoom.clone(), "anchor", with(vec![json!([1, 2, 3]), json!({"x": 1, "y": 2, "z": 3}), json!([1, 2]), json!([1e10, 0, 0])]));
|
||||
check(
|
||||
"view.navigate",
|
||||
json!({"camera": nav_camera(), "motion": "zoom"}),
|
||||
"factor",
|
||||
with(vec![json!(0.05), json!(20), json!(0.04), json!(20.5), json!(1)]),
|
||||
);
|
||||
let orbit = json!({"camera": nav_camera(), "motion": "orbit", "delta": [1, 1], "viewport": [800, 600]});
|
||||
check("view.navigate", orbit.clone(), "pivot", with(vec![json!([1, 2, 3]), json!([1, 2]), json!({"x": 1, "y": 2, "z": 3})]));
|
||||
check("view.navigate", orbit, "free_orbit", with(vec![json!(true), json!(false)]));
|
||||
let camera_values = vec![
|
||||
nav_camera(),
|
||||
camera(json!({"yaw": 1e6})),
|
||||
camera(json!({"yaw": 1.1e6})),
|
||||
camera(json!({"roll": 1.1e6})),
|
||||
camera(json!({"pitch": std::f64::consts::FRAC_PI_2})),
|
||||
camera(json!({"pitch": 1.58})),
|
||||
camera(json!({"pitch": -1.58})),
|
||||
camera(json!({"distance": 0})),
|
||||
camera(json!({"fov": 3.2})),
|
||||
camera(json!({"up": "y"})),
|
||||
camera(json!({"up": "w"})),
|
||||
];
|
||||
check("view.navigate", json!({"action": "fit"}), "camera", with(camera_values));
|
||||
}
|
||||
|
||||
/// A key of another form than the one the handler takes is not used, so the contract does not
|
||||
/// read it either: such a call replies as it does with the check off, in warn and in strict.
|
||||
#[test]
|
||||
fn navigate_reads_only_the_keys_of_its_form() {
|
||||
for p in [
|
||||
// A motion wins over an action and a direction.
|
||||
json!({"camera": nav_camera(), "motion": "zoom", "factor": 2, "action": "bogus", "direction": "up"}),
|
||||
// Each motion reads its own keys: a pan has no factor, a zoom no delta.
|
||||
json!({"camera": nav_camera(), "motion": "pan", "delta": [3, 4], "viewport": [800, 600], "factor": 99}),
|
||||
json!({"camera": nav_camera(), "motion": "zoom", "factor": 2, "delta": "far", "viewport": 0, "pivot": "here"}),
|
||||
// An orbit reads the viewport only about a pivot.
|
||||
json!({"camera": nav_camera(), "motion": "orbit", "delta": [3, 4], "viewport": 0}),
|
||||
// A direction has no degrees or action.
|
||||
json!({"camera": nav_camera(), "direction": [0, 0, 1], "degrees": 500, "action": "bogus"}),
|
||||
] {
|
||||
let off = Session::default().execute("view.navigate", &p).unwrap();
|
||||
for check in [ParamCheck::Warn, ParamCheck::Strict] {
|
||||
let checked = Session { param_check: check, ..Session::default() }.execute("view.navigate", &p).unwrap();
|
||||
assert_eq!(checked, off, "{check:?} {p}");
|
||||
}
|
||||
}
|
||||
// The keys of the form taken are still checked.
|
||||
let p = json!({"camera": nav_camera(), "motion": "pan", "delta": [3, 4], "viewport": [0, 600]});
|
||||
let strict = Session { param_check: ParamCheck::Strict, ..Session::default() }.execute("view.navigate", &p);
|
||||
assert!(strict.unwrap_err().to_string().contains("viewport dimensions must be in 1..1000000"));
|
||||
}
|
||||
Reference in new issue
Block a user