PhotoCraft: An open-source, photo editor written by scratch in pure Rust
ui.set validates every field before applying the first one (#820)
Elvis33LE5ecc860ac1ab
diff --git a/Cargo.lock b/Cargo.lockindex 260bbea0c..c6bbbeb6a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3867,6 +3867,7 @@ dependencies = ["photocraft-geom","photocraft-gpu","photocraft-io",+ "photocraft-paint","photocraft-plugins","photocraft-psd","photocraft-raster",diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.tomlindex e4d8ebd6a..2096bd083 100644--- a/crates/ui-egui/Cargo.toml+++ b/crates/ui-egui/Cargo.toml@@ -21,6 +21,8 @@ photocraft-plugins = { workspace = true }photocraft-algo = { workspace = true }photocraft-text = { workspace = true }photocraft-vector = { workspace = true }+# Only MAX_BRUSH_SIZE: `ui.set brushSize` validates against the Brush Settings range up front.+photocraft-paint = { workspace = true }# Reading files to open them (bounded reads, a clear error for files larger than memory).photocraft-format = { workspace = true }# Decoding the brand mark's PNG (`brand.rs`); already linked through photocraft-io.diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 482e4103f..ce980e24b 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -9,8 +9,8 @@//! - `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size); the menu//! tree is `ui.menu.list`//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, fit?, theme?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, brushSize?}`:+//! - `ui.set {tool?, panels?, dock?, dockTabs?, dockWidth?, colorPanel?, 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, wait?}` / `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, wait?}` / `ui.dialog.cancel {dialog}`//! - `ui.dialog.apply {dialog}`: commit Preferences changes without closing the dialog//! - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows@@ -68,8 +68,10 @@ 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).+/// The fields `ui.set` reads. Anything else is rejected before a field is applied, and every+/// field's value is validated before the first one is applied, so a typo, an unknown field, a+/// bad value or a bad nested key can't reply with success while nothing — or only half of it —+/// changed (#412).pub const UI_SET_FIELDS: [&str; 21] = ["tool","panels",@@ -100,6 +102,67 @@ fn ok(v: Value) -> Outcome {fn err(e: impl std::fmt::Display) -> Outcome {Outcome::Done(json!({"ok": false, "error": e.to_string()}))}++/// A `ui.set` boolean field: `Ok(None)` when absent, an error when present with another type.+fn bool_field(p: &Value, key: &str) -> std::result::Result<Option<bool>, String> {+ match p.get(key) {+ None => Ok(None),+ Some(v) => v.as_bool().map(Some).ok_or_else(|| format!("{key} must be a boolean")),+ }+}++/// A `ui.set` integer field: `Ok(None)` when absent; whole-number floats (`12.0`, as UIs send+/// them) are accepted, anything else is an error.+fn uint_field(p: &Value, key: &str) -> std::result::Result<Option<u64>, String> {+ match p.get(key) {+ None => Ok(None),+ Some(v) if v.is_u64() => Ok(v.as_u64()),+ Some(v) => v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| Some(f as u64)).ok_or_else(|| format!("{key} must be a non-negative integer")),+ }+}++/// A `ui.set` numeric field: `Ok(None)` when absent, finite numbers only.+fn num_field(p: &Value, key: &str) -> std::result::Result<Option<f64>, String> {+ match p.get(key) {+ None => Ok(None),+ Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| format!("{key} must be a finite number")),+ }+}++/// A `ui.set` object field merged into the current state (e.g. `panels`): the patch's keys are+/// merged into the serialized current value and parsed back, so a non-object value or an+/// unknown nested key is an error — a nested typo must not reply ok while changing nothing.+fn merged_object<T: serde::Serialize + serde::de::DeserializeOwned>(current: &T, patch: Option<&Value>, field: &str) -> std::result::Result<Option<T>, String> {+ let Some(patch) = patch else { return Ok(None) };+ let Some(patch) = patch.as_object() else { return Err(format!("{field} must be an object")) };+ let mut cur = serde_json::to_value(current).map_err(|e| e.to_string())?;+ let known: std::collections::HashSet<String> = cur.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();+ for (k, v) in patch {+ if !known.contains(k) {+ return Err(format!("unknown {field} field `{k}`"));+ }+ if let Some(c) = cur.as_object_mut() {+ c.insert(k.clone(), v.clone());+ }+ }+ serde_json::from_value(cur).map(Some).map_err(|e| format!("{field}: {e}"))+}++/// A `ui.set` object field applied by whole-value replacement (e.g. `dock`, `colorPanel`):+/// unknown nested keys are rejected like [`merged_object`] does, but the value replaces the+/// state instead of merging into it.+fn whole_object<T: serde::Serialize + serde::de::DeserializeOwned>(current: &T, v: Option<&Value>, field: &str) -> std::result::Result<Option<T>, String> {+ let Some(v) = v else { return Ok(None) };+ let Some(patch) = v.as_object() else { return Err(format!("{field} must be an object")) };+ let cur = serde_json::to_value(current).map_err(|e| e.to_string())?;+ let known: std::collections::HashSet<&str> = cur.as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default();+ for k in patch.keys() {+ if !known.contains(k.as_str()) {+ return Err(format!("unknown {field} field `{k}`"));+ }+ }+ serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("{field}: {e}"))+}fn wrap(r: Result<Value, String>) -> Outcome {match r {Ok(v) => ok(v),@@ -218,138 +281,172 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)} else {None};- if let Some(value) = p.get("gradientClassic")- && !value.is_boolean()- {- return err("gradientClassic must be a boolean");- }- if let Some(t) = s("tool") {- match Tool::from_name(t) {- Some(t) => app.ui.tool = t,- None => return err(format!("unknown tool `{t}`")),- }- }- let gradient_before = app.ui.tool_options.clone();- if let Some(mode) = gradient_blend {- app.ui.tool_options.gradient_blend_mode = mode;- }- if let Some(classic) = p.get("gradientClassic").and_then(Value::as_bool) {- app.ui.tool_options.gradient_classic = classic;- }- if gradient_blend.is_some() {- crate::gradient_ui::options_changed(app, &gradient_before);- }- if let Some(panels) = p.get("panels") {- let mut cur = serde_json::to_value(&app.ui.panels).unwrap_or_default();- if let (Some(c), Some(n)) = (cur.as_object_mut(), panels.as_object()) {- for (k, v) in n {- c.insert(k.clone(), v.clone());+ // Everything is validated and materialized before the first field is applied, so a+ // rejected call applies none of its fields (#412's guarantee, down to the values+ // and nested keys).+ let applied = (|| -> std::result::Result<Value, String> {+ let tool = match s("tool") {+ Some(t) => Tool::from_name(t).map(Some).ok_or_else(|| format!("unknown tool `{t}`"))?,+ None => None,+ };+ let gradient_classic = bool_field(p, "gradientClassic")?;+ let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?;+ let mask_target = bool_field(p, "maskTarget")?;+ let vector_mask_target = bool_field(p, "vectorMaskTarget")?;+ let selection_mode = uint_field(p, "selectionMode")?;+ let dock_tabs = merged_object(&app.ui.dock_tabs, p.get("dockTabs"), "dockTabs")?;+ let dock = whole_object(&app.ui.dock, p.get("dock"), "dock")?;+ // Which chip the Color panel edits.+ let color_panel = whole_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?;+ let dock_width = num_field(p, "dockWidth")?;+ let zoom = num_field(p, "zoom")?;+ let center = match p.get("center") {+ Some(v) => {+ let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?;+ if a.len() != 2 {+ return Err("center must be exactly [x, y]".into());+ }+ let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else {+ return Err("center must be [x, y] of two numbers".into());+ };+ Some([x as f32, y as f32])+ }+ None => None,+ };+ let fit = bool_field(p, "fit")? == Some(true);+ let theme = match s("theme") {+ Some(name) => {+ let kind = crate::theme::ThemeKind::from_name(name).ok_or_else(|| {+ let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect();+ format!("unknown theme `{name}` ({})", names.join(", "))+ })?;+ Some(kind)+ }+ None => None,+ };+ let brush_section = uint_field(p, "brushSection")?;+ let brush_tab = uint_field(p, "brushTab")?;+ let brushes_view = match p.get("brushesView") {+ Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushesView: {e} (list, grid)"))?,+ None => None,+ };+ let brush_picker_view = match p.get("brushPickerView") {+ Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushPickerView: {e} (list, grid)"))?,+ None => None,+ };+ // `Some(None)` is an explicit null, which closes the picker (a missing field+ // leaves it alone).+ let brush_picker = match p.get("brushPicker") {+ Some(v) => {+ let at = serde_json::from_value::<Option<[f32; 2]>>(v.clone())+ .map_err(|_| "brushPicker must be [x, y] in screen points, or null to close it".to_string())?;+ if at.is_some_and(|[x, y]| !x.is_finite() || !y.is_finite()) {+ return Err("brushPicker must be [x, y] in screen points, or null to close it".into());+ }+ Some(at)+ }+ None => None,+ };+ // brushSize rides the journaled `tools.setBrush` command (#744). Numeric values+ // are validated here so the command cannot fail after other fields were+ // applied; non-numeric values keep the API's historical silent no-op.+ let brush_size: Option<f64> = match p.get("brushSize").and_then(Value::as_f64) {+ Some(size) => {+ if !size.is_finite() || size > f64::from(photocraft_paint::MAX_BRUSH_SIZE) {+ return Err(format!("brushSize must be finite and at most {} px", photocraft_paint::MAX_BRUSH_SIZE));+ }+ Some(size)}+ None => None,+ };++ // Apply (nothing below can fail).+ if let Some(t) = tool {+ app.ui.tool = t;}- match serde_json::from_value(cur) {- Ok(v) => app.ui.panels = v,- Err(e) => return err(e),+ let gradient_before = app.ui.tool_options.clone();+ if let Some(mode) = gradient_blend {+ app.ui.tool_options.gradient_blend_mode = mode;}- }- if let Some(m) = p.get("maskTarget").and_then(Value::as_bool) {- app.ui.mask_target = m;- app.ui.vector_mask_target &= !m;- }- if let Some(m) = p.get("vectorMaskTarget").and_then(Value::as_bool) {- app.ui.vector_mask_target = m;- app.ui.mask_target &= !m;- }- // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect.- if let Some(m) = p.get("selectionMode").and_then(Value::as_u64) {- app.ui.selection_mode = m.min(3) as u8;- }- if let Some(tabs) = p.get("dockTabs") {- let mut cur = serde_json::to_value(app.ui.dock_tabs).unwrap_or_default();- if let (Some(c), Some(n)) = (cur.as_object_mut(), tabs.as_object()) {- for (k, v) in n {- c.insert(k.clone(), v.clone());- }+ if let Some(classic) = gradient_classic {+ app.ui.tool_options.gradient_classic = classic;}- match serde_json::from_value(cur) {- Ok(v) => app.ui.dock_tabs = v,- Err(e) => return err(e),+ if gradient_blend.is_some() {+ crate::gradient_ui::options_changed(app, &gradient_before);}- }- // Dock group order, heights and collapsed groups (see `dock::DockLayout`).- if let Some(d) = p.get("dock") {- match serde_json::from_value(d.clone()) {- Ok(v) => app.ui.dock = v,- Err(e) => return err(e),+ if let Some(v) = panels {+ app.ui.panels = v;}- }- // Which chip the Color panel edits.- if let Some(c) = p.get("colorPanel") {- match serde_json::from_value(c.clone()) {- Ok(v) => app.ui.color_panel = v,- Err(e) => return err(e),+ if let Some(m) = mask_target {+ app.ui.mask_target = m;+ app.ui.vector_mask_target &= !m;}- }- // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame.- if let Some(w) = p.get("dockWidth").and_then(Value::as_f64) {- crate::panels::request_dock_width(ctx, w as f32);- }- if let Some(i) = app.session.active_index() {- if let Some(z) = p.get("zoom").and_then(Value::as_f64) {- app.ui.views[i].zoom = (z as f32).clamp(0.01, 64.0);- app.ui.views[i].fit_pending = false;- app.ui.views[i].fill_pending = false;+ if let Some(m) = vector_mask_target {+ app.ui.vector_mask_target = m;+ app.ui.mask_target &= !m;}- if let Some(c) = p.get("center").and_then(Value::as_array)- && c.len() == 2- {- app.ui.views[i].center = [c[0].as_f64().unwrap_or(0.0) as f32, c[1].as_f64().unwrap_or(0.0) as f32];- app.ui.views[i].fit_pending = false;- app.ui.views[i].fill_pending = false;+ // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect.+ if let Some(m) = selection_mode {+ app.ui.selection_mode = m.min(3) as u8;}- if p.get("fit").and_then(Value::as_bool) == Some(true) {- app.ui.views[i].fit_pending = true;- app.ui.views[i].fill_pending = false;+ if let Some(v) = dock_tabs {+ app.ui.dock_tabs = v;}- }- if let Some(name) = s("theme") {- match crate::theme::ThemeKind::from_name(name) {- Some(k) => app.set_theme(ctx, k),- None => {- let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect();- return err(format!("unknown theme `{name}` ({})", names.join(", ")));+ // Dock group order, heights and collapsed groups (see `dock::DockLayout`).+ if let Some(v) = dock {+ app.ui.dock = v;+ }+ if let Some(v) = color_panel {+ app.ui.color_panel = v;+ }+ // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame.+ if let Some(w) = dock_width {+ crate::panels::request_dock_width(ctx, w as f32);+ }+ if let Some(i) = app.session.active_index() {+ if let Some(z) = zoom {+ app.ui.views[i].zoom = (z as f32).clamp(0.01, 64.0);+ app.ui.views[i].fit_pending = false;+ app.ui.views[i].fill_pending = false;+ }+ if let Some(c) = center {+ app.ui.views[i].center = c;+ app.ui.views[i].fit_pending = false;+ app.ui.views[i].fill_pending = false;+ }+ if fit {+ app.ui.views[i].fit_pending = true;+ app.ui.views[i].fill_pending = false;}}- }- if let Some(i) = u("brushSection") {- app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1);- }- if let Some(i) = u("brushTab") {- app.ui.brush_tab = (i as usize).min(1);- }- if let Some(v) = p.get("brushesView").cloned() {- match serde_json::from_value(v) {- Ok(v) => app.ui.brushes_panel.view = v,- Err(e) => return err(format!("brushesView: {e} (list, grid)")),+ if let Some(k) = theme {+ app.set_theme(ctx, k);}- }- if let Some(v) = p.get("brushPickerView").cloned() {- match serde_json::from_value(v) {- Ok(v) => app.ui.brush_picker_list.view = v,- Err(e) => return err(format!("brushPickerView: {e} (list, grid)")),+ if let Some(i) = brush_section {+ app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1);}- }- if let Some(v) = p.get("brushPicker").cloned() {- match serde_json::from_value::<Option<[f32; 2]>>(v) {- Ok(at) if at.is_none_or(|[x, y]| x.is_finite() && y.is_finite()) => app.ui.brush_picker = at,- _ => return err("brushPicker must be [x, y] in screen points, or null to close it"),+ if let Some(i) = brush_tab {+ app.ui.brush_tab = (i as usize).min(1);}- }- if let Some(size) = p.get("brushSize").and_then(Value::as_f64)- && let Err(e) = app.run("tools.setBrush", json!({"brush": {"size": size}}))- {- return err(e);- }- ok(Value::Null)+ if let Some(v) = brushes_view {+ app.ui.brushes_panel.view = v;+ }+ if let Some(v) = brush_picker_view {+ app.ui.brush_picker_list.view = v;+ }+ if let Some(at) = brush_picker {+ app.ui.brush_picker = at;+ }+ // Which chip the Color panel edits.+ if let Some(c) = color_panel {+ app.ui.color_panel = c;+ }+ if let Some(size) = brush_size {+ app.run("tools.setBrush", json!({"brush": {"size": size}})).map_err(|e| e.to_string())?;+ }+ Ok(Value::Null)+ })();+ wrap(applied)}"ui.dialog.open" => {let kind = match s("kind").unwrap_or("") {@@ -820,6 +917,41 @@ mod tests {assert_eq!(app.ui.brush_picker, None);}+ #[test]+ fn ui_set_applies_all_fields_or_none() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let before = app.ui.tool;+ let panels_before = serde_json::to_value(&app.ui.panels).unwrap_or_default();+ // A late invalid field must not leave the earlier valid one applied - including the+ // journaled brush command, which is validated up front for exactly this reason.+ for params in+ [json!({"tool": "move", "theme": "nope"}), json!({"tool": "move", "brushSize": 1e300}), json!({"tool": "move", "colorPanel": {"nope": true}})]+ {+ let r = call(&mut app, &ctx, "ui.set", params.clone());+ assert_eq!(r["ok"], false, "{params}: {r}");+ assert_eq!(app.ui.tool, before, "{params}: a rejected call applies none of its fields");+ }+ // Wrong types and unknown nested keys are errors, not silent no-ops with ok:true.+ for params in [+ json!({"panels": "x"}),+ json!({"panels": {"nope": true}}),+ json!({"dockTabs": {"nope": 1}}),+ json!({"dock": {"nope": 1}}),+ json!({"center": [1]}),+ json!({"center": [1, 2, 3]}),+ json!({"center": "here"}),+ json!({"colorPanel": "x"}),+ json!({"selectionMode": "add"}),+ ] {+ let r = call(&mut app, &ctx, "ui.set", params.clone());+ assert_eq!(r["ok"], false, "{params}: {r}");+ }+ assert_eq!(serde_json::to_value(&app.ui.panels).unwrap_or_default(), panels_before, "nothing was applied");+ // Non-numeric brushSize keeps the API's historical silent no-op (see the dispatch test).+ assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushSize": "large"}))["ok"], true);+ }+#[test]fn ui_set_color_panel_picks_the_edited_chip() {let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());