From 5e05d925e07c0486e92f6e981a66178dcdc311ad Mon Sep 17 00:00:00 2001 From: amolinari-autotex Date: Wed, 21 Oct 2026 18:56:38 +0000 Subject: [PATCH] Tapped Hole: keep Custom selection and edit nominal diameter (#2440) (#2441) * claim: #2440 * feat: choose ISO metric tapped-hole sizes and derive the drill diameter * fix: label the tap drill and hide the unused diameter editor * test: cover tapped hole catalogue and drill sizing * fix: omit coarse metric pitch from generated designations * Keep custom tapped-hole nominal diameter and pitch editable Preserve Custom as dialog state, derive the existing metric designation from numeric inputs, and refuse invalid drafts without applying the last valid size. Retain manual text editing, physical tap-drill geometry and saved-design compatibility. * fix(i18n): register custom tapped hole labels in source catalogs * Adapt tapped-hole Custom fields to the current form kit * fix: preserve tapped designation focus with dynamic custom rows --- assets/locales/en.json | 4 + assets/locales/it.json | 3 + assets/locales/ja.json | 4 + assets/locales/zh.json | 4 + crates/ui-egui/src/dialogs.rs | 25 +- crates/ui-egui/src/dialogs_dense.rs | 6 +- crates/ui-egui/src/dialogs_thread.rs | 371 +++++++++++++++++++++++++- crates/ui-egui/src/preselect_tests.rs | 5 +- docs/thread-designations.md | 7 + 9 files changed, 418 insertions(+), 11 deletions(-) create mode 100644 docs/thread-designations.md diff --git a/assets/locales/en.json b/assets/locales/en.json index 35de93051..9d184597a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -102,6 +102,7 @@ "Curv. Comb": "Curv. Comb", "Curvature (G2)": "Curvature (G2)", "Curvature change (G3)": "Curvature change (G3)", + "Custom": "Custom", "Customize Toolbar": "Customize Toolbar", "Delete": "Delete", "Delete all": "Delete all", @@ -233,6 +234,7 @@ "No matching appearance presets.": "No matching appearance presets.", "No matching appearances": "No matching appearances", "No visible bodies to export.": "No visible bodies to export.", + "Nominal diameter": "Nominal diameter", "None": "None", "Not available yet": "Not available yet", "Notch": "Notch", @@ -256,6 +258,7 @@ "Pick the tool bodies": "Pick the tool bodies", "Picked": "Picked", "Picked point": "Picked point", + "Pitch": "Pitch", "Place at the origin instead": "Place at the origin instead", "Plastic Rules": "Plastic Rules", "Playback": "Playback", @@ -361,6 +364,7 @@ "TRIM": "TRIM", "Tangent (G1)": "Tangent (G1)", "Tangent Chain": "Tangent Chain", + "Tap drill diameter": "Tap drill diameter", "Tear": "Tear", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", diff --git a/assets/locales/it.json b/assets/locales/it.json index 233e5846f..76bc619d3 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -102,6 +102,7 @@ "Curv. Comb": "Pettine curv.", "Curvature (G2)": "Curvatura (G2)", "Curvature change (G3)": "Variazione di curvatura (G3)", + "Custom": "Personalizzato", "Customize Toolbar": "Personalizza barra degli strumenti", "Delete": "Elimina", "Delete all": "Elimina tutto", @@ -233,6 +234,7 @@ "No matching appearance presets.": "Nessun predefinito di aspetto corrispondente.", "No matching appearances": "Nessun aspetto corrispondente", "No visible bodies to export.": "Nessun corpo visibile da esportare.", + "Nominal diameter": "Diametro nominale", "None": "Nessuno", "Not available yet": "Non ancora disponibile", "Notch": "Intaglio", @@ -256,6 +258,7 @@ "Pick the tool bodies": "Seleziona i corpi utensile", "Picked": "Selezionato", "Picked point": "Punto selezionato", + "Pitch": "Passo", "Place at the origin instead": "Posiziona invece nell'origine", "Plastic Rules": "Regole per plastica", "Playback": "Riproduzione", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 7b64c07d6..7a80e4b68 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -102,6 +102,7 @@ "Curv. Comb": "曲率コーム", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率変化 (G3)", + "Custom": "カスタム", "Customize Toolbar": "ツールバーのカスタマイズ", "Delete": "削除", "Delete all": "すべて削除", @@ -233,6 +234,7 @@ "No matching appearance presets.": "一致する外観プリセットはありません。", "No matching appearances": "一致する外観がありません", "No visible bodies to export.": "出力する表示中のボディがありません。", + "Nominal diameter": "呼び径", "None": "なし", "Not available yet": "まだ利用できません", "Notch": "ノッチ", @@ -256,6 +258,7 @@ "Pick the tool bodies": "ツールボディを選択", "Picked": "選択したもの", "Picked point": "選択した点", + "Pitch": "ピッチ", "Place at the origin instead": "代わりに原点に配置", "Plastic Rules": "樹脂ルール", "Playback": "再生", @@ -361,6 +364,7 @@ "TRIM": "トリム", "Tangent (G1)": "接線 (G1)", "Tangent Chain": "正接チェーン", + "Tap drill diameter": "タップ下穴径", "Tear": "引き裂き", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "破線のスケッチは保存された平面ガイドです。新しい面を選択してアタッチメントを修復してください。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存された作成元のオカレンスが見つかりません。再バインドする前に有効な作成元配置を選択してください。", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f6851834b..ac79a95c7 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -102,6 +102,7 @@ "Curv. Comb": "曲率梳", "Curvature (G2)": "曲率 (G2)", "Curvature change (G3)": "曲率变化 (G3)", + "Custom": "自定义", "Customize Toolbar": "自定义工具栏", "Delete": "删除", "Delete all": "全部删除", @@ -233,6 +234,7 @@ "No matching appearance presets.": "没有匹配的外观预设。", "No matching appearances": "没有匹配的外观", "No visible bodies to export.": "没有可导出的可见实体。", + "Nominal diameter": "公称直径", "None": "无", "Not available yet": "暂不可用", "Notch": "缺口", @@ -256,6 +258,7 @@ "Pick the tool bodies": "选择工具实体", "Picked": "所选", "Picked point": "选取的点", + "Pitch": "螺距", "Place at the origin instead": "改为放置在原点", "Plastic Rules": "塑料规则", "Playback": "播放", @@ -361,6 +364,7 @@ "TRIM": "修剪", "Tangent (G1)": "相切 (G1)", "Tangent Chain": "相切链", + "Tap drill diameter": "攻丝底孔直径", "Tear": "撕裂", "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "虚线草图是已保存的平面引导。选择一个新面以修复附着。", "The saved author occurrence is missing. Select a valid author placement before rebinding.": "保存的作者实例缺失。重新绑定前请选择有效的作者放置。", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f331fda05..69b83ca21 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -386,11 +386,13 @@ pub struct HoleOpts { /// Tap type: tapped (a cosmetic thread) instead of simple. pub tapped: bool, pub thread: String, + /// Custom nominal diameter and pitch being edited, separate from the saved designation. + pub custom_thread: Option, } impl Default for HoleOpts { fn default() -> Self { - HoleOpts { multiple: false, all: false, angled: true, tip_angle: "118 deg".into(), tapped: false, thread: "M5".into() } + HoleOpts { multiple: false, all: false, angled: true, tip_angle: "118 deg".into(), tapped: false, thread: "M5".into(), custom_thread: None } } } @@ -851,7 +853,9 @@ impl Dialog { } *of = picks.to_vec(); *suggested = picks.first().and_then(|sel| match sel { - Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok(), + Sel::Face { point, .. } => solidcraft_engine::doc::suggested_thread(&s.world_state(), *point).ok().map(|value| { + solidcraft_engine::doc::parse_metric_thread(&value).map(|(d, p)| crate::dialogs_thread::designation(d, p)).unwrap_or(value) + }), _ => None, }); *designation = suggested.clone().unwrap_or_default(); @@ -949,7 +953,12 @@ impl Dialog { } Kind::Shell { thickness } => ("Thickness", ValueKind::Length, thickness), Kind::Draft { angle } => ("Angle", ValueKind::Angle, angle), - Kind::Hole { diameter, .. } => ("Diameter", ValueKind::Length, diameter), + Kind::Hole { diameter, opts, .. } => { + if opts.tapped { + return None; + } + ("Diameter", ValueKind::Length, diameter) + } // A move's main value follows its type: a distance along X for the ones that // translate, the angle for Rotate. Point to Point is two picks with nothing to type. Kind::Move { mode, x, angle, .. } => match *mode { @@ -3607,7 +3616,9 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let mut out = Vec::new(); for place in places { let mut params = place; - params["diameter"] = json!(diameter); + if !opts.tapped { + params["diameter"] = json!(diameter); + } params["type"] = json!(ty); if to_object_on(&d.inputs) { params["to"] = to_object_point(&d.inputs).ok_or("select the object to drill to")?; @@ -3617,7 +3628,11 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S if ty == "drilled" { params["tip_angle"] = json!(opts.tip_angle); } - if opts.tapped && !opts.thread.trim().is_empty() { + if opts.tapped { + if let Some(error) = opts.custom_thread.as_ref().and_then(|draft| draft.error.as_ref()) { + return Err(error.clone()); + } + solidcraft_engine::doc::parse_metric_thread(&opts.thread).ok_or("select a valid metric thread size")?; params["thread"] = json!(opts.thread.trim()); } match *kind { diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 3ed097db7..a58e1d511 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -511,7 +511,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: opts.tapped = tap == 1; }); if opts.tapped { - enter |= expr_row(ui, "Size", &mut opts.thread); + enter |= crate::dialogs_thread::hole_rows(ui, &app.session.doc, &mut opts.thread, &mut opts.custom_thread); } if *kind == 0 { form_row(ui, "Drill Point", |ui| { @@ -526,7 +526,9 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: if *kind == 0 && opts.angled { enter |= expr_row(ui, "Tip Angle", &mut opts.tip_angle); } - enter |= expr_row(ui, "Diameter", diameter); + if !opts.tapped { + enter |= expr_row(ui, "Diameter", diameter); + } if *kind == 1 { enter |= expr_row(ui, "Counterbore Ø", cb_diameter); enter |= expr_row(ui, "Counterbore depth", cb_depth); diff --git a/crates/ui-egui/src/dialogs_thread.rs b/crates/ui-egui/src/dialogs_thread.rs index f765c4c3c..a680fa6fb 100644 --- a/crates/ui-egui/src/dialogs_thread.rs +++ b/crates/ui-egui/src/dialogs_thread.rs @@ -1,7 +1,7 @@ //! Metric thread choices use the document's sizing table and the existing designation //! parameter. Browsing choices does not edit the model or freeze an automatic feature. -use solidcraft_engine::doc::{metric_thread_sizes, parse_metric_thread}; +use solidcraft_engine::doc::{Document, metric_thread_sizes, parse_metric_thread}; use crate::dialogs::{combo, form_row}; use crate::i18n::tr; @@ -11,6 +11,109 @@ use crate::ui_kit::text_row; /// The coarse and current pitches are included separately; custom pairs remain editable. const PITCHES: &[f64] = &[0.2, 0.25, 0.35, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0]; +/// Generated metric designations omit only the shared catalogue's coarse pitch. +/// Authored designation text is never rewritten just by displaying a dialog. +pub(crate) fn designation(diameter: f64, pitch: f64) -> String { + let coarse = metric_thread_sizes().iter().any(|(d, p)| (d - diameter).abs() < 1e-9 && (p - pitch).abs() < 1e-9); + if coarse { format!("M{diameter}") } else { format!("M{diameter}x{pitch}") } +} + +/// Unsaved numeric inputs for a custom metric designation. The document still stores only +/// the existing designation; an invalid draft must not apply its last valid value. +#[derive(Clone, Debug, PartialEq)] +pub struct HoleThreadDraft { + source: String, + diameter: String, + pitch: String, + pub(crate) error: Option, +} + +impl HoleThreadDraft { + fn new(source: &str) -> Self { + let (diameter, pitch) = match parse_metric_thread(source) { + Some((d, p)) => (format!("{d} mm"), format!("{p} mm")), + None => (String::new(), String::new()), + }; + Self { source: source.into(), diameter, pitch, error: None } + } + + fn update(&mut self, doc: &Document, authored: &mut String) { + let candidate = || -> Result { + let d = doc.eval(&self.diameter, solidcraft_engine::doc::expr::Kind::Length).map_err(|e| format!("nominal diameter: {e}"))?; + let p = doc.eval(&self.pitch, solidcraft_engine::doc::expr::Kind::Length).map_err(|e| format!("pitch: {e}"))?; + let text = designation(d, p); + parse_metric_thread(&text).ok_or("use a positive nominal diameter and a pitch smaller than it")?; + Ok(text) + }; + match candidate() { + Ok(text) => { + *authored = text; + self.source = authored.clone(); + self.error = None; + } + Err(error) => self.error = Some(error), + } + } +} + +/// Tapped holes use the existing metric catalogue; the engine derives the tap drill. +/// Custom remains a dialog mode even when its current values match a catalogue size. +pub(crate) fn hole_rows(ui: &mut egui::Ui, doc: &Document, designation: &mut String, custom: &mut Option) -> bool { + let designation_id = ui.make_persistent_id("hole_thread_designation"); + form_row(ui, "Profile", |ui| { + ui.label(tr("ISO metric")); + }); + + let sizes = metric_thread_sizes(); + let current = parse_metric_thread(designation); + let catalogue = current.and_then(|pair| sizes.iter().position(|s| *s == pair)); + if custom.as_ref().is_some_and(|draft| draft.source != *designation) || (custom.is_none() && catalogue.is_none()) { + *custom = Some(HoleThreadDraft::new(designation)); + } + form_row(ui, "Size", |ui| { + let mut selected = if custom.is_some() { sizes.len() } else { catalogue.unwrap_or(sizes.len()) }; + let before = selected; + let mut labels: Vec = sizes.iter().map(|(d, p)| self::designation(*d, *p)).collect(); + labels.push("Custom".to_string()); + let labels: Vec<&str> = labels.iter().map(String::as_str).collect(); + combo(ui, "hole_thread_catalogue", &labels, &mut selected); + if selected != before { + if let Some((d, p)) = sizes.get(selected) { + *designation = self::designation(*d, *p); + *custom = None; + } else { + *custom = Some(HoleThreadDraft::new(designation)); + } + } + }); + + let mut enter = false; + if let Some(draft) = custom { + let (diameter_enter, diameter_changed) = text_row(ui, "Nominal diameter", &mut draft.diameter, ""); + let (pitch_enter, pitch_changed) = text_row(ui, "Pitch", &mut draft.pitch, ""); + if diameter_changed || pitch_changed { + draft.update(doc, designation); + } + enter |= diameter_enter || pitch_enter; + } + + let response = form_row(ui, "Designation", |ui| crate::ui_kit::cell_editor(ui, designation_id, designation, "M5 or M5x0.5", false)); + if response.changed() && custom.is_some() { + *custom = Some(HoleThreadDraft::new(designation)); + } + form_row(ui, "Tap drill diameter", |ui| { + match parse_metric_thread(designation).filter(|_| custom.as_ref().is_none_or(|draft| draft.error.is_none())) { + Some((d, p)) => { + ui.label(format!("{:.3} mm", d - p)); + } + None => { + ui.label(tr("Select size")); + } + } + }); + enter || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) +} + /// Returns (Enter pressed, automatic sizing requested). pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut Option, modeled: &mut bool, full: &mut bool) -> (bool, bool) { form_row(ui, "Profile", |ui| { @@ -54,7 +157,7 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut && let Some(d) = diameters.get(selected) && let Some((_, coarse)) = metric_thread_sizes().iter().find(|(n, _)| n == d) { - *designation = format!("M{d}x{coarse}"); + *designation = self::designation(*d, *coarse); *suggested = None; } }); @@ -79,7 +182,7 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut if selected != before && let (Some((d, _)), Some(p)) = (current, pitches.get(selected)) { - *designation = format!("M{d}x{p}"); + *designation = self::designation(d, *p); *suggested = None; } }); @@ -94,3 +197,265 @@ pub(crate) fn rows(ui: &mut egui::Ui, designation: &mut String, suggested: &mut } (enter, reset) } + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod contribution_tests { + use super::*; + use crate::{ + Services, SolveApp, + dialogs::{Dialog, Kind, apply_commands}, + }; + use serde_json::json; + use solidcraft_engine::{Sel, Session, geom::Vec3}; + fn hole() -> (SolveApp, Dialog) { + let mut app = SolveApp::new(Session::default(), Services::default()); + app.run("solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Plate"})).unwrap(); + app.session.selection = vec![Sel::Face { body: "Plate".into(), index: 5, point: Vec3::new(10.0, 10.0, 10.0) }]; + let d = Dialog::for_command(&app, "solid.hole").unwrap(); + (app, d) + } + fn custom_hole_widget() -> crate::scenario::Harness { + let (app, dialog) = hole(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.dialog = Some(dialog); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type:Tapped"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Size"}})).unwrap(); + let at = crate::scenario::handle_at("dialog:Size:M5").unwrap(); + h.call("ui.scroll", json!({"x":at.x,"y":at.y,"delta":-2000})); + h.frames(20); + h.step(&json!({"widget":"Custom"})).unwrap(); + h.frames(3); + h + } + + fn replace_field(h: &mut crate::scenario::Harness, field: &str, value: &str) { + h.step(&json!({"click":{"handle":format!("dialog:{field}")}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":value})).unwrap(); + h.frames(2); + } + + #[test] + fn custom_tapped_size_keeps_its_choice_and_exposes_nominal_diameter() { + let h = custom_hole_widget(); + assert!(h.widget("Custom").is_some(), "Custom must remain the selected size after the popup closes"); + assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_some(), "a custom tapped hole needs an editable nominal diameter"); + let card = crate::scenario::rect_of("dialog:card").unwrap(); + for label in ["Profile", "Size", "Nominal diameter", "Pitch", "Designation", "Tap drill diameter"] { + let row = crate::scenario::rect_of(&format!("dialog:row:{label}")).unwrap(); + let control = crate::scenario::rect_of(&format!("dialog:control:{label}")).unwrap(); + assert_eq!(row.height(), crate::theme::Tokens::get().control_height, "{label}"); + assert!(card.contains_rect(row) && row.contains_rect(control), "{label}: {row:?} {control:?} outside {card:?}"); + } + } + + #[test] + fn custom_nominal_diameter_and_pitch_change_the_real_hole_and_reopen() { + let mut h = custom_hole_widget(); + replace_field(&mut h, "Nominal diameter", "8.5 mm"); + replace_field(&mut h, "Pitch", "1 mm"); + let commands = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["thread"], "M8.5x1"); + assert!(commands[0].1.get("diameter").is_none(), "the nominal size must reach the engine through the thread designation"); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + h.frames(3); + assert!(h.app.dialog.is_none()); + let faces = h.app.run("model.faces", json!({"body":"Plate"})).unwrap(); + assert!( + faces["faces"].as_array().unwrap().iter().any(|face| { face["cylinder"]["radius"].as_f64().is_some_and(|r| (r - 3.75).abs() < 1e-9) }), + "the physical tap drill must be 8.5 - 1 = 7.5 mm" + ); + let saved = h.app.session.doc.to_json(); + let reopened = Session::new(Document::from_json(&saved).unwrap()); + let world = reopened.world_state(); + assert_eq!(world.threads.len(), 1); + assert_eq!(world.threads[0].designation, "M8.5x1"); + assert!((world.threads[0].pitch - 1.).abs() < 1e-9); + } + + #[test] + fn an_invalid_custom_pitch_blocks_the_old_valid_size_and_cancel_keeps_the_model() { + let mut h = custom_hole_widget(); + let before = h.app.session.doc.to_json(); + let history = (h.app.session.undo.len(), h.app.session.redo.len()); + replace_field(&mut h, "Pitch", "5 mm"); + assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err()); + assert_eq!(crate::scenario::count_of("dialog:ok:enabled"), Some(0.0)); + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + assert!(h.app.dialog.is_some(), "an invalid custom draft must keep the dialog open"); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.dialog.is_none()); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!((h.app.session.undo.len(), h.app.session.redo.len()), history); + } + + #[test] + fn manual_designation_keeps_keyboard_focus_when_custom_fields_appear() { + let (app, dialog) = hole(); + let mut h = crate::scenario::Harness::new(); + h.app = app; + h.app.dialog = Some(dialog); + h.frames(3); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Hole Tap Type:Tapped"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Designation"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + for text in ["M", "8", "x", "1"] { + h.step(&json!({"text":text})).unwrap(); + h.frames(2); + } + assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["thread"], "M8x1"); + assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_some()); + } + + #[test] + fn custom_lengths_use_explicit_units_and_invalid_drafts_never_apply_stale_values() { + let (mut app, mut dialog) = hole(); + app.run("document.units", json!({"units":"in"})).unwrap(); + let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("not a hole") }; + opts.tapped = true; + opts.all = true; + let mut draft = HoleThreadDraft::new(&opts.thread); + draft.diameter = "0.25 in".into(); + draft.pitch = "0.05 in".into(); + draft.update(&app.session.doc, &mut opts.thread); + assert!(draft.error.is_none()); + let (d, p) = parse_metric_thread(&opts.thread).unwrap(); + assert!((d - 6.35).abs() < 1e-9 && (p - 1.27).abs() < 1e-9); + opts.custom_thread = Some(draft); + let commands = apply_commands(&app, &dialog).unwrap(); + app.run(&commands[0].0, commands[0].1.clone()).unwrap(); + let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("not a hole") }; + for invalid in ["", "0", "-1 mm", "unknown_size", "NaN"] { + let draft = opts.custom_thread.as_mut().unwrap(); + draft.diameter = invalid.into(); + draft.update(&app.session.doc, &mut opts.thread); + assert!(draft.error.is_some(), "{invalid}"); + } + assert!(apply_commands(&app, &dialog).is_err()); + } + #[test] + fn contribution_tapped_holes_derive_the_drill_from_the_catalogue() { + for (designation, expected) in [("M5", 4.2), ("M6x1", 5.0), ("M5x0.5", 4.5)] { + let (mut app, mut d) = hole(); + if let Kind::Hole { diameter, opts, .. } = &mut d.kind { + *diameter = "17 mm".into(); + opts.tapped = true; + opts.all = true; + opts.thread = designation.into(); + } + assert!(d.primary().is_none(), "no independent diameter editor for a tapped hole"); + let commands = apply_commands(&app, &d).unwrap(); + let (id, p) = &commands[0]; + assert!(p.get("diameter").is_none()); + assert_eq!(p["thread"], designation); + let out = app.run(id, p.clone()).unwrap(); + let f = app.session.doc.feature(out["feature"].as_u64().unwrap()).unwrap(); + let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &f.kind else { panic!("not a Hole") }; + let drill = app.session.doc.eval(diameter, solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((drill - expected).abs() < 1e-9, "{designation}: {drill}"); + } + } + #[test] + fn contribution_invalid_tapped_holes_are_refused_and_plain_holes_keep_diameter() { + let (app, mut d) = hole(); + assert!(d.primary().is_some()); + assert!(apply_commands(&app, &d).unwrap()[0].1.get("diameter").is_some()); + for designation in ["", "M0", "M5x5", "M5xNaN", "not a thread"] { + if let Kind::Hole { opts, .. } = &mut d.kind { + opts.tapped = true; + opts.thread = designation.into(); + } + assert!(apply_commands(&app, &d).is_err(), "{designation}"); + } + } + #[test] + fn contribution_thread_catalogue_is_parseable_and_rendering_keeps_custom_designations() { + for (d, p) in metric_thread_sizes() { + assert_eq!(parse_metric_thread(&format!("M{d}")), Some((*d, *p))); + assert_eq!(parse_metric_thread(&format!("M{d}x{p}")), Some((*d, *p))); + } + let ctx = egui::Context::default(); + for original in ["M5", "M5x0.5", "M33x1", "invalid"] { + let mut designation = original.to_string(); + let mut custom = None; + let doc = Document::default(); + let _ = ctx.run_ui(Default::default(), |ui| { + egui::Grid::new("hole_catalogue").show(ui, |ui| { + hole_rows(ui, &doc, &mut designation, &mut custom); + }); + }); + assert_eq!(designation, original); + } + } + + #[test] + fn contribution_metric_designation_omits_only_the_catalogue_coarse_pitch() { + for &(d, p) in metric_thread_sizes() { + assert_eq!(designation(d, p), format!("M{d}")); + assert_eq!(parse_metric_thread(&designation(d, p)), Some((d, p))); + assert_eq!(parse_metric_thread(&designation(d, p / 2.)), Some((d, p / 2.))); + assert!(designation(d, p / 2.).contains('x')); + } + assert_eq!(designation(8., 1.25), "M8"); + assert_eq!(designation(8., 1.), "M8x1"); + assert_eq!(designation(5., 0.5), "M5x0.5"); + assert_eq!(designation(33., 1.), "M33x1"); + assert_eq!(designation(8., 1.25 + 1e-12), "M8"); + assert!(designation(8., 1.25 + 1e-6).contains('x')); + } + + #[test] + fn contribution_metric_designation_rendering_preserves_authored_legacy_and_custom_text() { + let context = egui::Context::default(); + crate::fonts::setup_bundled_fonts(&context); + for original in ["M8x1.25", "M8x1", "M33x1", "M5×0.5", " m8x1.25 ", "invalid"] { + let mut hole = original.to_string(); + let mut thread = original.to_string(); + let mut suggested = None; + let mut modeled = false; + let mut full = true; + let mut custom = None; + let doc = Document::default(); + let _ = context.run_ui(Default::default(), |ui| { + egui::Grid::new("authored_hole").show(ui, |ui| { + hole_rows(ui, &doc, &mut hole, &mut custom); + }); + egui::Grid::new("authored_thread").show(ui, |ui| { + rows(ui, &mut thread, &mut suggested, &mut modeled, &mut full); + }); + }); + assert_eq!(hole, original); + assert_eq!(thread, original); + } + } + + #[test] + fn contribution_metric_designation_keeps_domain_pitch_drill_units_and_reopen() { + for (diameter, pitch, drill) in [(8., 1.25, 6.75), (8., 1., 7.), (5., 0.5, 4.5)] { + let (mut app, mut dialog) = hole(); + app.run("document.units", json!({"units":"in"})).unwrap(); + if let Kind::Hole { opts, .. } = &mut dialog.kind { + opts.tapped = true; + opts.all = true; + opts.thread = designation(diameter, pitch); + } + let commands = apply_commands(&app, &dialog).unwrap(); + let result = app.run(&commands[0].0, commands[0].1.clone()).unwrap(); + let feature = app.session.doc.feature(result["feature"].as_u64().unwrap()).unwrap(); + let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &feature.kind else { panic!("not a hole") }; + assert!((app.session.doc.eval(diameter, solidcraft_engine::doc::expr::Kind::Length).unwrap() - drill).abs() < 1e-9); + let saved = app.session.doc.to_json(); + let reopened = Session::new(solidcraft_engine::doc::Document::from_json(&saved).unwrap()); + let state = reopened.world_state(); + assert_eq!(state.threads.len(), 1); + assert!((state.threads[0].pitch - pitch).abs() < 1e-9); + } + } +} diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 85c2daef9..9d62a25af 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1361,7 +1361,10 @@ fn thread_choices_can_start_without_a_face_and_recover_from_invalid_text() { h.call("ui.scroll", json!({"x":first.x,"y":first.y,"delta":-60})); h.frames(12); h.step(&json!({"click":{"handle":"dialog:Size:8 mm"}})).unwrap(); - assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "M8x1.25")); + assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Thread { designation, .. } if designation == "M8")); + if let Kind::Thread { designation, .. } = &h.app.dialog.as_ref().unwrap().kind { + assert_eq!(solidcraft_engine::doc::parse_metric_thread(designation), Some((8.0, 1.25))); + } assert!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).is_err(), "a face is still required"); } diff --git a/docs/thread-designations.md b/docs/thread-designations.md new file mode 100644 index 000000000..f27a93eaf --- /dev/null +++ b/docs/thread-designations.md @@ -0,0 +1,7 @@ +# Metric thread designations + +Generated size choices use the shared metric catalogue. Its coarse pitch is omitted from the designation: **M8** means diameter 8 mm and coarse pitch 1.25 mm. A fine or custom pitch remains explicit, for example **M8x1**. Hole catalogue choices and generated Thread size/pitch choices follow the same rule. + +This changes generated UI text, not the resolved numerical pitch or geometry. Existing authored designation text, including explicit legacy coarse pitches, is retained when a dialog is merely displayed. Custom and fine designations remain editable. Catalogue dimensions are millimetres regardless of the design's display units. + +Tapped Hole continues to derive its existing tap-drill diameter from nominal diameter minus pitch: M8 gives 6.75 mm, while M8x1 gives 7 mm. Saving and reopening retains the resolved pitch. Only the currently supported ISO metric family is offered; other thread families and a complete fine-pitch catalogue are not added by this change.