//! The thread dialog and a tapped hole's thread rows. The Thread dialog: the series, size, class, //! hand, starts, extent, runouts, tip and the modelled option of `solid.thread`; the Hole dialog's //! tapped rows: the series, size, class and drill of `solid.hole`'s thread. Choices only build the //! commands' parameters: the command checks the geometry and its error text is what the dialog //! shows. Browsing choices does not edit the model or freeze an automatic feature. //! //! One thread model, the document's ([`threads`]): a thread is its series, an item of the thread //! service's catalogue ([`ThreadItem`]), and its designation as the service reads it. Both dialogs //! list the catalogue's series under its groups; every size, class, limit of size and drill they //! show is the service's (`solidcraft_kernel::threads`), and a face's size comes from automatic //! sizing in the series chosen. The last series, Custom, lists no sizes: in either dialog its //! Profile, Diameter, Pitch and Angle rows make the designation the service writes //! ([`CustomRows`]). use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use std::thread::LocalKey; use serde_json::{Value, json}; use solidcraft_engine::doc::thread_forms::{self as threads, ClassLimitsMm, ScrewThread, SteepFlank, ThreadHand, ThreadTip}; use solidcraft_engine::doc::{Document, Expr, Feature, FeatureKind, ThreadLimit, ThreadRunout}; use solidcraft_engine::{Sel, Session}; use solidcraft_kernel::threads as kernel_threads; use solidcraft_kernel::threads::{CatalogueItem, CustomProfile, ThreadGroup, ThreadItem, ThreadProfile, ThreadSide, ThreadUnit, TipStandard}; use crate::dialogs::{Dialog, HoleOpts, Kind, combo, edge_sel, face_sel, form_row, object_point, plane_sel, put, set_object_accepting}; use crate::selection::{Accept, EDGES, FACES, PLANES, SelInput}; use crate::ui_kit::{StatusTone, choice_row, expr_row, hint_row, text_row}; use solidcraft_ui_text::tr_by_id; // --------------------------------------------------------------------------------------------- // The thread service, as the dialogs read it // --------------------------------------------------------------------------------------------- /// Answers about threads a window keeps, each with what it was asked: the dialogs are drawn every /// frame, and an answer depends on the question alone (the catalogue does not change). type Kept = RefCell>; /// How many answers of one kind about designations a window keeps: the dialogs ask about a size /// or two at a time. const KEPT: usize = 32; /// How many answers of one kind about series a window keeps: every series, on either side. const KEPT_SERIES: usize = 64; thread_local! { static CATALOGUE: Kept<(), Rc<[CatalogueItem]>> = const { RefCell::new(VecDeque::new()) }; static SIZES: Kept<(ThreadItem, bool), Rc<[String]>> = const { RefCell::new(VecDeque::new()) }; static NUMBERS: Kept<(ThreadItem, bool), Rc<[Numbers]>> = const { RefCell::new(VecDeque::new()) }; static ENTRIES: Kept = const { RefCell::new(VecDeque::new()) }; static HOLE_SERIES: Kept<(), Rc<[ThreadItem]>> = const { RefCell::new(VecDeque::new()) }; static THREADS: Kept> = const { RefCell::new(VecDeque::new()) }; static PROFILES: Kept> = const { RefCell::new(VecDeque::new()) }; static DRILLS: Kept<(String, Option), Option> = const { RefCell::new(VecDeque::new()) }; static RANGES: Kept<(String, Option), Option<(f64, f64)>> = const { RefCell::new(VecDeque::new()) }; static LIMITS: Kept<(String, String, bool), Option> = const { RefCell::new(VecDeque::new()) }; } /// The answer for `key`: kept from an earlier frame, or worked out by `work` and kept, at most /// `bound` of them (the oldest goes first). fn kept(store: &'static LocalKey>, bound: usize, key: K, work: impl FnOnce(&K) -> V) -> V { let hit = store.with(|answers| answers.try_borrow().ok().and_then(|answers| answers.iter().find(|(k, _)| *k == key).map(|(_, v)| v.clone()))); if let Some(value) = hit { return value; } // Worked out with nothing borrowed: the work may ask for other answers. let value = work(&key); store.with(|answers| { if let Ok(mut answers) = answers.try_borrow_mut() { while answers.len() >= bound.max(1) { answers.pop_front(); } answers.push_back((key, value.clone())); } }); value } /// A size with its major diameter and pitch (mm), as the service reads it. #[derive(Clone, Debug, PartialEq)] struct Numbers { designation: String, major: f64, pitch: f64, } /// A tapped hole's drill, as the thread service gives it: the drill (mm), the drills a hole of the /// thread accepts in its class ([`drill_range`]), the internal thread's minor diameter, whether a /// drill table has the size (else the drill is that minor diameter), and whether the drill's table /// is one of inch drills, so the drill reads in inches. #[derive(Clone, Copy, Debug, PartialEq)] struct Drill { mm: f64, low: f64, high: f64, minor: f64, tabulated: bool, inch: bool, } /// Every series of the thread catalogue, in its order, with its group. fn catalogue() -> Rc<[CatalogueItem]> { kept(&CATALOGUE, 1, (), |_| kernel_threads::items().into()) } /// The group of the catalogue a series stands in. fn group_of(series: ThreadItem) -> Option { catalogue().iter().find(|c| c.item == series).map(|c| c.group) } /// A series' entry in the catalogue, as the thread service gives it (`item`): its group, the sides /// it has threads on, the unit of its standard, the kind of its sizes' profile, whether it reads /// sizes off its lists, and the standard that gives its chamfered tip's depth. fn entry(series: ThreadItem) -> CatalogueItem { kept(&ENTRIES, KEPT_SERIES, series, |&series| kernel_threads::item(series)) } /// The side a hole (`internal`) or a shaft takes a thread on. fn side_of(internal: bool) -> ThreadSide { if internal { ThreadSide::Internal } else { ThreadSide::External } } /// The thread a designation names, as the document reads it through the thread service; none /// for text it does not read (a designation being typed among them). fn thread(designation: &str) -> Option { let text = designation.trim(); if text.is_empty() { return None; } kept(&THREADS, KEPT, text.to_string(), |text| threads::read_thread(text).ok()) } /// The kind of profile of the thread a designation names, as the thread service reads it /// (`form.profile`); none for text it reads no thread of. fn profile_of(designation: &str) -> Option { let text = designation.trim(); if text.is_empty() { return None; } kept(&PROFILES, KEPT, text.to_string(), |text| kernel_threads::find(text).ok().map(|t| t.form.profile)) } /// The sizes of a series by their designations as a hole (`internal`) or a shaft takes them, in /// the catalogue's order, as the thread service lists them (`designations_on`): those automatic /// sizing picks from. ISO 7-1's series lists its R threads for a shaft and, for a hole, each /// size's Rc (taper) and then its Rp (parallel). fn sizes(series: ThreadItem, internal: bool) -> Rc<[String]> { kept(&SIZES, KEPT_SERIES, (series, internal), |&(series, internal)| kernel_threads::designations_on(series, side_of(internal)).into()) } /// Each size of [`sizes`] with its major diameter and pitch: the example size, and the pitch a /// custom thread's rows start at. fn numbers(series: ThreadItem, internal: bool) -> Rc<[Numbers]> { kept(&NUMBERS, KEPT_SERIES, (series, internal), |&(series, internal)| { sizes(series, internal) .iter() .filter_map(|size| { threads::read_thread(size).ok().map(|t| Numbers { designation: size.clone(), major: t.major_diameter, pitch: t.pitch }) }) .collect() }) } /// The series a tapped hole lists: the catalogue's series that have internal threads, as the /// catalogue says (`sides`), in its order, Custom among them. fn hole_series() -> Rc<[ThreadItem]> { kept(&HOLE_SERIES, 1, (), |_| catalogue().iter().filter(|c| c.sides.internal).map(|c| c.item).collect()) } /// A tapped hole's drill for the thread `designation` names, in the tolerance class `class` (none: /// no class); none where it names no hole's thread or the service gives it no drill. The drill and /// its table's unit are the service's (`default_drill`); the drills a hole accepts are those of the /// class ([`drill_range`]), or with a class the service gives no range for, those of no class. fn drill(designation: &str, class: Option<&str>) -> Option { let text = designation.trim(); if text.is_empty() { return None; } kept(&DRILLS, KEPT, (text.to_string(), class.map(str::to_string)), |(text, class)| { let t = threads::read_thread(text).ok().filter(|t| t.takes_side(true))?; let mm = t.tap_drill().ok()?; // Shown in inches for a thread of an inch standard drilled with inch drills (#10353: a // Unified size is chosen by someone working in inches), in millimetres for an ISO metric // thread and for the pipe and sealing threads, whose drills read in millimetres as G's and // Rc's do: the series' unit and group, as the catalogue gives them. A display choice, not a // thread's number. let inch = inch(t.series) && !one_start(t.series); let (low, high) = drill_range(text, class.as_deref()).or_else(|| drill_range(text, None))?; Some(Drill { mm, low, high, minor: t.minor_diameter().unwrap_or(mm), tabulated: t.drill_is_tabulated(), inch }) }) } /// The drills (mm) a tapped hole of `designation` accepts in the tolerance class `class` (none: no /// class), as the document gives them from the thread service ([`ScrewThread::drill_range`]): the /// drilled hole is the internal thread's minor diameter, so with a class whose limits give it the /// class's limits of that diameter, and with no class from the basic minor diameter to the /// standard's drill (a taper thread's from its drill to its minor diameter at the gauge plane). /// None where the service gives none, and for a class no tapped hole of the thread takes. fn drill_range(designation: &str, class: Option<&str>) -> Option<(f64, f64)> { kept(&RANGES, KEPT, (designation.trim().to_string(), class.map(str::to_string)), |(designation, class)| { thread(designation)?.drill_range(class.as_deref()).ok() }) } /// The limits of size of `designation` in `class` on a hole (`internal`) or a shaft, in mm, as the /// document gives them from the service; none where the service gives the class none. fn limits_of(designation: &str, class: &str, internal: bool) -> Option { kept(&LIMITS, KEPT, (designation.trim().to_string(), class.to_string(), internal), |(designation, class, internal)| { threads::class_limits_mm(designation, class, *internal) }) } /// The drill (mm) a tapped hole of `designation` is drilled to unless another is typed: the /// service's, as the document gives it ([`ScrewThread::tap_drill`]). None where `designation` /// names no hole's thread. pub(crate) fn default_drill(designation: &str) -> Option { drill(designation, None).map(|d| d.mm) } /// Whether a tapped hole of `designation` with no tolerance class can be drilled `mm`: one of the /// drills the thread service gives it, as the command checks it ([`ScrewThread::check_drill`]). pub(crate) fn drill_accepted(designation: &str, mm: f64) -> bool { thread(designation).is_some_and(|t| t.check_drill(mm, None).is_ok()) } /// Why `designation` is no tapped hole's thread, in the document's words: the service reads no /// thread of it, or the thread is a shaft's (`R 1/2`, whose hole is `Rc 1/2`). pub(crate) fn check_hole_thread(designation: &str) -> Result<(), String> { match thread(designation) { Some(t) => t.check_side(true), None => threads::read_thread(designation).map(|_| ()), } } // --------------------------------------------------------------------------------------------- // The Series lists // --------------------------------------------------------------------------------------------- /// The Series lists' label of a series: its message, the catalogue's name for it /// (`thread.series.`). fn series_label(series: ThreadItem) -> &'static str { match series { ThreadItem::IsoMetricCoarse => "thread.series.iso_metric_coarse", ThreadItem::IsoMetricFine => "thread.series.iso_metric_fine", ThreadItem::Mj => "thread.series.mj", ThreadItem::Unc => "thread.series.unc", ThreadItem::Unf => "thread.series.unf", ThreadItem::Unef => "thread.series.unef", ThreadItem::UnConstantPitch => "thread.series.un_constant_pitch", ThreadItem::Uns => "thread.series.uns", ThreadItem::Unj => "thread.series.unj", ThreadItem::Npt => "thread.series.npt", ThreadItem::Nptf => "thread.series.nptf", ThreadItem::Npsm => "thread.series.npsm", ThreadItem::Npsl => "thread.series.npsl", ThreadItem::Npsh => "thread.series.npsh", ThreadItem::BsppG => "thread.series.bspp_g", ThreadItem::BsptR => "thread.series.bspt_r", ThreadItem::Pg => "thread.series.pg", ThreadItem::Acme => "thread.series.acme", ThreadItem::StubAcme => "thread.series.stub_acme", ThreadItem::Trapezoidal => "thread.series.trapezoidal", ThreadItem::Square => "thread.series.square", ThreadItem::ButtressMetric => "thread.series.buttress_metric", ThreadItem::ButtressInch => "thread.series.buttress_inch", ThreadItem::WhitworthBsw => "thread.series.whitworth_bsw", ThreadItem::WhitworthBsf => "thread.series.whitworth_bsf", ThreadItem::Ba => "thread.series.ba", ThreadItem::Knuckle => "thread.series.knuckle", ThreadItem::StiInch => "thread.series.sti_inch", ThreadItem::StiMetric => "thread.series.sti_metric", ThreadItem::Custom => "thread.series.custom", } } /// The heading of a group of the Series lists: its message, the catalogue's name for it. fn group_label(group: ThreadGroup) -> &'static str { match group { ThreadGroup::Fastener => "thread.group.fastener", ThreadGroup::Pipe => "thread.group.pipe", ThreadGroup::Power => "thread.group.power", ThreadGroup::Speciality => "thread.group.speciality", ThreadGroup::Custom => "thread.group.custom", } } /// The Series row: the catalogue's series of `offered`, in its order, under its groups' names. A /// series `offered` leaves out (a designation of it typed) is listed too, where the catalogue /// has it. True when another series was chosen. Its options are published as a dropdown's /// (`dialog:thread.series:`). fn series_row(ui: &mut egui::Ui, id: &str, offered: &[ThreadItem], series: &mut ThreadItem) -> bool { let catalogue = catalogue(); let listed: Vec<&CatalogueItem> = catalogue.iter().filter(|c| offered.contains(&c.item) || c.item == *series).collect(); let labels: Vec<&str> = listed.iter().map(|c| series_label(c.item)).collect(); let mut headings = Vec::new(); let mut group = None; for (index, c) in listed.iter().enumerate() { if group != Some(c.group) { group = Some(c.group); headings.push((index, group_label(c.group))); } } let mut selected = listed.iter().position(|c| c.item == *series).unwrap_or(0); let before = selected; // A long list under its groups' headings, opening at its choice (`dropdown` opens at the top). form_row(ui, "thread.series", |ui| crate::ui_kit::dropdown_grouped(ui, id, &mut selected, &labels, &headings)); match listed.get(selected).filter(|_| selected != before) { Some(c) => { *series = c.item; true } None => false, } } /// A series whose family reads sizes off its lists by the family's rule (`M8.5x1`, as the /// catalogue says: `off_list_sizes`): a tapped hole of it can be given any diameter and pitch. fn off_list(series: ThreadItem) -> bool { entry(series).off_list_sizes } /// A series of the catalogue's pipe and sealing threads: one start, turning one way. fn one_start(series: ThreadItem) -> bool { group_of(series) == Some(ThreadGroup::Pipe) } /// A buttress series: two unequal flanks, the steep one facing one end. fn is_buttress(series: ThreadItem) -> bool { entry(series).profile == ThreadProfile::Buttress } /// A series of an inch standard: a tapped hole's class gives its limits in inches too. fn inch(series: ThreadItem) -> bool { entry(series).unit == ThreadUnit::Inch } /// Under a size of a series whose round form is never cut into the model (the knuckle thread's): /// it can only be cosmetic. Dim while it is, a warning while Modeled is ticked. fn cosmetic_only_note(ui: &mut egui::Ui, series: ThreadItem, modeled: bool) { if entry(series).profile == ThreadProfile::Round { crate::ui_kit::status_line(ui, "thread.cosmetic_only", if modeled { StatusTone::Warning } else { StatusTone::Dim }); } } // --------------------------------------------------------------------------------------------- // A tapped hole's thread // --------------------------------------------------------------------------------------------- /// Unsaved numeric inputs for a size off a series' lists (`M8.5x1`), of a series whose family reads /// such sizes ([`off_list`]). 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, /// The series the size is written in: the one the designation it was made from names, else /// the default series. series: ThreadItem, diameter: String, pitch: String, pub(crate) error: Option, } impl HoleThreadDraft { fn new(source: &str) -> Self { let read = thread(source); let series = read.as_ref().map_or_else(threads::default_series, |t| t.series); let (diameter, pitch) = match read.filter(|t| off_list(t.series)) { Some(t) => (format!("{} mm", t.major_diameter), format!("{} mm", t.pitch)), None => (String::new(), String::new()), }; Self { source: source.into(), series, diameter, pitch, error: None } } /// The size of the draft's diameter and pitch, as the thread service writes a size of its /// series by its numbers (`write_size`: the listed size where one matches, `M8` and not /// M8x1.25, else the family's spelling, `M8.5x1`), into `authored`; or why there is none. /// Authored designation text is never rewritten just by displaying a dialog. 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 refused = "use a positive nominal diameter and a pitch smaller than it"; let text = kernel_threads::write_size(self.series, d, p).map_err(|_| refused)?; thread(&text).ok_or(refused)?; Ok(text) }; match candidate() { Ok(text) => { *authored = text; self.source = authored.clone(); self.error = None; } Err(error) => self.error = Some(error), } } } /// The size a thread's designation comes to now: a text parameter or expression evaluated with the /// design's parameters; a designation the thread service reads stays as written. pub(crate) fn evaluated_designation(doc: &Document, source: &str) -> String { doc.eval_thread_designation(source, &doc.param_values().0) } /// The tapped thread a hole's designation comes to now ([`evaluated_designation`]), as the thread /// service reads it for a hole, or the refusal the document gives it. pub(crate) fn tapped_size(doc: &Document, source: &str) -> Result { let name = evaluated_designation(doc, source); check_hole_thread(&name)?; threads::read_thread(&name) } /// A tapped hole's thread rows in the Hole dialog: the series (those with internal threads, Custom /// among them), the size, the diameter and pitch of a size off the series' lists, the designation, /// the class and the drill: the service's for the size, or one typed among those the service /// accepts in the hole's class. A pipe or sealing thread's size names no diameter, so its diameter /// and pitch are shown. Custom in the Size list remains a dialog mode even when its current values /// match a catalogue size. The size lists are long (hundreds of UN sizes), so they open at the /// size chosen. Series Custom lists no sizes: the Thread dialog's Profile, Diameter, Pitch and /// Angle rows make its designation ([`custom_rows`]), starting at the diameter of the size chosen /// before. pub(crate) fn hole_rows(ui: &mut egui::Ui, doc: &Document, opts: &mut HoleOpts) -> bool { let before = opts.thread.clone(); let designation_id = ui.make_persistent_id("hole_thread_designation"); // The designation names its series (a text parameter or expression by the size it comes to // now); while one is being typed, the series chosen last stays. if let Some(t) = thread(&evaluated_designation(doc, &opts.thread)) { opts.thread_series = t.series; } let mut series = opts.thread_series; if series_row(ui, "hole_thread_series", &hole_series(), &mut series) { opts.thread_series = series; opts.custom_thread = None; opts.custom_rows = None; if threads::is_custom(series) { // A custom thread is made from its rows, which start at the size chosen before. let mut rows = CustomRows::for_face(thread(&evaluated_designation(doc, &opts.thread)).map(|t| t.major_diameter)); opts.thread = rows.compose(doc).unwrap_or_default(); opts.custom_rows = Some(Box::new(rows)); } else if let Some(first) = sizes(series, true).first() { opts.thread.clone_from(first); } } let series = opts.thread_series; let custom = threads::is_custom(series); let mut enter = false; if custom { // The Custom series lists no sizes: its own rows make its designation. opts.custom_thread = None; let mut no_suggestion = None; enter |= custom_rows(ui, doc, &mut opts.thread, &mut no_suggestion, &mut opts.custom_rows, None); } else { opts.custom_rows = None; enter |= size_rows(ui, doc, series, opts); } let hint = if custom { tr!("thread.custom_hint") } else { "M5, M5x0.5, 1/4-20 UNC" }; let response = form_row(ui, "Designation", |ui| crate::ui_kit::cell_editor(ui, designation_id, &mut opts.thread, hint, false)); if response.changed() { if evaluated_designation(doc, &opts.thread) != opts.thread { // A text parameter or expression is no custom size being typed. opts.custom_thread = None; } else if opts.custom_thread.is_some() { opts.custom_thread = Some(HoleThreadDraft::new(&opts.thread)); } } // The thread the designation names now (a text parameter or expression by the size it comes // to), as a hole's; none while a row of a custom size or of the Custom series is wrong. let evaluated = evaluated_designation(doc, &opts.thread); let hole = thread(&evaluated).filter(|t| t.takes_side(true) && hole_thread_error(opts).is_none()); cosmetic_only_note(ui, opts.thread_series, opts.modeled); // The class shown: one the designation writes after the size (`1/4-20 UNC-2B`), which is the // thread's, else the Class row's. let mut class = opts.thread_class.clone(); if let Some(t) = &hole { // The class goes when the size no longer takes it (another series' size, a preset's // size), and stays while a designation is being typed. let offered = t.classes_on(true); if t.class.is_some() || opts.thread_class.as_deref().is_some_and(|class| !offered.iter().any(|c| c == class)) { opts.thread_class = None; } class = t.class.clone().or_else(|| opts.thread_class.clone()); if !offered.is_empty() { class_choice(ui, "hole_thread_class", &offered, &mut class, t.class.is_some()); if t.class.is_none() { opts.thread_class.clone_from(&class); } } } // The drill: the service's for the size, or one the user types among those the class accepts. // A new size goes back to its own drill. if opts.thread != before { opts.drill = None; } let mut drill_enter = false; let drilled = hole.as_ref().and_then(|_| drill(&evaluated, class.as_deref())); let default = drilled.map(|d| drill_label(d.mm, d.inch)); form_row(ui, "Tap drill diameter", |ui| match (&hole, drilled.zip(default)) { (Some(_), Some((d, default))) => { let mut text = opts.drill.clone().unwrap_or_else(|| default.clone()); let (submitted, changed) = crate::ui_kit::text_field_tip(ui, &mut text, &default, &drill_tip(&d)); if changed { opts.drill = (text.trim() != default && !text.trim().is_empty()).then_some(text); } drill_enter = submitted; } (Some(_), None) => { ui.label(tr!("hole.no_drill")); } (None, _) => { ui.label(tr!("thread.select_size")); } }); // The hole the class allows, one line under the drill: the drills the class accepts, its limits // of the internal thread's minor diameter. if let Some(line) = hole.as_ref().zip(class.as_deref()).and_then(|(t, class)| class_band(t, class)) { crate::ui_kit::status_line(ui, &line, StatusTone::Dim); } enter || drill_enter || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) } /// A tapped hole's Thread data section, under the last of its thread's input rows (the Hand, /// Modeled and End rows the Hole dialog draws after [`hole_rows`]). pub(crate) fn hole_data_section(ui: &mut egui::Ui, doc: &Document, opts: &HoleOpts) { data_section(ui, doc, &evaluated_designation(doc, &opts.thread), true); } /// A tapped hole's Size row for a series that lists sizes ([`sizes`] in a hole): the series' sizes /// and, for a series that reads sizes off its lists ([`off_list`]), Custom, whose Nominal diameter /// and Pitch rows make a size of any diameter and pitch ([`HoleThreadDraft`]); and for a pipe or /// sealing thread, whose size names no diameter, its diameter and pitch. Returns whether Enter was /// pressed in a row. fn size_rows(ui: &mut egui::Ui, doc: &Document, series: ThreadItem, opts: &mut HoleOpts) -> bool { let listed = sizes(series, true); let custom_sizes = off_list(series); if !custom_sizes { opts.custom_thread = None; } // A text parameter or expression shows the size it comes to now, and is no custom size. let evaluated = evaluated_designation(doc, &opts.thread); let expression = evaluated != opts.thread; if expression { opts.custom_thread = None; } let read = thread(&evaluated).map(|t| t.designation); let at = listed.iter().position(|s| s == evaluated.trim() || Some(s.as_str()) == read.as_deref()); if custom_sizes && !expression && (opts.custom_thread.as_ref().is_some_and(|draft| draft.source != opts.thread) || (opts.custom_thread.is_none() && at.is_none())) { opts.custom_thread = Some(HoleThreadDraft::new(&opts.thread)); } form_row(ui, "Size", |ui| { let typed = evaluated.trim().to_string(); let custom = custom_sizes.then_some(opts.custom_thread.is_some()); let (labels, mut selected, first) = size_labels(&listed, &typed, read.as_deref(), custom); let shown = selected; crate::ui_kit::dropdown_grouped(ui, "hole_thread_size", &mut selected, &labels, &[]); if selected != shown { match selected.checked_sub(first).and_then(|i| listed.get(i)) { Some(size) => { opts.thread.clone_from(size); opts.custom_thread = None; } None if custom_sizes => opts.custom_thread = Some(HoleThreadDraft::new(&opts.thread)), None => {} } } }); if let Some(t) = thread(&evaluated_designation(doc, &opts.thread)).filter(|t| t.group == ThreadGroup::Pipe && hole_thread_error(opts).is_none()) { form_row(ui, "Thread diameter", |ui| { ui.label(match t.included_angle { Some(angle) => format!("{:.3} mm, {angle}°", t.major_diameter), None => format!("{:.3} mm", t.major_diameter), }); }); form_row(ui, "Pitch", |ui| { ui.label(match t.dimensions_mm.tpi { Some(tpi) => format!("{:.4} mm ({tpi} TPI)", t.pitch), None => format!("{:.4} mm", t.pitch), }); }); } let mut enter = false; if let Some(draft) = &mut opts.custom_thread { 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, &mut opts.thread); } enter |= diameter_enter || pitch_enter; } enter } /// Why a tapped hole's thread rows make no designation to drill: a row of a size off the series' /// lists ([`HoleThreadDraft`]) or of the Custom series ([`CustomRows`]) that is no length or angle, /// or makes no thread. None for rows that make one. pub(crate) fn hole_thread_error(opts: &HoleOpts) -> Option<&str> { let draft = opts.custom_thread.as_ref().and_then(|draft| draft.error.as_deref()); let rows = || opts.custom_rows.as_ref().filter(|_| threads::is_custom(opts.thread_series)).and_then(|rows| rows.error.as_deref()); draft.or_else(rows) } /// The command's `thread_class` for a tapped hole of `designation` with the Class row's `class`. /// `designation` may be a text parameter or expression, read by the size it comes to now, as the /// Class row is. A size with a Class row (the service gives it classes in a hole) always gives it, /// an empty one for none, so an edit that takes the class off takes it off (an edit that gives /// none keeps the hole's class, #16336). A size without one gives none, so an edit keeps the class /// it was saved with. pub(crate) fn hole_class_param(doc: &Document, designation: &str, class: Option<&str>) -> Option { let t = thread(&evaluated_designation(doc, designation))?; (!t.classes_on(true).is_empty()).then(|| json!(class.unwrap_or_default())) } /// The line under a tapped hole's drill for its class: the drills the class accepts /// ([`drill_range`]), its limits of the internal thread's minor diameter, in millimetres, and in /// inches too for a thread of an inch standard (`Class 2B: hole 4.978 to 5.258 mm (0.196 to 0.207 /// in)`). None where the service gives the class no such range. fn class_band(t: &ScrewThread, class: &str) -> Option { let (low, high) = drill_range(&t.designation, Some(class))?; let mm = |v: f64| format!("{v:.3}"); let (low_mm, high_mm) = (mm(low), mm(high)); if !inch(t.series) { return Some(solidcraft_ui_text::format("hole.class_band", &[("class", class), ("low", &low_mm), ("high", &high_mm)])); } // Three places of an inch, as the standard gives a hole's minor diameter, and the fourth only // where it is not a nought (the drill field's own rule). let inches = |v: f64| crate::prefs::length_number(v, "in", 3); let (low_in, high_in) = (inches(low), inches(high)); let args = [("class", class), ("low", low_mm.as_str()), ("high", high_mm.as_str()), ("low_in", low_in.as_str()), ("high_in", high_in.as_str())]; Some(solidcraft_ui_text::format("hole.class_band_inch", &args)) } /// A tapped hole's drill as the Tap drill field shows it: in inches for a thread drilled with inch /// drills, its drill coming from a table of inch drills (`default_drill`'s unit: a Unified size is /// chosen by someone working in inches whose drill tables are inch drills, #10353), else in /// millimetres (ISO metric, and the pipe threads G, Rp, Rc and NPT). The field's tooltip gives the /// drill in millimetres: both side by side do not fit the form's value column (`0.4219 in /// (10.715625 mm)` was cut off). Left unchanged, the field keeps the service's exact drill. fn drill_label(mm: f64, in_inches: bool) -> String { if in_inches { crate::prefs::format_length(mm, "in", 3) } else { format!("{} mm", trimmed(mm)) } } /// The Tap drill field's default for `designation` ([`drill_label`]); none where it names no /// hole's thread with a drill. #[cfg(test)] fn tap_drill_label(designation: &str) -> Option { drill(designation, None).map(|d| drill_label(d.mm, d.inch)) } /// A length in mm to four places, without trailing zeros (`6.8`, `13.9`, `5.1054`). fn trimmed(mm: f64) -> String { let text = format!("{mm:.4}"); text.trim_end_matches('0').trim_end_matches('.').to_string() } /// A custom thread's number (a length in mm, a V's angle in degrees) to the six places the thread /// service holds it to, without trailing zeros (`1.500001`, `47.5`): what the Custom series' rows /// hold when a designation fills them ([`CustomRows::of`]), so that a row left as it is makes the /// same number again. Numbers that are only shown keep four places ([`trimmed`]). fn six_places(value: f64) -> String { let text = format!("{value:.6}"); text.trim_end_matches('0').trim_end_matches('.').to_string() } /// The Tap drill field's tooltip: the drill, where it comes from (a drill table's, or the internal /// thread's minor diameter where no table lists the size), and the drills a hole accepts. fn drill_tip(d: &Drill) -> String { let mm = |v: f64| format!("{v:.3}"); let args = [("drill", mm(d.mm)), ("minor", mm(d.minor)), ("low", mm(d.low)), ("high", mm(d.high))]; let args: Vec<(&str, &str)> = args.iter().map(|(k, v)| (*k, v.as_str())).collect(); solidcraft_ui_text::format(if d.tabulated { "thread.drill_range" } else { "hole.drill_range_minor" }, &args) } /// A Class row over the classes `offered`, or none. A class chosen or saved that is not among /// them (the other side's, on a Thread) stays offered as it is: the command says why it is not /// this face's. A class the designation writes after the size (`1/4-20 UNC-2A`) is shown and not /// chosen (`written`): the designation gives it. fn class_choice(ui: &mut egui::Ui, id: &str, offered: &[String], class: &mut Option, written: bool) { let other = class.clone().filter(|c| !offered.contains(c)); let mut labels: Vec<&str> = vec!["None"]; labels.extend(offered.iter().map(String::as_str)); labels.extend(other.as_deref()); let mut selected = class.as_deref().and_then(|c| labels.iter().skip(1).position(|l| *l == c)).map_or(0, |i| i + 1); let before = selected; form_row(ui, "thread.class", |ui| { ui.add_enabled_ui(!written, |ui| combo(ui, id, &labels, &mut selected)); }); if selected != before { *class = labels.get(selected).filter(|_| selected > 0).map(|c| (*c).to_string()); } } // --------------------------------------------------------------------------------------------- // The Thread dialog // --------------------------------------------------------------------------------------------- const HANDS: &[(&str, ThreadHand)] = &[("Right", ThreadHand::Right), ("Left", ThreadHand::Left), ("Both", ThreadHand::Both)]; /// A tapped hole's and a pipe thread's hands: one groove, so never both. const HOLE_HANDS: &[(&str, ThreadHand)] = &[("Right", ThreadHand::Right), ("Left", ThreadHand::Left)]; const STARTS: &[(&str, u32)] = &[("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5), ("6", 6), ("7", 7), ("8", 8)]; const FULL: usize = 0; const LENGTH: usize = 1; const UP_TO_EXTENT: usize = 2; const EXTENTS: &[(&str, &str)] = &[("Full", "full"), ("Length", "length"), ("Up to", "up_to")]; /// The thread's chamfered ends, the command's `tip`: none, the free end it starts from, or every /// free end it reaches (a shaft's tip, ISO 4753; a hole's countersunk entry). const CHAMFER_AT: &[(&str, ThreadTip)] = &[("None", ThreadTip::None), ("Start", ThreadTip::Start), ("Both", ThreadTip::Both)]; /// The chamfered ends of a thread with an offset: its start lies inside the face, which no /// chamfer reaches, so none, or every free end it reaches. const CHAMFER_AT_OFFSET: &[(&str, ThreadTip)] = &[("None", ThreadTip::None), ("Both", ThreadTip::Both)]; /// The thread's inner end: a square stop (the groove ends in its own profile) or a fade /// (ISO 3508's runout). const ENDS_AT: &[&str] = &["thread.end_square", "ui.fade"]; const FLANKS: &[(&str, SteepFlank)] = &[("End", SteepFlank::End), ("Start", SteepFlank::Start)]; /// The pick of the end the thread is measured from (`from`). const START_END: &str = "Start side (optional)"; /// The face or plane an Up To extent runs to (`up_to`). const UP_TO: &str = "Up to"; const UP_TO_ACCEPT: Accept = FACES | PLANES; /// The selection inputs of a new thread dialog. pub(crate) fn inputs() -> Vec { vec![SelInput::new("Cylindrical face", FACES, false)] } /// The inner end: square or a fade, the fade's typed length (empty: ISO 3508's runout, the /// standard 2.5 P unless the thread was saved with the short 1.25 P). #[derive(Clone, Debug, Default, PartialEq)] pub struct Ease { pub fade: bool, pub length: String, pub short: bool, } impl Ease { pub(crate) fn of(r: &Option) -> Ease { match r { None => Ease::default(), Some(ThreadRunout::Standard) => Ease { fade: true, ..Ease::default() }, Some(ThreadRunout::Short) => Ease { fade: true, short: true, ..Ease::default() }, Some(ThreadRunout::Length { length }) => Ease { fade: true, length: expr(length), short: false }, } } /// The command's `ease_out`, none for a square end. pub(crate) fn param(&self) -> Option { let typed = self.length.trim(); self.fade.then(|| match (typed.is_empty(), self.short) { (false, _) => json!(typed), (true, true) => json!("short"), (true, false) => json!("standard"), }) } } fn expr(e: &Expr) -> String { e.to_string() } /// The thread options beyond the size and length. #[derive(Clone, Debug, PartialEq)] pub struct Options { /// The series the sizes are listed from and the face is sized from (the command's `series`). pub series: ThreadItem, /// The tolerance class (the command's `class`): one the service gives the size on the face's /// side; none for none. pub class: Option, /// The thread was saved with a class: none chosen now takes it off (an empty `class`). pub saved_class: bool, pub hand: ThreadHand, pub starts: u32, /// An index into the extents (full, length, up to). pub extent: usize, /// How far in from the end it starts at the thread starts, as typed (empty: at that end). pub offset: String, pub ease_out: Ease, /// A modelled internal thread runs down to a blind hole's bottom (#22616). pub to_bottom: bool, pub tip: ThreadTip, pub chamfer_angle: String, pub chamfer_depth: String, pub steep_flank: SteepFlank, /// The Custom series' rows, which make a custom thread's designation ([`CustomRows`]); none /// for another series. Boxed as the Hole dialog's are, so that one `custom_rows` edits both. pub custom: Option>, } impl Default for Options { fn default() -> Options { Options { series: threads::default_series(), class: None, saved_class: false, hand: ThreadHand::default(), starts: 1, extent: FULL, offset: String::new(), ease_out: Ease::default(), to_bottom: false, tip: ThreadTip::default(), chamfer_angle: String::new(), chamfer_depth: String::new(), steep_flank: SteepFlank::default(), custom: None, } } } impl Options { /// Does the thread start at one end of the face (a length or an Up To extent, an offset, a /// runout or a tip)? Then the end to start from can be picked. pub fn starts_at_an_end(&self, doc: &Document) -> bool { self.extent != FULL || self.has_offset(doc) || self.ease_out.fade || self.tip != ThreadTip::None } /// Is an offset given? Then the thread starts inside the face, not at its end. A blank one, or /// one that comes to 0, is none, as the command takes it; one that can't be worked out (or is /// negative) counts as given, so the command says what is wrong with it. pub fn has_offset(&self, doc: &Document) -> bool { let typed = self.offset.trim(); !typed.is_empty() && !doc.eval(typed, solidcraft_engine::doc::expr::Kind::Length).is_ok_and(|v| v == 0.0) } /// Whether the thread's teeth have a steep flank: a buttress series' (its catalogue entry's /// profile), or a custom thread's of a buttress profile. fn buttress(&self) -> bool { is_buttress(self.series) || (threads::is_custom(self.series) && self.custom.as_deref().is_some_and(CustomRows::buttress)) } /// Why the Custom series' rows make no designation, a row being no length or angle: OK is /// refused with it. None for another series, and for rows that make one. pub(crate) fn custom_error(&self) -> Option<&str> { self.custom.as_ref().filter(|_| threads::is_custom(self.series)).and_then(|rows| rows.error.as_deref()) } } /// The Custom series' Profile choices, each with its message: the profiles the thread service /// makes a custom thread of (`Custom x

