PhotoCraft: An open-source, photo editor written by scratch in pure Rust
ui.set: reject unknown fields; the theme error names all five themes (#412, #413) (#437)
BFlat262046026793
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rsindex 346ec8e08..df507d55e 100644--- a/crates/automation/src/server.rs+++ b/crates/automation/src/server.rs@@ -157,7 +157,10 @@ pub struct MenuParams {#[derive(Debug, Deserialize, JsonSchema)]pub struct UiSetParams {- /// Fields accepted by the control method `ui.set` (tool, panels, zoom, center, dark).+ /// Fields for the control method `ui.set`: tool, panels, dock, dockTabs, dockWidth, maskTarget,+ /// vectorMaskTarget, selectionMode, zoom, center, fit, theme (pro, proMedium, studio,+ /// studioLight, classic), brushSection, brushTab, brushesView, brushSize. Other fields are an+ /// error.pub fields: Value,}@@ -576,7 +579,9 @@ impl PhotocraftMcp {}}- #[tool(description = "Bridge mode: change UI state (tool, panels, zoom, center, dark).")]+ #[tool(+ description = "Bridge mode: change UI state (tool, panels, dock, zoom, center, fit, theme, brush settings; see `fields`). Unknown fields are an error."+ )]async fn ui_set(&self, Parameters(p): Parameters<UiSetParams>) -> Result<CallToolResult, McpError> {match self.bridge_client() {Some(b) => to_result(b.call("ui.set", p.fields).await),diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 46077eed5..8d51a89ac 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -7,7 +7,8 @@//! - `engine.execute {command, params}`: run any engine or UI command by id//! - `engine.commands`: list commands with enablement//! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size)-//! - `ui.set {tool?, panels?, zoom?, center?, dark?}`: change UI state+//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushSize?}`:+//! change UI state; any other field is an error ([`UI_SET_FIELDS`])//! - `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree//! - `ui.dialog.open {kind, fields?}` (kinds: newDocument, about, layerStyle {effect?}, colorPicker {target: foreground|background}, command {command}) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`//! - `ui.dialog.apply {dialog}`: commit Preferences changes without closing the dialog@@ -66,6 +67,27 @@ pub enum Outcome {AfterJob(photocraft_engine::jobs::JobId),}+/// The fields `ui.set` reads. Anything else is rejected before a field is applied, so a typo or+/// a field the method doesn't have can't reply with success while nothing changes (#412).+pub const UI_SET_FIELDS: [&str; 16] = [+ "tool",+ "panels",+ "dock",+ "dockTabs",+ "dockWidth",+ "maskTarget",+ "vectorMaskTarget",+ "selectionMode",+ "zoom",+ "center",+ "fit",+ "theme",+ "brushSection",+ "brushTab",+ "brushesView",+ "brushSize",+];+fn ok(v: Value) -> Outcome {Outcome::Done(json!({"ok": true, "result": v}))}@@ -142,6 +164,9 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()),"ui.inspect" => ok(inspect(app, ctx)),"ui.set" => {+ if let Some(field) = p.as_object().and_then(|o| o.keys().find(|k| !UI_SET_FIELDS.contains(&k.as_str()))) {+ return err(format!("unknown field `{field}` (fields: {})", UI_SET_FIELDS.join(", ")));+ }if let Some(t) = s("tool") {match Tool::from_name(t) {Some(t) => app.ui.tool = t,@@ -213,7 +238,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequestif let Some(name) = s("theme") {match crate::theme::ThemeKind::from_name(name) {Some(k) => app.set_theme(ctx, k),- None => return err(format!("unknown theme `{name}` (studio, studioLight, classic)")),+ None => {+ let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect();+ return err(format!("unknown theme `{name}` ({})", names.join(", ")));+ }}}if let Some(i) = u("brushSection") {@@ -572,6 +600,44 @@ mod tests {assert_eq!(app.session.active().unwrap().revision, rev, "opening a dialog must not edit the document");}+ #[test]+ fn ui_set_rejects_unknown_fields_before_changing_anything() {+ use crate::theme::ThemeKind;+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ app.set_theme(&ctx, ThemeKind::StudioLight);+ // `dark` was advertised to MCP clients but never read; a typo looked like success too.+ for params in [json!({"dark": true}), json!({"thme": "classic"}), json!({"tool": "move", "dark": true})] {+ let r = call(&mut app, &ctx, "ui.set", params.clone());+ assert_eq!(r["ok"], false, "{params}: {r}");+ assert!(r["error"].as_str().unwrap().contains("unknown field"), "{r}");+ }+ assert_eq!(app.ui.theme, ThemeKind::StudioLight);+ assert_eq!(app.ui.tool, Tool::Brush, "a rejected call applies none of its fields");+ // Every field the method reads gets past the check (a bad value is its own error).+ for field in UI_SET_FIELDS {+ let r = call(&mut app, &ctx, "ui.set", json!({ field: null }));+ assert!(!r.to_string().contains("unknown field"), "{field}: {r}");+ }+ assert_eq!(call(&mut app, &ctx, "ui.set", Value::Null)["ok"], true);+ }++ #[test]+ fn ui_set_unknown_theme_error_names_every_theme_and_each_name_works() {+ use crate::theme::ThemeKind;+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let r = call(&mut app, &ctx, "ui.set", json!({"theme": "nope"}));+ assert_eq!(r["ok"], false);+ let error = r["error"].as_str().unwrap();+ for kind in ThemeKind::ALL {+ assert!(error.contains(kind.id()), "{error} lacks {}", kind.id());+ assert_eq!(call(&mut app, &ctx, "ui.set", json!({"theme": kind.id()}))["ok"], true);+ assert_eq!(app.ui.theme, kind);+ assert_eq!(ThemeKind::from_name(kind.id()), Some(kind));+ }+ }+#[test]fn preferences_apply_is_available_over_control_without_closing() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rsindex 70d7324a2..b504bd6ad 100644--- a/crates/ui-egui/src/theme.rs+++ b/crates/ui-egui/src/theme.rs@@ -35,6 +35,17 @@ impl ThemeKind {ThemeKind::Classic => "Classic",}}+ /// The canonical name: `ui.set {theme}` accepts it and the Window › Theme commands are+ /// `window.theme.<id>`.+ pub fn id(self) -> &'static str {+ match self {+ ThemeKind::Pro => "pro",+ ThemeKind::ProMedium => "proMedium",+ ThemeKind::Studio => "studio",+ ThemeKind::StudioLight => "studioLight",+ ThemeKind::Classic => "classic",+ }+ }pub fn next(self) -> Self {let i = Self::ALL.iter().position(|k| *k == self).unwrap_or(0);Self::ALL[(i + 1) % Self::ALL.len()]diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex e0b641c62..6d554e022 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -35,7 +35,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given- `engine.commands`: list commands with enablement- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, menu tree, window size). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`)-- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, maskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?}`: change UI state (`selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520)+- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?}`: change UI state; any other field is an error, checked before anything changes (`theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520)- `ui.menu.invoke {id}` / `ui.menu.list`: activate a menu item by id; list the menu tree- `ui.dialog.open {kind, fields?}` (kinds `newDocument`, `about`, `layerStyle {effect?}`, `colorPicker {target: foreground|background}`, `command {command}`) / `ui.dialog.set {dialog, field, value}` / `ui.dialog.confirm {dialog}` / `ui.dialog.cancel {dialog}`- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) edits the sections in its `values` field. `ui.dialog.apply {dialog}` saves those values through `prefs.set` and keeps the same dialog and section open. `ui.dialog.confirm` saves and closes; `ui.dialog.cancel` discards only edits made since the last successful Apply. Invalid values return an error without closing the Apply dialog or changing the saved preferences. Settings marked for the next launch still require a restart.