PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(ui): respect explicit dropdown defaults in schema dialogs (#3056) (#3149)
buivanvu941fdb0378a34b
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex d0c79d4fa..b5ffb786f 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -18,7 +18,10 @@ pub enum Kind {max: f32,default: f32,},- Choice(Vec<String>),+ Choice {+ options: Vec<String>,+ default: Option<String>,+ },Bool(bool),Int {default: i64,@@ -80,8 +83,22 @@ pub fn parse_spec(spec: &str) -> Vec<Param> {}let v = v.trim();let kind = if let Some(choices) = v.strip_prefix('"') {- let body = choices.split('"').next().unwrap_or("");- Kind::Choice(body.split('|').map(str::to_string).collect())+ let (body, rest) = choices.split_once('"').unwrap_or((choices, ""));+ let options: Vec<String> = body.split('|').map(str::to_string).collect();+ let default = if let Some((_, def_part)) = rest.split_once('=') {+ let trimmed = def_part.trim();+ let def = if let Some(unquoted) = trimmed.strip_prefix('"') {+ unquoted.split('"').next().unwrap_or("")+ } else if let Some(unquoted) = trimmed.strip_prefix('\'') {+ unquoted.split('\'').next().unwrap_or("")+ } else {+ trimmed.split(|c: char| c.is_whitespace() || c == '(' || c == ')' || c == ',' || c == '}').next().unwrap_or("")+ };+ if !def.is_empty() && options.iter().any(|opt| opt == def) { Some(def.to_string()) } else { None }+ } else {+ None+ };+ Kind::Choice { options, default }} else if let Some(rest) = v.strip_prefix("bool") {Kind::Bool(rest.trim_start_matches('=').trim() == "true")} else if v == "text" {@@ -278,7 +295,7 @@ pub fn has_dialog(command: &str) -> bool {fn rememberable(kind: &Kind, value: &Value) -> bool {match kind {Kind::Range { min, max, .. } => value.as_f64().is_some_and(|n| n.is_finite() && n >= f64::from(*min) && n <= f64::from(*max)),- Kind::Choice(choices) => value.as_str().is_some_and(|v| choices.iter().any(|choice| choice == v)),+ Kind::Choice { options, .. } => value.as_str().is_some_and(|v| options.iter().any(|choice| choice == v)),Kind::Bool(_) => value.is_boolean(),Kind::Int { .. } => value.as_i64().is_some(),_ => false,@@ -320,7 +337,10 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {let v = match &p.kind {Kind::Range { default, .. } if command == "image.mode.indexedColor" && p.key == "colors" => json!(default.round().clamp(2.0, 256.0) as u32),Kind::Range { default, .. } => json!(default),- Kind::Choice(c) => json!(c.first().cloned().unwrap_or_default()),+ Kind::Choice { options, default } => {+ let initial = default.as_deref().or_else(|| options.first().map(String::as_str)).unwrap_or("");+ json!(initial)+ }Kind::Bool(default) => json!(default),Kind::Int { default } => json!(default),Kind::Text => json!(""),@@ -402,7 +422,10 @@ pub fn open_with_spec(app: &mut PhotocraftApp, command: &str, label: &str, spec:for p in parse_spec(spec) {let v = match &p.kind {Kind::Range { default, .. } => json!(default),- Kind::Choice(c) => json!(c.first().cloned().unwrap_or_default()),+ Kind::Choice { options, default } => {+ let initial = default.as_deref().or_else(|| options.first().map(String::as_str)).unwrap_or("");+ json!(initial)+ }Kind::Bool(default) => json!(default),Kind::Int { default } => json!(default),Kind::Color(Some(rgb)) => json!(crate::color_picker_ui::hex(*rgb)),@@ -493,10 +516,11 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {let scale = if max - min <= 10.0 { 100.0 } else { 10.0 };f.insert(p.key, json!((v * scale).round() / scale));}- Kind::Choice(options) => {+ Kind::Choice { options, default } => {ui.horizontal(|ui| {ui.label(egui::RichText::new(label(&p.key)).color(t.text_dim));- let mut cur = f.get(&p.key).and_then(Value::as_str).unwrap_or(&options[0]).to_string();+ let initial = default.as_deref().or_else(|| options.first().map(String::as_str)).unwrap_or("");+ let mut cur = f.get(&p.key).and_then(Value::as_str).unwrap_or(initial).to_string();let labels: Vec<String> = options.iter().map(|o| choice_label(o)).collect();let opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect();crate::widgets::dropdown(ui, &format!("flt-{cmd}-{}", p.key), &mut cur, &opts, 170.0);@@ -721,11 +745,13 @@ mod tests {fn parses_registry_notation() {let p = parse_spec(r#"{"radius":0.1..1000=1,"method":"spin|zoom","monochromatic":bool,"seed":u32=0,"horizontal":px=0}"#);assert_eq!(p[0], Param { key: "radius".into(), kind: Kind::Range { min: 0.1, max: 1000.0, default: 1.0 } });- assert_eq!(p[1].kind, Kind::Choice(vec!["spin".into(), "zoom".into()]));+ assert_eq!(p[1].kind, Kind::Choice { options: vec!["spin".into(), "zoom".into()], default: None });assert_eq!(p[2].kind, Kind::Bool(false));assert_eq!(p[3].kind, Kind::Int { default: 0 });assert_eq!(p[4].kind, Kind::Int { default: 0 });assert!(parse_spec("{}").is_empty());+ let p_choice = parse_spec(r#"{"quality":"draft|good|best"="good"}"#);+ assert_eq!(p_choice[0].kind, Kind::Choice { options: vec!["draft".into(), "good".into(), "best".into()], default: Some("good".into()) });let p = parse_spec(r#"{"lighting":bool=true,"kernel":int[25],"pins":json,"points":[[0,0],[1,0]],"mapPath":text,"mapDocument":doc,"scale":1..9999=1}"#);let kinds: Vec<&Kind> = p.iter().map(|p| &p.kind).collect();assert_eq!(@@ -815,12 +841,12 @@ mod tests {continue;}check(source_label(&p.key));- if let Kind::Choice(choices) = p.kind {- for choice in choices {+ if let Kind::Choice { options, .. } = &p.kind {+ for choice in options {// Only symbolic options are UI choices; registry docs also contain// colour syntax and array notation, which are not translatable names.if choice.chars().all(|c| c.is_ascii_alphanumeric()) {- check(source_label(&choice));+ check(source_label(choice));}}}@@ -1454,4 +1480,46 @@ mod tests {}}}++ #[test]+ fn schema_dialogs_respect_explicit_dropdown_defaults() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());++ // 1. Radial Blur has explicit default "good", not the first option ("draft").+ open(&mut app, "filter.blur.radialBlur").unwrap();+ let fields = &app.ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["quality"], json!("good"), "Radial Blur must select explicit default 'good'");+ assert_eq!(fields["method"], json!("spin"), "Radial Blur method has no explicit default, retains first option");+ let params = params_of(fields);+ assert_eq!(params["quality"], json!("good"));++ // 2. Convert to Profile has explicit default "relative", not first option ("perceptual").+ open(&mut app, "edit.convertToProfile").unwrap();+ let fields = &app.ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["intent"], json!("relative"), "Convert to Profile must select explicit default 'relative'");+ let params = params_of(fields);+ assert_eq!(params["intent"], json!("relative"));++ // 3. Proof Setup has explicit default "relative".+ open(&mut app, "view.proofSetup").unwrap();+ let fields = &app.ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["intent"], json!("relative"), "Proof Setup must select explicit default 'relative'");+ let params = params_of(fields);+ assert_eq!(params["intent"], json!("relative"));++ // 4. Remembered values still override initial defaults.+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.session.prefs.edit(|prefs| {+ prefs.dialogs.insert("filter.blur.radialBlur".into(), json!({"quality": "best"}));+ });+ open(&mut app, "filter.blur.radialBlur").unwrap();+ let fields = &app.ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["quality"], json!("best"), "Remembered choice must override explicit default");++ // 5. Explicit default that is the first option (e.g. "cw" in arbitrary rotation).+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ open(&mut app, "image.rotation.arbitrary").unwrap();+ let fields = &app.ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["direction"], json!("cw"), "Explicit default matching first option is preserved");+ }}diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rsindex 80afe652c..ed1597deb 100644--- a/crates/ui-egui/src/gallery_ui.rs+++ b/crates/ui-egui/src/gallery_ui.rs@@ -52,7 +52,10 @@ fn default_params(f: GalleryFilter) -> Map<String, Value> {for p in parse_spec(f.params_doc()) {let v = match p.kind {Kind::Range { default, .. } => json!(default),- Kind::Choice(c) => json!(c[0]),+ Kind::Choice { options, default } => {+ let initial = default.as_deref().or_else(|| options.first().map(String::as_str)).unwrap_or("");+ json!(initial)+ }Kind::Bool(b) => json!(b),_ => continue,};@@ -685,8 +688,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {widgets::slider_row(ui, &label, &mut v, min..=max, "", None);e.params.insert(p.key, json!(v.round()));}- Kind::Choice(options) => {- let mut c = e.params.get(&p.key).and_then(Value::as_str).unwrap_or(&options[0]).to_string();+ Kind::Choice { options, default } => {+ let initial = default.as_deref().or_else(|| options.first().map(String::as_str)).unwrap_or("");+ let mut c = e.params.get(&p.key).and_then(Value::as_str).unwrap_or(initial).to_string();let labels: Vec<String> = options.iter().map(|o| crate::filter_dialog::label(o)).collect();let opts: Vec<(String, &str)> = options.iter().cloned().zip(labels.iter().map(String::as_str)).collect();ui.horizontal(|ui| {diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 2c79bb6e4..be88ab8b8 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -1912,7 +1912,9 @@ mod tests {assert!(invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].is_u64());let spec = photocraft_engine::commands::find("edit.convertToProfile").unwrap();let params = crate::filter_dialog::parse_spec(spec.params);- assert!(matches!(¶ms[0].kind, crate::filter_dialog::Kind::Choice(c) if c[0] == "srgb" && !c.iter().any(|v| v.contains('/'))));+ assert!(+ matches!(¶ms[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/')))+ );}}