`, a V's `Custom x

x`), a V at /// an angle last, its included angle the Angle row's. const CUSTOM_PROFILES: &[(&str, CustomProfile)] = &[ ("thread.profile.v60", CustomProfile::V(60.0)), ("thread.profile.v55", CustomProfile::V(55.0)), ("thread.profile.trapezoidal", CustomProfile::Trapezoidal), ("thread.profile.acme", CustomProfile::Acme), ("thread.profile.buttress_3_30", CustomProfile::MetricButtress), ("thread.profile.buttress_7_45", CustomProfile::InchButtress), ("thread.profile.square", CustomProfile::Square), ("thread.profile.v_angle", CustomProfile::V(60.0)), ]; /// The Profile choice of a V at an angle, [`CUSTOM_PROFILES`]' last. const V_AT_AN_ANGLE: usize = 7; /// The included angle the Angle row of a V at an angle starts at. const V_ANGLE: &str = "60 deg"; /// A custom thread's rows (the Custom series, in the Thread dialog and a tapped hole's): its /// profile, diameter and pitch, and a V at an angle's included angle, as typed. They make its /// designation (`Custom 10x1.5x60`), which the Designation row shows and the command reads; a /// custom designation typed there, or saved, fills them, from the profile, diameter and pitch the /// thread service reads in it. #[derive(Clone, Debug, PartialEq)] pub struct CustomRows { /// An index into [`CUSTOM_PROFILES`]. pub profile: usize, /// The major diameter, a length expression (`10 mm`). pub diameter: String, /// The pitch, a length expression (`1.5 mm`). pub pitch: String, /// A V at an angle's included angle, an angle expression (`60 deg`). pub angle: String, /// The designation the rows made last, or were filled from: another one typed fills them /// again. source: String, /// Why a row is no length or angle, or the thread service writes no designation of the rows' /// numbers: the rows make no designation, and OK is refused with it. pub(crate) error: Option, /// The thread service's refusal of the designation the rows make (an angle off 20 to 90°, a /// pitch too coarse for the diameter), which the command gives too. pub(crate) refusal: Option, } impl CustomRows { /// The rows the Custom series starts with on a face `face` mm across (none picked: no /// diameter): a 60° V of that diameter, at the coarse pitch of the ISO metric size nearest it /// (ISO 261's coarse series, as the catalogue lists it), else 1 mm. fn for_face(face: Option) -> CustomRows { let face = face.filter(|d| d.is_finite() && *d > 0.0); let coarse = face.and_then(|d| { let listed = numbers(ThreadItem::IsoMetricCoarse, false); listed.iter().min_by(|a, b| (a.major - d).abs().total_cmp(&(b.major - d).abs())).map(|n| n.pitch) }); CustomRows { profile: 0, diameter: face.map(|d| format!("{} mm", trimmed(d))).unwrap_or_default(), pitch: format!("{} mm", trimmed(coarse.unwrap_or(1.0))), angle: V_ANGLE.into(), source: String::new(), error: None, refusal: None, } } /// The rows of a custom designation the thread service reads (`Custom Tr20x2.5`), its profile /// and numbers as the service reads them ([`threads::custom_parts`]: the thread's custom /// profile, a V at the angle read), each number to the service's six places ([`six_places`]), /// so that changing one row keeps the others' numbers (`Custom Tr20x1.500001` keeps its pitch /// through a new diameter); none for any other text. A 60° or a 55° V is its own choice, a V /// of another angle a V at an angle. fn of(designation: &str) -> Option { let (profile, diameter, pitch) = threads::custom_parts(designation)?; let listed = |choice: &CustomProfile| match (*choice, profile) { (CustomProfile::V(a), CustomProfile::V(b)) => (a - b).abs() < 1e-9, (a, b) => a == b, }; let index = CUSTOM_PROFILES.iter().take(V_AT_AN_ANGLE).position(|(_, choice)| listed(choice)).unwrap_or(V_AT_AN_ANGLE); let angle = match profile { CustomProfile::V(a) if index == V_AT_AN_ANGLE => format!("{} deg", six_places(a)), _ => V_ANGLE.into(), }; Some(CustomRows { profile: index, diameter: format!("{} mm", six_places(diameter)), pitch: format!("{} mm", six_places(pitch)), angle, source: designation.to_string(), error: None, refusal: None, }) } /// Whether the thread the rows made last has a buttress profile, whose teeth have a steep /// flank: the kind of profile the thread service reads in its designation. fn buttress(&self) -> bool { profile_of(&self.source) == Some(ThreadProfile::Buttress) } /// The designation the rows make (`Custom 10x1.5x60`), as the thread service writes it /// ([`threads::custom_designation`]) and, where it reads it, as it spells it, else as made, with /// the service's refusal noted ([`CustomRows::refusal`]); none for a row that is no length or /// angle, or numbers the service writes no designation of, which is noted /// ([`CustomRows::error`]). A bare number is in the design's units, as a feature's length is. fn compose(&mut self, doc: &Document) -> Option { match self.made(doc) { Err(why) => { self.error = Some(why); self.refusal = None; None } Ok(made) => { let read = thread(&made); self.error = None; self.refusal = if read.is_some() { None } else { threads::read_thread(&made).err() }; let made = read.map_or(made, |t| t.designation); self.source.clone_from(&made); Some(made) } } } /// The designation of the rows' numbers, as the thread service writes it, or why a row is no /// length or angle, or why the service writes none of them. fn made(&self, doc: &Document) -> Result { use solidcraft_engine::doc::expr::Kind as Quantity; let value = |row: &str, text: &str, kind: Quantity| { doc.eval(&doc.with_design_unit(text.trim(), kind), kind) .map_err(|e| solidcraft_ui_text::format("thread.custom_row_error", &[("row", tr_by_id(row)), ("why", &e.to_string())])) }; let chosen = CUSTOM_PROFILES.get(self.profile).map_or(CustomProfile::V(60.0), |(_, profile)| *profile); let profile = if self.profile == V_AT_AN_ANGLE { CustomProfile::V(value("thread.angle", &self.angle, Quantity::Angle)?.to_degrees()) } else { chosen }; let diameter = value("thread.diameter", &self.diameter, Quantity::Length)?; let pitch = value("thread.pitch", &self.pitch, Quantity::Length)?; threads::custom_designation(profile, diameter, pitch) } } /// A typical size of the series (a hole's, `internal`, as a hole lists them), for the Designation /// field's hint: the one nearest 20 mm. fn example(series: ThreadItem, internal: bool) -> String { numbers(series, internal) .iter() .min_by(|a, b| (a.major - 20.0).abs().total_cmp(&(b.major - 20.0).abs())) .map(|n| n.designation.clone()) .unwrap_or_default() } /// `size` with the class and hand `typed` writes after its own size, where the service reads them /// on `size` (`M8-6g` and `M3` make `M3-6g`), spelled as the thread service spells a designation /// (`spell`): a class typed stays through a new size that takes it. fn with_written(typed: &str, size: &str) -> String { let Some(old) = thread(typed) else { return size.to_string() }; let class = old.class.as_deref().filter(|class| thread(size).is_some_and(|new| new.classes.iter().any(|c| c.name == *class))); kernel_threads::spell(size, class, old.left_hand).ok().filter(|kept| thread(kept).is_some()).unwrap_or_else(|| size.to_string()) } /// A new series keeps a manual size's diameter where the series lists a size of it that the face's /// side takes: the one of the same pitch where it lists that too (`size_of`), else the first at /// that diameter (`sizes_at`), with the class and hand written after it ([`with_written`]); any /// other size goes back to the size that fits the face. True when the size went back to automatic. fn change_series(designation: &mut String, suggested: &mut Option, to: ThreadItem, internal: Option) -> bool { let automatic = designation.trim().is_empty() || suggested.as_deref() == Some(designation.as_str()); *suggested = None; let keep = (!automatic).then(|| thread(designation)).flatten().and_then(|now| { let on_side = sizes(to, internal == Some(true)); let at_major = kernel_threads::sizes_at(to, now.major_diameter); kernel_threads::size_of(to, now.major_diameter, now.pitch).into_iter().chain(at_major).find(|size| on_side.contains(size)) }); match keep { Some(size) => { *designation = with_written(designation.as_str(), &size); false } None => { designation.clear(); true } } } /// The hole dialog's Hand row for a tapped hole, the same choice the thread dialog offers. pub(crate) fn hole_hand_row(ui: &mut egui::Ui, hand: &mut ThreadHand) { pick(ui, "Hand", "hole_hand", hand, HOLE_HANDS); } /// A choice row over typed values. fn pick(ui: &mut egui::Ui, label: &str, id: &str, value: &mut T, choices: &[(&str, T)]) { let labels: Vec<&str> = choices.iter().map(|c| c.0).collect(); let mut index = choices.iter().position(|c| c.1 == *value).unwrap_or(0); choice_row(ui, label, id, &mut index, &labels); if let Some(c) = choices.get(index) { *value = c.1; } } /// The thread's rows. Returns (Enter pressed, automatic sizing requested). The picks are the /// caller's: [`sync_inputs`] adds or removes them by the options. `side` is the face picked /// ([`Side`]): the Class row offers its side's classes, a hole lists the sizes a hole takes, and /// the Custom series' rows start at its diameter; `doc` reads their lengths ([`custom_rows`]) and /// the offset's ([`Options::has_offset`]). pub(crate) fn rows( ui: &mut egui::Ui, doc: &Document, designation: &mut String, suggested: &mut Option, length: &mut String, o: &mut Options, modeled: &mut bool, side: &Side, ) -> (bool, bool) { let internal = side.internal; let mut enter = false; let mut reset = false; // A designation names its series: a size of another series typed, or one saved, shows it (a // text parameter or expression by the size it comes to now). if let Some(t) = thread(&evaluated_designation(doc, designation)) && t.series != o.series { o.series = t.series; } let all: Vec = catalogue().iter().map(|c| c.item).collect(); let mut series = o.series; if series_row(ui, "thread_series", &all, &mut series) { if threads::is_custom(series) { // A custom thread is made from its rows, which start from the face. designation.clear(); *suggested = None; o.custom = None; } else { // Another series' size takes the place of the size the designation comes to now. let mut evaluated = evaluated_designation(doc, designation); reset |= change_series(&mut evaluated, suggested, series, internal); *designation = evaluated; } o.series = series; // A class is its series' standard's: another series starts with none. o.class = None; } let s = o.series; // The Custom series lists no sizes and gives no classes: its own rows make its designation. let custom = threads::is_custom(s); if custom { o.class = None; } else { o.custom = None; } let before = designation.trim().is_empty() || suggested.as_deref() == Some(designation.as_str()); let mut automatic = before; crate::ui_kit::section(ui, "thread_options", "Options", true, |ui| { crate::ui_kit::checkbox_grid(ui, &mut [("Modeled", modeled)], 2); if !custom { ui.add_enabled_ui(!designation.trim().is_empty(), |ui| crate::ui_kit::checkbox_grid(ui, &mut [("Automatic size", &mut automatic)], 2)); } }); reset |= automatic && !before; if automatic != before { *suggested = None; if automatic { designation.clear(); } } let hint = if custom { enter |= custom_rows(ui, doc, designation, suggested, &mut o.custom, side.diameter); tr!("thread.custom_hint").to_string() } else { // The size list shows the size the designation comes to now; a size chosen from it takes // the place of a text parameter or expression. let mut evaluated = evaluated_designation(doc, designation); let before = evaluated.clone(); size_row(ui, s, internal, &mut evaluated, suggested); if evaluated != before { *designation = evaluated; } tr!("thread.fits_the_face", example = &example(s, internal == Some(true))) }; let (submitted, changed) = text_row(ui, "Designation", designation, &hint); enter |= submitted; if let Some(at) = crate::scenario::handle_at("dialog:Designation") { crate::scenario::publish_handle("dialog:thread_size", at); } if changed { *suggested = None; } cosmetic_only_note(ui, s, *modeled); if let Some(internal) = internal.filter(|_| !custom) { let had_class = o.class.is_some(); class_rows(ui, &evaluated_designation(doc, designation), &mut o.class, internal); // A class is a class of the size shown: choosing one keeps that size, no longer the face's // automatic one (the command takes a class only with its size). if o.class.is_some() && !had_class && suggested.as_deref() == Some(designation.as_str()) { *suggested = None; } } if one_start(s) { // A pipe or sealing thread has one start and turns one way. o.starts = 1; if o.hand == ThreadHand::Both { o.hand = ThreadHand::Right; } pick(ui, "Hand", "thread_hand", &mut o.hand, HOLE_HANDS); } else { pick(ui, "Hand", "thread_hand", &mut o.hand, HANDS); pick(ui, "thread.interleaved_grooves", "thread_starts", &mut o.starts, STARTS); } if o.buttress() { pick(ui, "Steep Flank", "thread_flank", &mut o.steep_flank, FLANKS); } let extents: Vec<&str> = EXTENTS.iter().map(|x| x.0).collect(); let extent = o.extent; choice_row(ui, "Extent", "thread_extent", &mut o.extent, &extents); if o.extent == LENGTH { if extent != LENGTH && length.trim().is_empty() { *length = "10 mm".into(); } enter |= expr_row(ui, "Length", length); } // How far in from the end it starts at the thread starts: a plain stretch at that end. enter |= crate::ui_kit::expr_row_positive(ui, "Offset", &mut o.offset); crate::ui_kit::section(ui, "thread_ends", "Ends", true, |ui| { // The chamfered ends, the command's `tip`: none, the free end the thread starts from, or // every free end it reaches (a stud's two ends); a shaft's tip (ISO 4753), a hole's // countersunk entry, on a cosmetic or a modelled thread. An offset start lies inside the // face, which no chamfer reaches: with an offset the row offers None and Both, and a // Start chosen shows as the `tip: both` it is sent as (`sent_tip`), which chamfers the // free far end the thread reaches. The choice kept is the user's own, so clearing the // offset brings back what they chose. let choices = if o.has_offset(doc) { CHAMFER_AT_OFFSET } else { CHAMFER_AT }; let labels: Vec<&str> = choices.iter().map(|c| c.0).collect(); let shown = sent_tip(o, doc); let mut chamfer = choices.iter().position(|c| c.1 == shown).unwrap_or(0); let before = chamfer; choice_row(ui, "Chamfer", "thread_chamfer", &mut chamfer, &labels); if chamfer != before && let Some(c) = choices.get(chamfer) { o.tip = c.1; } if o.tip != ThreadTip::None { enter |= hint_row(ui, "Chamfer Angle", &mut o.chamfer_angle, tr!("ui.iso_4753")); // ISO 4753 gives an ISO metric shaft's depth (the catalogue's `tip`); every other // thread's default goes as far past its root, which the thread works out. let iso_4753 = !internal.unwrap_or(false) && entry(s).tip == Some(TipStandard::Iso4753); enter |= hint_row(ui, "Chamfer Depth", &mut o.chamfer_depth, if iso_4753 { tr!("ui.iso_4753") } else { "" }); } enter |= end_rows(ui, &mut o.ease_out); // A square end of a modelled thread can run down to a blind hole's bottom (#22616). if *modeled && !o.ease_out.fade { crate::ui_kit::checkbox_grid(ui, &mut [("Run to the hole's bottom", &mut o.to_bottom)], 2); } }); data_section(ui, doc, &evaluated_designation(doc, designation), internal.unwrap_or(false)); (enter, reset) } /// The thread's data under its rows, read-only, as the thread service gives it for the /// designation: its pitch and threads per inch (the standard's count, else 25.4 mm over the /// pitch), its lead where it has more than one start, its major, pitch and minor diameters on the /// face's side (a hole's minor diameter is the internal thread's, a shaft's its root), its depth, /// the included angle of its flanks, a taper thread's taper and effective length (L2), and a /// hole's tap drill. Nothing shows before a designation names a thread. Its rows have messages of /// their own (`thread.data.*`), so that none is taken for an input row of the same words above it /// (a class's limits, a custom thread's Pitch and Angle). It comes after every input row of the /// thread, in the Hole dialog too ([`hole_data_section`]). fn data_section(ui: &mut egui::Ui, doc: &Document, designation: &str, hole: bool) { let Some(t) = thread(designation) else { return }; let d = t.dimensions_mm; let length = |mm: f64| crate::length_input::shown(doc, mm); crate::ui_kit::section(ui, "thread_data", "thread.data", true, |ui| { crate::ui_kit::value_row(ui, "thread.data.pitch", &length(t.pitch)); crate::ui_kit::value_row(ui, "thread.data.tpi", &trimmed(d.tpi.unwrap_or(25.4 / t.pitch))); if t.starts > 1 { crate::ui_kit::value_row(ui, "thread.data.lead", &length(t.pitch * f64::from(t.starts))); } let major = if hole { d.major_internal.unwrap_or(d.major) } else { d.major }; crate::ui_kit::value_row(ui, "thread.data.major", &length(major)); if let Some(pitch_diameter) = d.pitch_diameter { crate::ui_kit::value_row(ui, "thread.data.pitch_diameter", &length(pitch_diameter)); } if let Some(minor) = if hole { d.minor_internal } else { d.root_external } { crate::ui_kit::value_row(ui, "thread.data.minor", &length(minor)); } if let Some(depth) = d.thread_height { crate::ui_kit::value_row(ui, "thread.data.profile_depth", &length(depth)); } if let Some(angle) = t.included_angle { crate::ui_kit::value_row(ui, "thread.data.angle", &format!("{}\u{b0}", trimmed(angle))); } if let Some(taper) = t.taper.filter(|x| *x > 0.0) { crate::ui_kit::value_row(ui, "thread.data.taper", &format!("1:{}", trimmed(1.0 / taper))); } if let Some(l2) = d.effective_thread_length { crate::ui_kit::value_row(ui, "thread.data.effective_length", &length(l2)); } if hole && let Some(d) = drill(designation, None) { crate::ui_kit::value_row(ui, "thread.data.tap_drill", &drill_label(d.mm, d.inch)); } }); } /// The inner end of a modelled thread (a thread's, or a tapped hole's towards its bottom): /// square, or a fade over its length. pub(crate) fn end_rows(ui: &mut egui::Ui, ease: &mut Ease) -> bool { let mut fade = usize::from(ease.fade); choice_row(ui, "End", "thread_end", &mut fade, ENDS_AT); ease.fade = fade == 1; if !ease.fade { return false; } let hint = if ease.short { tr!("thread.fade_short") } else { tr!("thread.fade_standard") }; hint_row(ui, "Fade Length", &mut ease.length, hint) } /// The Custom series' rows, in place of the Size list (the series lists no sizes) and the Class /// row (it gives no classes): the Profile, the Diameter and the Pitch, and the Angle of a V at an /// angle. They make the designation the Designation row shows ([`CustomRows::compose`]); a custom /// designation typed there, or saved, fills them, and with none they start from the face picked, /// `face` mm across ([`CustomRows::for_face`]). A row that is no length or angle says so under /// them, as does the thread service's refusal of what they make. Returns whether Enter was pressed /// in a row. fn custom_rows( ui: &mut egui::Ui, doc: &Document, designation: &mut String, suggested: &mut Option, rows: &mut Option>, face: Option, ) -> bool { if rows.as_ref().is_none_or(|r| r.source != *designation) { if let Some(read) = CustomRows::of(designation) { *rows = Some(Box::new(read)); } else if rows.is_none() { let mut fresh = CustomRows::for_face(face); if designation.trim().is_empty() { if let Some(made) = fresh.compose(doc) { *designation = made; *suggested = None; } } else { // A designation the service reads as no custom thread (a saved one its rules // reject) stays as it is, its reason shown, until a row is changed. fresh.source.clone_from(designation); fresh.refusal = threads::read_thread(designation).err(); } *rows = Some(Box::new(fresh)); } } let Some(r) = rows.as_mut() else { return false }; let before = (r.profile, r.diameter.clone(), r.pitch.clone(), r.angle.clone()); let labels: Vec<&str> = CUSTOM_PROFILES.iter().map(|(label, _)| *label).collect(); choice_row(ui, "thread.profile", "thread_custom_profile", &mut r.profile, &labels); let mut enter = expr_row(ui, "thread.diameter", &mut r.diameter); enter |= expr_row(ui, "thread.pitch", &mut r.pitch); if r.profile == V_AT_AN_ANGLE { enter |= expr_row(ui, "thread.angle", &mut r.angle); } let edited = (r.profile, &r.diameter, &r.pitch, &r.angle) != (before.0, &before.1, &before.2, &before.3); if edited && let Some(made) = r.compose(doc) { *designation = made; *suggested = None; } if let Some(why) = &r.error { crate::ui_kit::status_line(ui, why, StatusTone::Error); } else if let Some(why) = &r.refusal { crate::ui_kit::status_line(ui, why, StatusTone::Warning); } enter } /// The Size choice: the series' sizes by their designations (on a hole, `internal`, the sizes a /// hole takes), the one the designation names chosen; a size typed that the list does not have /// is listed last as typed, and with none yet the list opens at its top, `Select size` first. fn size_row(ui: &mut egui::Ui, series: ThreadItem, internal: Option, designation: &mut String, suggested: &mut Option) { let listed = sizes(series, internal == Some(true)); if listed.is_empty() { return; } let typed = designation.trim().to_string(); let read = thread(&typed).map(|t| t.designation); let (labels, mut selected, first) = size_labels(&listed, &typed, read.as_deref(), None); let before = selected; form_row(ui, "Size", |ui| crate::ui_kit::dropdown_grouped(ui, "thread_diameter", &mut selected, &labels, &[])); if selected != before && let Some(size) = selected.checked_sub(first).and_then(|i| listed.get(i)) { *designation = with_written(&typed, size); *suggested = None; } } /// A Size list's labels, the option shown chosen and the index of the first size: the sizes /// `listed` (the one `typed` names chosen, as typed or as the service writes it, `read`), and the /// choice that names none of them. With `custom` (a tapped hole's ISO metric sizes, /// `Some(chosen)`): Custom, listed last, chosen while `chosen` is or no size is; else a size typed /// that the list does not have, as typed, listed last; else, with none typed, `Select size`, /// listed first, so the list opens at its top. fn size_labels<'a>(listed: &'a [String], typed: &'a str, read: Option<&str>, custom: Option) -> (Vec<&'a str>, usize, usize) { let mut labels: Vec<&str> = listed.iter().map(String::as_str).collect(); let at = labels.iter().position(|s| *s == typed || Some(*s) == read); if let Some(chosen) = custom { let shown = if chosen { labels.len() } else { at.unwrap_or(labels.len()) }; labels.push("Custom"); return (labels, shown, 0); } match at { Some(at) => (labels, at, 0), None if typed.is_empty() => { labels.insert(0, "thread.select_size"); (labels, 0, 1) } None => { labels.push(typed); let shown = labels.len().saturating_sub(1); (labels, shown, 0) } } } /// The Class row of a thread: the classes the thread service gives its size on the side of the /// face picked (a shaft's external classes, a hole's internal ones) or none; and under it, with a /// class of that side, the limits of size the class allows. A class the size has on neither side /// goes (another series' size was chosen); a class of the other side stays shown as it is, and /// the command says why it is not this face's. A class the designation writes after the size /// (`1/4-20 UNC-2A`, as the service reads it: [`ScrewThread::class`]) is the thread's: the row /// shows it, and no other is chosen. No row for a size the service gives no class on this side, /// nor for text the service does not read. fn class_rows(ui: &mut egui::Ui, designation: &str, class: &mut Option, internal: bool) { let Some(t) = thread(designation) else { return }; if t.class.is_some() || class.as_deref().is_some_and(|c| !t.classes.iter().any(|x| x.name == c)) { *class = None; } let offered = t.classes_on(internal); let mut shown = t.class.clone().or_else(|| class.clone()); if offered.is_empty() && shown.is_none() { return; } class_choice(ui, "thread_class", &offered, &mut shown, t.class.is_some()); if t.class.is_none() { class.clone_from(&shown); } if let Some(name) = shown.as_deref().filter(|c| offered.iter().any(|x| x == c)) && let Some(limits) = limits_of(&t.designation, name, internal) { limit_row(ui, "thread.limits_major", limits.major_min, limits.major_max); limit_row(ui, "thread.limits_pitch", limits.pitch_min, limits.pitch_max); limit_row(ui, "thread.limits_minor", limits.minor_min, limits.minor_max); } } /// A read-only row of a class's limits of size: from the smallest to the largest value (mm), or /// the one limit the standard gives for the side; none without either. fn limit_row(ui: &mut egui::Ui, label: &str, min: Option, max: Option) { let (low, high) = (min.map(|v| format!("{v:.3}")), max.map(|v| format!("{v:.3}"))); let text = match (low.as_deref(), high.as_deref()) { (Some(low), Some(high)) => solidcraft_ui_text::format("thread.limits_range", &[("low", low), ("high", high)]), (Some(low), None) => solidcraft_ui_text::format("thread.limits_at_least", &[("low", low)]), (None, Some(high)) => solidcraft_ui_text::format("thread.limits_at_most", &[("high", high)]), (None, None) => return, }; crate::ui_kit::value_row(ui, label, &text); } /// The side of the face a thread is on (a hole's: an internal thread) and its diameter, worked /// out once for the picks they were found for, so an unchanged dialog does no geometry work: the /// Class row offers that side's classes, and the Custom series' rows start at the diameter. None /// before a cylindrical face is picked. #[derive(Clone, Debug, Default, PartialEq)] pub struct Side { of: Vec, pub(crate) internal: Option, /// The face's diameter (mm). pub(crate) diameter: Option, } impl Side { /// Work the side and the diameter out again when the picks changed. pub(crate) fn sync(&mut self, s: &Session, picks: &[Sel]) { if self.of.as_slice() != picks { self.of = picks.to_vec(); let face = picked_face(s, picks); self.internal = face.map(|(internal, _)| internal); self.diameter = face.map(|(_, diameter)| diameter); } } } /// Whether the first face picked is a hole's (the material outside its cylinder), and its /// diameter, found as the Thread command finds its face and side (`kernel::cylinder_face_at`), so /// the Class row offers what the command takes; none for no pick or a face that is not round. fn picked_face(s: &Session, picks: &[Sel]) -> Option<(bool, f64)> { let Some(Sel::Face { body, point, .. }) = picks.first() else { return None }; let world = crate::open_meshing::session_world(s); solidcraft_engine::kernel::cylinder_face_at(&world.body(body)?.body, *point).map(|c| (c.internal, 2.0 * c.radius)) } /// Add the picks the options use, and take away the others: the end to start from (optional, /// so it does not take the next click), and the Up To place (which does). pub(crate) fn sync_inputs(inputs: &mut Vec, active: &mut usize, o: &Options, doc: &Document) { let was = *active; set_object_accepting(inputs, active, START_END, EDGES, o.starts_at_an_end(doc)); *active = was.min(inputs.len().saturating_sub(1)); set_object_accepting(inputs, active, UP_TO, UP_TO_ACCEPT, o.extent == UP_TO_EXTENT); } /// Put the options into the command's parameters. Defaults are left out, so a thread without /// them means what it always did. /// The tip the command is sent: with an offset the start lies inside the face, so a chamfered /// start is the command's `tip: both`, the free far end (the refusal of `tip: start` advises it). pub(crate) fn sent_tip(o: &Options, doc: &Document) -> ThreadTip { if o.tip == ThreadTip::Start && o.has_offset(doc) { ThreadTip::Both } else { o.tip } } pub(crate) fn put_params(p: &mut Value, length: &str, o: &Options, inputs: &[SelInput]) { if !threads::is_default_series(&o.series) { p["series"] = json!(o.series); } match (&o.class, o.saved_class) { (Some(class), _) => p["class"] = json!(class), (None, true) => p["class"] = json!(""), (None, false) => {} } if o.hand != ThreadHand::default() { p["hand"] = json!(o.hand); } if o.starts != 1 { p["starts"] = json!(o.starts); } match o.extent { LENGTH => { p["extent"] = json!(EXTENTS[LENGTH].1); put(p, &[("length", length)]); } UP_TO_EXTENT => { p["extent"] = json!(EXTENTS[UP_TO_EXTENT].1); if let Some(to) = up_to(inputs) { p["up_to"] = to; } } _ => {} } put(p, &[("offset", o.offset.as_str())]); if let Some(from) = object_point(inputs, START_END) { p["from"] = from; } if let Some(e) = o.ease_out.param() { p["ease_out"] = e; } if o.to_bottom && !o.ease_out.fade && p.get("modeled").and_then(Value::as_bool).unwrap_or(false) { p["to_bottom"] = json!(true); } if o.tip != ThreadTip::None { p["tip"] = json!(o.tip); put(p, &[("chamfer_angle", o.chamfer_angle.as_str()), ("chamfer_depth", o.chamfer_depth.as_str())]); } if o.buttress() && o.steep_flank != SteepFlank::default() { p["steep_flank"] = json!(o.steep_flank); } } /// The picked Up To place: a plane's name, or a point on a face. fn up_to(inputs: &[SelInput]) -> Option { match inputs.iter().find(|i| i.label == UP_TO)?.items.first()? { Sel::Plane { name } => Some(json!(name)), _ => object_point(inputs, UP_TO), } } /// The face's size in the dialog's series, for an automatic size: the size the thread service fits /// to the face, past the series' last size too (a Ø150 shaft in ISO metric coarse takes ISO 261's /// M150x8, its coarsest pitch at 150 mm). pub(crate) fn suggested(s: &Session, picks: &[Sel], o: &Options) -> Option { picks.first().and_then(|sel| match sel { Sel::Face { body, point, .. } => { let world = crate::open_meshing::session_world(s); let mut state = solidcraft_engine::doc::ModelState::default(); state.bodies = world.bodies.iter().filter(|candidate| candidate.name == *body).cloned().collect(); solidcraft_engine::doc::suggested_thread_in(&state, *point, o.series).ok() } _ => None, }) } /// A saved thread's dialog: every option as saved, with its picks. pub(crate) fn reopen(d: &mut Dialog, s: &Session, feature: &Feature) { let kind = &feature.kind; let FeatureKind::Thread { face, designation, length, offset, modeled, continuous_flanks, from, up_to, series, class, hand, starts, ease_out, to_bottom, tip, chamfer_angle, chamfer_depth, steep_flank, // Kept by the edit itself (`timeline.redefine`), not a dialog option. old_auto_size: _, // Not a dialog option either, and dropped by the edit: the edited thread is made at the // thread's size. face_as_drawn: _, // Dropped by the edit too, which saves the series the Series row shows. series_from_designation, additional_faces, target_bodies, single_face_selection, } = kind else { return; }; d.extra.insert("continuous_flanks".into(), json!(continuous_flanks)); if *modeled { d.extra.insert("modeled".into(), json!(true)); } // A Thread of an older design that takes its series from its designation's words shows the // series it is built in now, that of the words its designation comes to, so OK keeps the thread. let series = if *series_from_designation { threads::formless_series(designation.as_deref().map(|text| evaluated_designation(&s.doc, text)).as_deref()) } else { *series }; let options = Options { series, class: class.clone(), saved_class: class.is_some(), hand: *hand, starts: *starts, extent: if length.is_some() { LENGTH } else if up_to.is_some() { UP_TO_EXTENT } else { FULL }, offset: offset.as_ref().map(expr).unwrap_or_default(), ease_out: Ease::of(ease_out), to_bottom: *to_bottom, tip: *tip, chamfer_angle: chamfer_angle.as_ref().map(expr).unwrap_or_default(), chamfer_depth: chamfer_depth.as_ref().map(expr).unwrap_or_default(), steep_flank: *steep_flank, // A custom thread's rows, read from its designation. custom: designation.as_deref().filter(|_| threads::is_custom(series)).and_then(CustomRows::of).map(Box::new), }; let refill = |slot: usize, saved| { let target = kind.thread_target_body(slot); let target_slot = slot != 1 || !matches!(up_to, Some(ThreadLimit::Face(_))); let mut pick = if !target_bodies.is_empty() && target_slot { let body = target.unwrap_or(""); feature .face_names .get(slot) .and_then(|name| crate::dialogs::named_refill_on_body(s, body, name, saved)) .or_else(|| Some(Sel::Face { body: body.to_string(), index: usize::MAX, point: saved })) } else { feature .face_names .get(slot) .and_then(|name| crate::dialogs::named_refill(s, kind.face_body(), name, saved, false)) .or_else(|| face_sel(s, saved)) }; if let Some(Sel::Face { point, .. }) = &mut pick { *point = solidcraft_engine::doc::restored_thread_pick(saved, *point); } pick }; // Face names follow the geometry walk: primary, optional Up To face, then added faces. let added_at = 1 + usize::from(matches!(up_to, Some(ThreadLimit::Face(_)))); if let Some(inp) = d.inputs.first_mut() { inp.multi = !additional_faces.is_empty() || (!single_face_selection && !target_bodies.is_empty()); inp.items = std::iter::once((0, face)) .chain(additional_faces.iter().enumerate().map(|(index, pick)| (added_at + index, pick))) .filter_map(|(slot, pick)| refill(slot, pick.0)) .collect(); } sync_inputs(&mut d.inputs, &mut d.active, &options, &s.doc); // A place no pick finds again (the model changed) is still the place saved. let place = |sel: Option, p| sel.unwrap_or(Sel::Vertex { body: String::new(), point: p }); let set = |d: &mut Dialog, label: &str, sel: Sel| { if let Some(inp) = d.inputs.iter_mut().find(|i| i.label == label) { inp.items = vec![sel]; } }; if let Some(from) = from { set(d, START_END, place(edge_sel(s, from.0), from.0)); } match up_to { Some(ThreadLimit::Face(at)) => set(d, UP_TO, place(refill(1, at.0), at.0)), Some(ThreadLimit::Plane(plane)) => { if let Some(sel) = plane_sel(s, plane) { set(d, UP_TO, sel); } } None => {} } d.active = 0; d.kind = Kind::Thread { designation: designation.clone().unwrap_or_default(), length: length.as_ref().map(expr).unwrap_or_default(), suggested: None, of: Vec::new(), options, side: Side::default(), }; } #[cfg(test)] #[path = "dialogs_thread_tests.rs"] pub(crate) mod tests; #[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 solidcore_record::Vec3; use solidcraft_engine::geom::MeshGeom; use solidcraft_engine::{Sel, Session}; 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); } /// A tapped hole's thread rows drawn once, as the Hole dialog draws them, on `opts`. fn draw_hole_rows(opts: &mut HoleOpts) { let context = egui::Context::default(); crate::fonts::setup_bundled_fonts(&context); let doc = Document::default(); context .run_ui(Default::default(), |ui| { egui::Grid::new("hole_rows").show(ui, |ui| { hole_rows(ui, &doc, opts); }); }) .textures_delta .clear(); } /// A tapped hole of `designation` with the hole's other options at their defaults. fn tapped(designation: &str) -> HoleOpts { HoleOpts { tapped: true, thread: designation.into(), ..HoleOpts::default() } } #[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 ["thread.series", "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(), solidcraft_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 = crate::open_meshing::session_world(&reopened); 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); } /// A tapped hole offers what a thread does: Modeled, and then its inner end, square or a /// fade, towards the bottom. OK cuts it; editing the hole brings them back. #[test] fn a_tapped_hole_is_modelled_with_the_threads_end() { let (app, dialog) = hole(); let mut h = crate::scenario::Harness::new(); *h.app = app; h.app.dialog = Some(dialog); h.frames(3); for handle in ["dialog:Hole Tap Type", "dialog:Hole Tap Type:Tapped"] { h.step(&json!({"click":{"handle":handle}})).unwrap(); } h.frames(2); assert!(crate::scenario::rect_of("dialog:row:End").is_none(), "a listed thread has no end to finish"); h.step(&json!({"click":{"handle":"dialog:Modeled"}})).unwrap(); h.frames(2); for handle in ["dialog:End", "dialog:End:ui.fade"] { h.step(&json!({"click":{"handle":handle}})).unwrap(); } h.frames(2); let (cmd, p) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); assert_eq!((&p["modeled"], &p["ease_out"]), (&json!(true), &json!("standard")), "{p}"); let id = h.app.run(&cmd, p.clone()).unwrap()["feature"].as_u64().unwrap(); h.app.dialog = None; h.app.edit_feature(id); h.frames(2); let (_, again) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); let again = if again.get("params").is_some() { again["params"].clone() } else { again }; assert_eq!((&again["modeled"], &again["ease_out"]), (&json!(true), &json!("standard")), "{again}"); } /// A tapped hole's drill: the tap maker's for the size (M8: 6.8 mm, ISO 2306), or a typed one /// the standards accept, the drilled hole being the internal thread's minor diameter: with no /// class, from its basic minor diameter, D1 = 8 - 1.082532 x 1.25 = 6.647 mm (ISO 724), to that /// drill. Outside that the command names the range. A new size takes its own drill again, and /// a saved hole drilled otherwise (an older design's d - P) reopens with its drill. #[test] fn a_tapped_holes_drill_is_the_tap_makers_or_one_within_its_range() { let (app, dialog) = hole(); let mut h = crate::scenario::Harness::new(); *h.app = app; h.app.dialog = Some(dialog); h.frames(3); for handle in ["dialog:Hole Tap Type", "dialog:Hole Tap Type:Tapped"] { h.step(&json!({"click":{"handle":handle}})).unwrap(); } let set = |h: &mut crate::scenario::Harness, field: &str, text: &str| { h.step(&json!({"click":{"handle":format!("dialog:{field}")}})).unwrap(); h.step(&json!({"key":"A","cmd":true})).unwrap(); h.step(&json!({"text":text})).unwrap(); h.frames(2); }; set(&mut h, "Designation", "M8"); let params = |h: &crate::scenario::Harness| apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0).1; assert!(params(&h).get("diameter").is_none(), "the tap maker's drill is the command's own"); set(&mut h, "Tap drill diameter", "6.7 mm"); assert_eq!(params(&h)["diameter"], json!("6.7 mm")); let (cmd, p) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); let id = h.app.run(&cmd, p.clone()).unwrap()["feature"].as_u64().unwrap(); set(&mut h, "Tap drill diameter", "7.5 mm"); let (cmd, p) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); let e = h.app.session.execute(&cmd, &p).unwrap_err().to_string(); assert!(e.contains("from 6.647 to 6.8 mm") && e.contains("too little of the thread"), "{e}"); set(&mut h, "Designation", "M10"); assert!(params(&h).get("diameter").is_none(), "a new size takes its own drill"); // An older design's M8 hole, drilled 6.75 mm (d - P), keeps that drill when edited. let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &mut h.app.session.doc_mut().feature_mut(id).unwrap().kind else { panic!("not Hole") }; *diameter = "6.75 mm".into(); h.app.dialog = None; h.app.edit_feature(id); h.frames(2); let (_, again) = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0); let again = if again.get("params").is_some() { again["params"].clone() } else { again }; assert_eq!(again["diameter"], json!("6.75 mm"), "{again}"); } #[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 t = thread(&opts.thread).unwrap(); assert!((t.major_diameter - 6.35).abs() < 1e-9 && (t.pitch - 1.27).abs() < 1e-9, "{t:?}"); 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() { let read = |text: String| thread(&text).map(|t| (t.major_diameter, t.pitch)); for (d, p) in numbers(ThreadItem::IsoMetricCoarse, true).iter().map(|n| (n.major, n.pitch)) { assert_eq!(read(format!("M{d}")), Some((d, p))); assert_eq!(read(format!("M{d}x{p}")), Some((d, p))); } for original in ["M5", "M5x0.5", "M33x1", "1/4-20 UNC", "#10-32 UNF", "invalid"] { let mut opts = tapped(original); draw_hole_rows(&mut opts); assert_eq!(opts.thread, original); } } #[test] fn expanded_catalogue_profiles_select_unified_sizes_and_keep_metric_custom_mode() { let mut h = custom_hole_widget(); super::tests::choose_listed(&mut h, "thread.series", "thread.series.unc"); super::tests::choose_listed(&mut h, "Size", "1/4-20 UNC"); h.frames(3); assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["thread"], "1/4-20 UNC"); assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_none()); assert!(h.widget("0.201 in").is_some(), "a UNC size's tap drill must read in inches (#10353)"); let unc = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap().remove(0).1; assert!(unc.get("diameter").is_none(), "the untouched inch default keeps the catalogue's exact drill: {unc}"); super::tests::choose_listed(&mut h, "thread.series", "thread.series.unf"); super::tests::choose_listed(&mut h, "Size", "#10-32 UNF"); h.frames(3); assert_eq!(apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["thread"], "#10-32 UNF"); super::tests::choose_listed(&mut h, "thread.series", "thread.series.iso_metric_coarse"); if let Some(Dialog { kind: Kind::Hole { opts, .. }, .. }) = h.app.dialog.as_mut() { opts.thread = "M8x1".into(); } h.frames(3); assert!(h.widget("M8x1").is_some()); assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_none()); // Choosing Custom is persistent even at a now-catalogued fine pitch. if let Some(Dialog { kind: Kind::Hole { opts, .. }, .. }) = h.app.dialog.as_mut() { opts.custom_thread = Some(HoleThreadDraft::new(&opts.thread)); } h.frames(3); assert!(h.widget("Custom").is_some()); assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_some()); } #[test] fn unified_tap_drills_read_in_inches_and_other_profiles_in_millimetres() { // #10353: 1/4-20 UNC is a #7 drill (0.201 in), 1/2-13 UNC a 27/64 in drill. for (name, label) in [("1/4-20 UNC", "0.201 in"), ("1/2-13 UNC", "0.4219 in"), ("#10-32 UNF", "0.159 in")] { assert_eq!(tap_drill_label(name).as_deref(), Some(label)); } for series in [ThreadItem::Unc, ThreadItem::Unf] { for size in sizes(series, true).iter() { let label = tap_drill_label(size).unwrap(); let inches: f64 = label.strip_suffix(" in").unwrap().parse().unwrap(); assert!((inches * 25.4 - default_drill(size).unwrap()).abs() < 0.0005 * 25.4, "{size}: {label}"); } } // The standards' drills: ISO 2306:1972 tables 5 and 6 drill G 1/4 at 11.8 mm and Rp 1/4 at // 11.5 mm; a taper thread is drilled to its minor diameter at its small end, Rc 1/2 (ISO 7-1) // 18.631 - 13.2/16 = 17.806 mm and 1/2 NPT (H28) 0.77843 - 0.8/14 - 0.5337/16 in = 17.473 mm. for (name, label) in [("M8", "6.8 mm"), ("G 1/4", "11.8 mm"), ("Rp 1/4", "11.5 mm"), ("Rc 1/2", "17.806 mm"), ("1/2 NPT", "17.473 mm")] { assert_eq!(tap_drill_label(name).as_deref(), Some(label)); } } #[test] fn expanded_catalogue_drills_real_cylinders_and_reopens_without_resizing() { for (name, major, pitch, drill) in [ ("1/4-20 UNC", 6.35, 1.27, 5.1054), ("#10-32 UNF", 4.826, 25.4 / 32.0, 4.0386), ("M8", 8.0, 1.25, 6.8), ("M8x1", 8.0, 1.0, 7.0), ("M8.5x1", 8.5, 1.0, 7.5), ] { let (mut app, _) = hole(); let out = app.run("solid.hole", json!({"position":[10,10,10], "thread":name})).unwrap(); let id = out["feature"].as_u64().unwrap(); let saved = app.session.doc.to_json(); let reopened = Session::new(Document::from_json(&saved).unwrap()); let world = crate::open_meshing::session_world(&reopened); let t = &world.threads[0]; assert_eq!(t.designation, name); assert!((t.major_diameter - major).abs() < 1e-9 && (t.pitch - pitch).abs() < 1e-9); let body = &world.bodies[0].body; assert!(body.validity().is_empty()); let face = solidcraft_engine::kernel::cylinder_face_at(body, Vec3::new(10.0 + drill / 2.0, 10.0, 5.0)).unwrap(); assert!(face.internal && (2.0 * face.radius - drill).abs() < 1e-8); let actual = body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume; let expected = 4000.0 - std::f64::consts::PI * (drill / 2.0).powi(2) * 10.0; assert!((actual - expected).abs() < 0.5, "{name}: {actual} versus {expected}"); // A saved explicit drill remains authoritative, including a legacy metric bore. let mut doc = Document::from_json(&saved).unwrap(); let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &mut doc.feature_mut(id).unwrap().kind else { panic!("not Hole") }; *diameter = format!("{} mm", drill + 0.05).as_str().into(); let reopened = Session::new(Document::from_json(&doc.to_json()).unwrap()); let world = crate::open_meshing::session_world(&reopened); let face = solidcraft_engine::kernel::cylinder_face_at(&world.bodies[0].body, Vec3::new(10.0 + (drill + 0.05) / 2.0, 10.0, 5.0)).unwrap(); assert!((2.0 * face.radius - drill - 0.05).abs() < 1e-8); } } #[test] fn expanded_catalogue_rejects_external_taper_holes_and_mismatched_thread_forms() { let (mut app, _) = hole(); let before = app.session.doc.to_json(); for name in ["R1/4", "1/4-20 UNF"] { assert!(app.run("solid.hole", json!({"position":[10,10,10],"thread":name})).is_err()); assert_eq!(app.session.doc.to_json(), before); } app.run("solid.hole", json!({"position":[10,10,10],"thread":"M8"})).unwrap(); let before = app.session.doc.to_json(); for designation in ["G 1/4", "Rp 1/4"] { for modeled in [false, true] { assert!(app.run("solid.thread", json!({"face":[13.4,10,5],"designation":designation,"modeled":modeled})).is_err()); assert_eq!(app.session.doc.to_json(), before); } } assert_eq!(app.session.doc.to_json(), before); let out = app.run("solid.thread", json!({"face":[13.4,10,5],"designation":"M8"})).unwrap(); let solidcraft_engine::doc::FeatureKind::Thread { designation, modeled, .. } = &mut app.session.doc_mut().feature_mut(out["feature"].as_u64().unwrap()).unwrap().kind else { panic!("not Thread") }; *designation = Some("1/4-20 UNC".into()); *modeled = true; let reopened = Session::new(Document::from_json(&app.session.doc.to_json()).unwrap()); // The thread is metric (the M8 it was made as): a unified designation is not one of its. let error = reopened.model.results.last().unwrap().error.clone().unwrap(); assert!(error.contains("`1/4-20 UNC` is a unified designation, not metric"), "{error}"); } #[test] fn expanded_catalogue_public_plate_evidence_uses_only_headless_model_rendering() { let Some(dir) = std::env::var_os("SOLIDCRAFT_CATALOGUE_EVIDENCE") else { return }; crate::gpu::install_cpu_picture_renderer(); let mut h = crate::scenario::Harness::new(); h.app.run("solid.box", json!({"length":50,"width":25,"height":6,"body_name":"ThreadPlate"})).unwrap(); for (x, name) in [(10, "M8x1"), (25, "1/4-20 UNC"), (40, "#10-32 UNF")] { h.app.run("solid.hole", json!({"position":[x,12.5,6],"thread":name})).unwrap(); } h.call("ui.view", json!({"view":"iso"})); let path = std::path::Path::new(&dir).join("catalogue-plate.png"); let out = h.call("ui.render", json!({"path":path,"width":1000,"height":700,"grid":false,"axes":false})); assert_eq!(out["ok"], true, "{out}"); std::fs::write(std::path::Path::new(&dir).join("catalogue-plate.solidcraft"), h.app.session.doc.to_json()).unwrap(); } /// A tapped hole's size of an ISO metric diameter and pitch, as the thread service writes it. fn designation(diameter: f64, pitch: f64) -> String { kernel_threads::write_size(ThreadItem::IsoMetricCoarse, diameter, pitch).unwrap() } #[test] fn contribution_metric_designation_omits_only_the_catalogue_coarse_pitch() { let read = |text: &str| thread(text).map(|t| (t.major_diameter, t.pitch)); for (d, p) in numbers(ThreadItem::IsoMetricCoarse, false).iter().map(|n| (n.major, n.pitch)) { assert_eq!(designation(d, p), format!("M{d}")); assert_eq!(read(&designation(d, p)), Some((d, p))); assert_eq!(read(&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() { // The tapped hole's rows; the thread dialog's own tests cover its designations. for original in ["M8x1.25", "M8x1", "M33x1", "M5×0.5", " m8x1.25 ", "invalid"] { let mut opts = tapped(original); draw_hole_rows(&mut opts); assert_eq!(opts.thread, original); } } #[test] fn contribution_metric_designation_keeps_domain_pitch_drill_units_and_reopen() { for (diameter, pitch, drill) in [(8., 1.25, 6.8), (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 = crate::open_meshing::session_world(&reopened); assert_eq!(state.threads.len(), 1); assert!((state.threads[0].pitch - pitch).abs() < 1e-9); } } #[test] fn parallel_pipe_profiles_switch_and_cancel_without_changing_the_document() { let mut h = custom_hole_widget(); let before = h.app.session.doc.to_json(); // ISO 2306:1972 drills G 1/4 at 11.8 mm (table 5) and Rp 1/4 at 11.5 mm (table 6). for (series, name, drill) in [("thread.series.bspp_g", "G 1/4", "11.8 mm"), ("thread.series.bspt_r", "Rp 1/4", "11.5 mm")] { super::tests::choose_listed(&mut h, "thread.series", series); super::tests::choose_listed(&mut h, "Size", name); h.frames(3); let command = apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert_eq!(command[0].1["thread"], name); assert!(command[0].1.get("diameter").is_none()); assert!(h.widget(drill).is_some()); assert!(crate::scenario::handle_at("dialog:Nominal diameter").is_none()); } h.step(&json!({"key":"Escape"})).unwrap(); assert!(h.app.dialog.is_none()); assert_eq!(h.app.session.doc.to_json(), before); } #[test] fn parallel_pipe_holes_have_the_tabulated_cylinders_depth_and_saved_designations() { // The G and Rp sizes 1/8 to 1, drilled as ISO 2306:1972 gives them (tables 5 and 6). for (designation, drill) in [ ("G 1/8", 8.8), ("G 1/4", 11.8), ("G 3/8", 15.25), ("G 1/2", 19.0), ("G 3/4", 24.5), ("G 1", 30.75), ("Rp 1/8", 8.6), ("Rp 1/4", 11.5), ("Rp 3/8", 15.0), ("Rp 1/2", 18.5), ("Rp 3/4", 24.0), ("Rp 1", 30.25), ] { let size = thread(designation).unwrap(); let mut app = SolveApp::new(Session::default(), Services::default()); app.run("solid.box", json!({"length":80,"width":80,"height":15,"body_name":"Plate"})).unwrap(); let result = app.run("solid.hole", json!({"position":[40,40,15],"thread":designation,"depth":10})).unwrap(); let saved = app.session.doc.to_json(); let reopened = Session::new(Document::from_json(&saved).unwrap()); let state = crate::open_meshing::session_world(&reopened); assert_eq!(state.threads.len(), 1); let t = &state.threads[0]; assert_eq!(t.designation, designation); assert!((t.major_diameter - size.major_diameter).abs() < 1e-9 && (t.pitch - size.pitch).abs() < 1e-9); assert!((t.end - t.start - 10.0).abs() < 1e-6); let body = &state.bodies[0].body; assert!(body.validity().is_empty()); for z in [6.0, 10.0, 14.0] { let c = solidcraft_engine::kernel::cylinder_face_at(body, Vec3::new(40.0 + drill / 2.0, 40.0, z)).unwrap(); assert!(c.internal && (2.0 * c.radius - drill).abs() < 1e-8); } let actual = body.mesh(&solidcraft_engine::kernel::MeshTolerance::chord(0.001)).unwrap().measure().volume; let removed = std::f64::consts::PI * (drill / 2.0).powi(2) * 10.0; assert!((actual - (96000.0 - removed)).abs() / removed < 0.002, "{designation}: {actual}"); assert_eq!(reopened.doc.to_json(), saved); if designation.ends_with(" 1/4") { let mut doc = Document::from_json(&saved).unwrap(); let solidcraft_engine::doc::FeatureKind::Hole { diameter, .. } = &mut doc.feature_mut(result["feature"].as_u64().unwrap()).unwrap().kind else { panic!("not Hole") }; *diameter = format!("{} mm", drill + 0.03).as_str().into(); let reopened = Session::new(Document::from_json(&doc.to_json()).unwrap()); let state = crate::open_meshing::session_world(&reopened); let c = solidcraft_engine::kernel::cylinder_face_at(&state.bodies[0].body, Vec3::new(40.0 + (drill + 0.03) / 2.0, 40.0, 10.0)).unwrap(); assert!((2.0 * c.radius - drill - 0.03).abs() < 1e-8); } } } }