diff --git a/assets/locales/pending/material-selection.json b/assets/locales/pending/material-selection.json new file mode 100644 index 000000000..b1661a7c0 --- /dev/null +++ b/assets/locales/pending/material-selection.json @@ -0,0 +1,38 @@ +{ + "en": { + "material.selection.choose": "Choose a material", + "material.selection.mixed": "Different materials" + }, + "it": { + "material.selection.choose": "Scegli un materiale", + "material.selection.mixed": "Materiali diversi" + }, + "ja": { + "material.selection.choose": "材料を選択", + "material.selection.mixed": "異なる材料" + }, + "zh": { + "material.selection.choose": "选择材料", + "material.selection.mixed": "不同材料" + }, + "ar": { + "material.selection.choose": "اختر مادة", + "material.selection.mixed": "مواد مختلفة" + }, + "he": { + "material.selection.choose": "בחירת חומר", + "material.selection.mixed": "חומרים שונים" + }, + "vi": { + "material.selection.choose": "Chọn vật liệu", + "material.selection.mixed": "Các vật liệu khác nhau" + }, + "de": { + "material.selection.choose": "Material auswählen", + "material.selection.mixed": "Unterschiedliche Materialien" + }, + "ko": { + "material.selection.choose": "재질 선택", + "material.selection.mixed": "서로 다른 재질" + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 52bbf5b00..557a5860e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -876,7 +876,9 @@ impl Dialog { }, vec![SelInput::new("Cylindrical face", FACES, false)], ), - "material.assign" => Dialog::new(Kind::Material { index: 1, editor: Default::default() }, vec![SelInput::new("Bodies", BODIES, true)]), + "material.assign" => { + Dialog::new(Kind::Material { index: usize::MAX, editor: Default::default() }, vec![SelInput::new("Bodies", BODIES, true)]) + } "inspect.section" => Dialog::new( Kind::Section { offset: length_default(s, "0"), flip: false, hatch: true }, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)], @@ -1103,10 +1105,17 @@ impl Dialog { inp.items = default_profiles(s); } d.sync_thread(s); + d.sync_material(s); d.advance(); Some(d) } + fn sync_material(&mut self, s: &Session) { + let Kind::Material { index, editor } = &mut self.kind else { return }; + let bodies = self.inputs.first().map(|input| input.items.body_names()).unwrap_or_default(); + editor.sync_selection(&s.doc, &bodies, index); + } + /// Resolve a newly selected face without replacing an authored size or changing the /// document. Clearing the face also clears a suggestion that no longer applies. fn sync_thread(&mut self, s: &Session) { @@ -1484,6 +1493,7 @@ impl Dialog { self.focus = true; self.error = None; self.sync_thread(s); + self.sync_material(s); true } @@ -1556,6 +1566,7 @@ impl Dialog { } self.error = None; self.sync_thread(s); + self.sync_material(s); } /// Box selection result: replace (or add to) the active input. @@ -1601,6 +1612,7 @@ impl Dialog { } } self.sync_thread(s); + self.sync_material(s); } /// Rebuild a Fillet or Chamfer dialog's edge input from the edges that were picked when @@ -2779,6 +2791,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { sync_reach(app, &mut d); auto_operation(app, &mut d); d.sync_thread(&app.session); + d.sync_material(&app.session); update_measure(app, &mut d); update_fill_cells(app, &mut d); // A refused OK's error is about the inputs it ran with (#641). Once a value (in the dialog, @@ -2838,7 +2851,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { Kind::Sketch => false, // Nothing picked is an answer too: OK empties the chat's tray. Kind::ChatContext => true, - Kind::Material { editor, .. } if editor.editing() => false, + Kind::Material { editor, .. } => !editor.editing() && apply_commands(app, &d).is_ok(), Kind::SaveMesh(_) => crate::dialogs_save_mesh::ready(&d.inputs), Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { .. }) => { // Corner dialogs: preview errors are visual only; validation errors from @@ -3655,6 +3668,7 @@ pub(crate) fn report_title(d: &Dialog) -> String { /// The commands OK runs (an edit rebuilds its feature in place); the live preview runs the same. pub fn apply_commands(app: &SolveApp, d: &Dialog) -> Result, String> { let mut normalized = d.clone(); + normalized.sync_material(&app.session); for value in crate::length_input::fields(&app.session.doc, &mut normalized.kind) { *value = crate::length_input::expression(&app.session.doc, value, ValueKind::Length); } @@ -4303,7 +4317,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S return Err(crate::i18n::tr("material.editor.save_or_discard").to_string()); } need(0, "bodies")?; - let name = s.doc.material_names().get(*index).cloned().unwrap_or_else(|| solidcraft_engine::doc::DEFAULT_MATERIAL.into()); + let name = s.doc.material_names().get(*index).cloned().ok_or_else(|| crate::i18n::tr("material.selection.choose").to_string())?; ("material.assign", json!({"bodies": sels(d, 0).body_names(), "material": name})) } Kind::Section { offset, flip, hatch } => { diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 0b0f957a8..513cda600 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -190,6 +190,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: } else { input_rows(d, ui, &app.session); } + d.sync_material(&app.session); match &mut d.kind { Kind::Material { index, editor } => crate::material_editor::rows(app, ui, index, editor), Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs), diff --git a/crates/ui-egui/src/manage_dialogs_tests.rs b/crates/ui-egui/src/manage_dialogs_tests.rs index 8c4e63185..cc41cbf46 100644 --- a/crates/ui-egui/src/manage_dialogs_tests.rs +++ b/crates/ui-egui/src/manage_dialogs_tests.rs @@ -144,6 +144,59 @@ fn physical_material_is_dense_and_keeps_assignment() { assert!(commands[0].1["material"].is_string()); } +#[test] +fn material_selector_clicking_the_suggested_material_preserves_that_choice_for_new_targets() { + let mut h = fixture(); + h.app.run("material.assign", json!({"bodies":["Body1"],"material":"Aluminum"})).unwrap(); + h.app.run("solid.box", json!({"corner":[30,0,0],"length":10,"width":10,"height":10,"body_name":"Other"})).unwrap(); + h.app.run("material.assign", json!({"bodies":["Other"],"material":"Steel"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Body1".into() }]; + let doc = h.app.session.doc.clone(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + h.app.start("material.assign"); + h.frames(3); + assert!(h.widget("Density: 2.7 g/cm³").is_some()); + h.step(&json!({"click":{"handle":"dialog:Material"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Material:Aluminum"}})).unwrap(); + let d = h.app.dialog.as_mut().unwrap(); + d.active = 0; + d.take_box(&h.app.session, vec![Sel::Body { name: "Other".into() }], false); + h.frames(3); + let commands = dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["material"], "Aluminum"); + assert_eq!(commands[0].1["bodies"], json!(["Other"])); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &h.app.session.doc)); + assert_eq!(history, (h.app.session.undo.len(), h.app.session.redo.len())); +} + +#[test] +fn material_selector_mixed_targets_show_a_placeholder_and_cannot_confirm_until_chosen() { + let mut h = fixture(); + h.app.run("solid.box", json!({"corner":[30,0,0],"length":10,"width":10,"height":10,"body_name":"Other"})).unwrap(); + h.app.run("material.assign", json!({"bodies":["Body1"],"material":"Aluminum"})).unwrap(); + h.app.run("material.assign", json!({"bodies":["Other"],"material":"Steel"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Body1".into() }, Sel::Body { name: "Other".into() }]; + let before = h.app.session.doc.clone(); + h.app.start("material.assign"); + h.frames(3); + assert!(h.widget("Different materials").is_some()); + assert!(dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err()); + assert_eq!(scenario::count_of("dialog:ok:enabled"), Some(0.0)); + h.step(&json!({"click":{"handle":"dialog:Material"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Material:Copper"}})).unwrap(); + h.frames(2); + assert_eq!(scenario::count_of("dialog:ok:enabled"), Some(1.0)); + assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.doc)); + let undo = h.app.session.undo.len(); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + assert_eq!(h.app.session.doc.body_material("Body1"), "Copper"); + assert_eq!(h.app.session.doc.body_material("Other"), "Copper"); + assert_eq!(h.app.session.undo.len(), undo + 1); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.materials, before.materials); +} + #[test] fn physical_material_panel_reviews_saved_si_card_without_changing_the_design() { let mut h = fixture(); diff --git a/crates/ui-egui/src/material_editor.rs b/crates/ui-egui/src/material_editor.rs index 32dd87d1e..8342941ec 100644 --- a/crates/ui-egui/src/material_editor.rs +++ b/crates/ui-egui/src/material_editor.rs @@ -27,9 +27,37 @@ pub struct Editor { pub(crate) draft: Option, error: Option, note: Option, + chosen_material: Option, + observed_index: Option, + mixed_materials: bool, } impl Editor { + /// Follow the targets until the user deliberately chooses a material. Keep a + /// choice by name: inserting, renaming or deleting a library row must not + /// silently turn it into another material at the same ordinal. + pub(crate) fn sync_selection(&mut self, doc: &Document, bodies: &[String], index: &mut usize) { + if self.editing() { + return; + } + let names = doc.material_names(); + if self.observed_index.is_some_and(|previous| previous != *index) { + self.chosen_material = names.get(*index).cloned(); + } + let materials: Vec<_> = bodies + .iter() + .map(|body| { + let assigned = doc.materials.get(body).map(String::as_str).unwrap_or(solidcraft_engine::doc::DEFAULT_MATERIAL); + doc.material_name(assigned).filter(|name| doc.material_density(name).is_some()) + }) + .collect(); + self.mixed_materials = materials.first().is_some_and(|first| materials.iter().any(|material| material != first)); + let common = materials.first().and_then(Option::as_ref).filter(|first| materials.iter().all(|material| material.as_ref() == Some(*first))); + let selected = self.chosen_material.as_ref().or(common); + *index = selected.and_then(|name| names.iter().position(|candidate| candidate == name)).unwrap_or(usize::MAX); + self.observed_index = Some(*index); + } + pub fn editing(&self) -> bool { self.draft.is_some() } @@ -47,6 +75,8 @@ impl Editor { app.run(command, params)?; } *index = app.session.doc.material_names().iter().position(|n| n == &name).unwrap_or(*index); + self.chosen_material = Some(name); + self.observed_index = Some(*index); self.draft = None; self.error = None; self.note = Some(tr("material.editor.saved").to_string()); @@ -406,8 +436,22 @@ fn card_rows(ui: &mut egui::Ui, card: &mut CardDraft) { pub(crate) fn rows(app: &mut SolveApp, ui: &mut egui::Ui, index: &mut usize, editor: &mut Editor) { let names = app.session.doc.material_names(); if editor.draft.is_none() { - let refs: Vec<_> = names.iter().map(String::as_str).collect(); - ui_kit::choice_row(ui, "Material", "mat", index, &refs); + let placeholder = if editor.mixed_materials { "material.selection.mixed" } else { "material.selection.choose" }; + let current = names.get(*index).map(String::as_str).unwrap_or_else(|| tr(placeholder)); + ui_kit::row(ui, "Material", |ui| { + ui_kit::dropdown_menu(ui, "mat", current, |ui| { + for (i, name) in names.iter().enumerate() { + let option = ui_kit::list_picker(ui, &format!("physical_material_{i}"), name, *index == i); + crate::scenario::publish_handle(&format!("dialog:Material:{name}"), option.rect.center()); + if option.clicked() { + *index = i; + editor.chosen_material = Some(name.clone()); + editor.observed_index = Some(i); + ui.close(); + } + } + }); + }); let selected = names.get(*index).map(String::as_str); ui.horizontal_wrapped(|ui| { let new = ui_kit::button(ui, tr("New"), ui_kit::Button::Normal); diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index e261be25c..ba2318280 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -7,6 +7,84 @@ use solidcraft_engine::doc::expr::Kind as ValueKind; use solidcraft_engine::geom::Vec3; use solidcraft_engine::{Sel, Session}; +#[test] +fn material_selector_starts_with_the_assigned_material() { + let mut app = app_with(json!([ + {"command":"solid.box","params":{"length":10,"width":10,"height":10}}, + {"command":"material.assign","params":{"bodies":["Body1"],"material":"Aluminum"}} + ])); + app.session.selection = vec![Sel::Body { name: "Body1".into() }]; + let before = app.session.doc.to_json(); + let d = crate::dialogs::Dialog::for_command(&app, "material.assign").unwrap(); + let commands = crate::dialogs::apply_commands(&app, &d).unwrap(); + assert_eq!(commands[0].1["material"], "Aluminum"); + assert_eq!(app.session.doc.to_json(), before); +} + +fn material_selector_fixture() -> crate::SolveApp { + app_with(json!([ + {"command":"solid.box","params":{"length":10,"width":10,"height":10,"body_name":"Plate"}}, + {"command":"solid.box","params":{"corner":[30,0,0],"length":10,"width":10,"height":10,"body_name":"Block"}}, + {"command":"material.assign","params":{"bodies":["Plate"],"material":"Aluminum"}}, + {"command":"material.assign","params":{"bodies":["Block"],"material":"Steel"}} + ])) +} + +fn material_body(name: &str) -> Sel { + Sel::Body { name: name.into() } +} + +#[test] +fn material_selector_mixed_and_empty_targets_require_an_explicit_choice() { + let mut app = material_selector_fixture(); + let before = app.session.doc.to_json(); + for selected in [vec![], vec![material_body("Plate"), material_body("Block")]] { + app.session.selection = selected; + let d = crate::dialogs::Dialog::for_command(&app, "material.assign").unwrap(); + assert!(crate::dialogs::apply_commands(&app, &d).is_err()); + } + assert_eq!(app.session.doc.to_json(), before); +} + +#[test] +fn material_selector_follows_target_changes_until_a_material_is_chosen() { + let mut app = material_selector_fixture(); + app.session.selection = vec![material_body("Plate")]; + let mut d = crate::dialogs::Dialog::for_command(&app, "material.assign").unwrap(); + d.active = 0; + d.take_box(&app.session, vec![material_body("Block")], false); + assert_eq!(crate::dialogs::apply_commands(&app, &d).unwrap()[0].1["material"], "Steel"); + d.take_box(&app.session, vec![material_body("Plate"), material_body("Block")], false); + assert!(crate::dialogs::apply_commands(&app, &d).is_err()); + d.pick(&app.session, material_body("Block")); + assert_eq!(crate::dialogs::apply_commands(&app, &d).unwrap()[0].1["material"], "Aluminum"); + let crate::dialogs::Kind::Material { index, .. } = &mut d.kind else { panic!("material dialog") }; + *index = app.session.doc.material_names().iter().position(|name| name == "Copper").unwrap(); + d.take_box(&app.session, vec![material_body("Block")], false); + let commands = crate::dialogs::apply_commands(&app, &d).unwrap(); + assert_eq!(commands[0].1["material"], "Copper"); + assert_eq!(commands[0].1["bodies"], json!(["Block"])); +} + +#[test] +fn material_selector_supports_custom_materials_faces_and_default_without_editing_the_document() { + let mut app = material_selector_fixture(); + app.run("material.create", json!({"name":"Synthetic material","density_g_cm3":0.8})).unwrap(); + app.run("material.assign", json!({"bodies":["Plate","Block"],"material":"Synthetic material"})).unwrap(); + app.session = Session::new(solidcraft_engine::doc::Document::from_json(&app.session.doc.to_json()).unwrap()); + for selection in [vec![material_body("Plate"), material_body("Block")], vec![Sel::Face { body: "Plate".into(), index: 0, point: Vec3::ZERO }]] { + app.session.selection = selection; + let before = app.session.doc.to_json(); + let d = crate::dialogs::Dialog::for_command(&app, "material.assign").unwrap(); + assert_eq!(crate::dialogs::apply_commands(&app, &d).unwrap()[0].1["material"], "Synthetic material"); + assert_eq!(app.session.doc.to_json(), before); + } + app.run("material.assign", json!({"bodies":["Plate"],"material":"Default"})).unwrap(); + app.session.selection = vec![material_body("Plate")]; + let d = crate::dialogs::Dialog::for_command(&app, "material.assign").unwrap(); + assert_eq!(crate::dialogs::apply_commands(&app, &d).unwrap()[0].1["material"], "Default"); +} + #[test] fn confirming_coplanar_body_faces_uses_one_atomic_extrusion() { let mut h = crate::scenario::Harness::new();