Personal Hole parameter presets (#4480)

* feat: add personal Hole parameter presets

* feat(hole): prompt for preset names and recall changed selections

Ask for a name only on Save new or Rename in the kit confirmation. Keep Enter and Escape inside the prompt, preserve cancelled drafts, recall only changed selections, and retain independent recessed-hole bottom choices.

* feat(hole): preserve thread direction and partial depth in presets

Carry Left/Partial, explicit source units and Custom draft guards through personal preset capture and recall. Preserve legacy Right/Full/flat defaults and reject unknown options before changing the form. This production bridge depends on the handedness and graphical-depth changes inherited below it.

* docs(hole): describe supported preset thread options

* feat(ui): save modified hole presets in place

* fix(presets): retain reference placement and current locale contracts

* test(ui): borrow restored preset library during serialization

* test(presets): preserve modal focus with viewport focus restoration

* Use UI kit controls for hole preset selection
This commit is contained in:
amolinari-autotex
2026-10-26 22:00:56 +00:00
committed by GitHub
parent c391ef17cb
commit 1d02a5f2d4
12 changed files with 1319 additions and 15 deletions
-3
View File
@@ -2210,10 +2210,7 @@
"the parts library is not available": "the parts library is not available",
"thread.automatic_size": "Automatic size",
"thread.designation": "Designation",
"thread.direction": "Thread direction",
"thread.iso_metric": "ISO metric",
"thread.left_hand": "Left-hand",
"thread.right_hand": "Right-hand",
"thread.select_size": "Select size",
"timeline.delete_after_marker_one": "Delete 1 Feature After History Marker",
"timeline.delete_after_marker_other": "Delete {count} Features After History Marker",
-3
View File
@@ -1131,10 +1131,7 @@
"the parts library is not available": "la libreria delle parti non è disponibile",
"thread.automatic_size": "Dimensione automatica",
"thread.designation": "Designazione",
"thread.direction": "Verso del filetto",
"thread.iso_metric": "Metrica ISO",
"thread.left_hand": "Sinistro",
"thread.right_hand": "Destro",
"thread.select_size": "Seleziona dimensione",
"timeline.group": "Nuova cartella di lavorazioni",
"timeline.move_many": "Sposta elementi della sequenza temporale",
-3
View File
@@ -2210,10 +2210,7 @@
"the parts library is not available": "パーツライブラリは利用できません",
"thread.automatic_size": "サイズを自動選択",
"thread.designation": "ねじの呼び",
"thread.direction": "ねじの方向",
"thread.iso_metric": "ISOメートルねじ",
"thread.left_hand": "左ねじ",
"thread.right_hand": "右ねじ",
"thread.select_size": "サイズを選択",
"timeline.delete_after_marker_one": "履歴マーカー以降の 1 個のフィーチャーを削除",
"timeline.delete_after_marker_other": "履歴マーカー以降の {count} 個のフィーチャーを削除",
+102
View File
@@ -0,0 +1,102 @@
{
"en": {
"hole_presets.confirm_delete": "Confirm delete",
"hole_presets.delete": "Delete",
"hole_presets.delete_prompt": "Delete this personal preset? Existing holes are unchanged.",
"hole_presets.full": "The personal library already contains 64 presets.",
"hole_presets.invalid_name": "Enter a short name without line breaks or control characters.",
"hole_presets.invalid_parameters": "Complete the hole parameters using valid expressions of reasonable length.",
"hole_presets.missing": "The selected preset is no longer available.",
"hole_presets.name": "Preset name",
"hole_presets.name_exists": "A preset with this name already exists. Use a different name.",
"hole_presets.name_hint": "A unique name",
"hole_presets.overwrite": "Save changes to selected preset",
"hole_presets.preset": "Preset",
"hole_presets.recall": "Recall",
"hole_presets.rename": "Rename",
"hole_presets.save": "Save new",
"hole_presets.scope": "Saved in your profile for all projects.",
"hole_presets.select": "Select a preset",
"hole_presets.title": "Personal presets",
"hole_presets.unsupported_options": "This preset uses thread options that this version cannot recall.",
"hole_presets.unsupported_overwrite": "This preset contains options that cannot be overwritten safely.",
"thread.direction": "Thread direction",
"thread.left_hand": "Left-hand",
"thread.right_hand": "Right-hand"
},
"it": {
"hole_presets.confirm_delete": "Conferma eliminazione",
"hole_presets.delete": "Elimina",
"hole_presets.delete_prompt": "Eliminare questo preset personale? I fori esistenti restano invariati.",
"hole_presets.full": "La raccolta personale contiene già 64 preset.",
"hole_presets.invalid_name": "Inserisci un nome breve, senza a capo o caratteri di controllo.",
"hole_presets.invalid_parameters": "Completa i parametri del foro con espressioni valide e di lunghezza ragionevole.",
"hole_presets.missing": "Il preset selezionato non è più disponibile.",
"hole_presets.name": "Nome preset",
"hole_presets.name_exists": "Esiste già un preset con questo nome. Usa un nome diverso.",
"hole_presets.name_hint": "Un nome univoco",
"hole_presets.overwrite": "Salva le modifiche nel preset selezionato",
"hole_presets.preset": "Preset",
"hole_presets.recall": "Richiama",
"hole_presets.rename": "Rinomina",
"hole_presets.save": "Salva nuovo",
"hole_presets.scope": "Salvati nel tuo profilo per tutti i progetti.",
"hole_presets.select": "Seleziona un preset",
"hole_presets.title": "Preset personali",
"hole_presets.unsupported_options": "Questo preset usa opzioni del filetto che questa versione non può richiamare.",
"hole_presets.unsupported_overwrite": "Questo preset contiene opzioni che non possono essere sovrascritte in sicurezza.",
"thread.direction": "Verso del filetto",
"thread.left_hand": "Sinistro",
"thread.right_hand": "Destro"
},
"ja": {
"hole_presets.confirm_delete": "削除を確認",
"hole_presets.delete": "削除",
"hole_presets.delete_prompt": "この個人用プリセットを削除しますか?既存の穴は変更されません。",
"hole_presets.full": "個人用ライブラリには既に64個のプリセットがあります。",
"hole_presets.invalid_name": "改行や制御文字を含まない短い名前を入力してください。",
"hole_presets.invalid_parameters": "適切な長さの有効な式で穴のパラメーターを入力してください。",
"hole_presets.missing": "選択したプリセットは利用できなくなりました。",
"hole_presets.name": "プリセット名",
"hole_presets.name_exists": "同じ名前のプリセットが既にあります。別の名前を指定してください。",
"hole_presets.name_hint": "一意の名前",
"hole_presets.overwrite": "選択したプリセットの変更を保存",
"hole_presets.preset": "プリセット",
"hole_presets.recall": "呼び出し",
"hole_presets.rename": "名前を変更",
"hole_presets.save": "新規保存",
"hole_presets.scope": "すべてのプロジェクトで使えるようにプロファイルに保存します。",
"hole_presets.select": "プリセットを選択",
"hole_presets.title": "個人用プリセット",
"hole_presets.unsupported_options": "このプリセットには、このバージョンで呼び出せないねじオプションが含まれています。",
"hole_presets.unsupported_overwrite": "このプリセットには安全に上書きできないオプションが含まれています。",
"thread.direction": "ねじの方向",
"thread.left_hand": "左ねじ",
"thread.right_hand": "右ねじ"
},
"zh": {
"hole_presets.confirm_delete": "确认删除",
"hole_presets.delete": "删除",
"hole_presets.delete_prompt": "删除此个人预设?现有孔不会改变。",
"hole_presets.full": "个人库中已有64个预设。",
"hole_presets.invalid_name": "请输入不含换行符或控制字符的简短名称。",
"hole_presets.invalid_parameters": "请使用长度适当的有效表达式填写孔参数。",
"hole_presets.missing": "所选预设已不可用。",
"hole_presets.name": "预设名称",
"hole_presets.name_exists": "同名预设已存在,请使用其他名称。",
"hole_presets.name_hint": "唯一名称",
"hole_presets.overwrite": "保存对所选预设的修改",
"hole_presets.preset": "预设",
"hole_presets.recall": "调用",
"hole_presets.rename": "重命名",
"hole_presets.save": "另存为新预设",
"hole_presets.scope": "保存在您的配置中,适用于所有项目。",
"hole_presets.select": "选择预设",
"hole_presets.title": "个人预设",
"hole_presets.unsupported_options": "此预设使用了当前版本无法调用的螺纹选项。",
"hole_presets.unsupported_overwrite": "此预设包含无法安全覆盖的选项。",
"thread.direction": "螺纹方向",
"thread.left_hand": "左旋",
"thread.right_hand": "右旋"
}
}
-3
View File
@@ -2210,10 +2210,7 @@
"the parts library is not available": "零件库不可用",
"thread.automatic_size": "自动尺寸",
"thread.designation": "螺纹标记",
"thread.direction": "螺纹方向",
"thread.iso_metric": "ISO 公制",
"thread.left_hand": "左旋",
"thread.right_hand": "右旋",
"thread.select_size": "选择尺寸",
"timeline.delete_after_marker_one": "删除历史标记之后的 1 个特征",
"timeline.delete_after_marker_other": "删除历史标记之后的 {count} 个特征",
+17 -2
View File
@@ -2814,6 +2814,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
let body = |ui: &mut egui::Ui| {
d.sync_fillet_chain(&app.session);
crate::hole_presets::rows(ui, &mut d, &mut app.preferences.hole_presets, &app.session.doc, reset_scroll);
let (accepted, fields) = crate::ui_kit::value_fields(ctx, || dense::rows(app, ctx, &mut d, ui));
enter |= accepted;
value_fields = fields;
@@ -2897,6 +2898,12 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
} else {
d.value_focus = ctx.memory(|memory| memory.focused()).filter(|id| value_fields.iter().any(|(field, _)| field == id));
}
let preset_prompt = crate::hole_presets::name_prompt(ctx, &mut d, &mut app.preferences.hole_presets, &app.session.doc);
if preset_prompt {
enter = false;
ok = false;
cancel = false;
}
// Keyboard: Enter applies (from a value field, or with nothing focused), Esc cancels.
let (enter_free, esc) = ctx.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape)));
let nothing_focused = ctx.memory(|m| m.focused().is_none());
@@ -2906,10 +2913,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
&& !matches!(&d.kind, Kind::Motion(k) if k.wide())
&& !matches!(&d.kind, Kind::Material { editor, .. } if editor.editing());
let report_active = app.issue_report.draft.is_some();
if !report_active && enter_applies && app.applying.is_none() && (enter || canvas_enter || (enter_free && nothing_focused)) {
if !preset_prompt && !report_active && enter_applies && app.applying.is_none() && (enter || canvas_enter || (enter_free && nothing_focused)) {
ok = true;
}
if !report_active && esc && !app.esc_handled {
if !preset_prompt && !report_active && esc && !app.esc_handled {
app.esc_handled = true;
cancel = true;
}
@@ -3128,6 +3135,14 @@ fn set_to_object(inputs: &mut Vec<SelInput>, active: &mut usize, on: bool) {
set_object(inputs, active, TO_OBJECT, on);
}
/// A personal preset remembers the extent mode, never its destination geometry.
pub(crate) fn preset_to_object(d: &mut Dialog, on: bool) {
set_to_object(&mut d.inputs, &mut d.active, on);
if let Some(input) = d.inputs.iter_mut().find(|input| input.label == TO_OBJECT) {
input.items.clear();
}
}
fn set_object(inputs: &mut Vec<SelInput>, active: &mut usize, label: &'static str, on: bool) {
if on && !object_on(inputs, label) {
inputs.push(SelInput::new(label, FACES | selection::VERTICES, false));
@@ -15,6 +15,299 @@ use crate::dialogs::Kind;
use crate::scenario::Harness;
use crate::viewport::Hit;
fn personal_preset_harness() -> Harness {
let mut h = Harness::new();
crate::fonts::setup_bundled_fonts(&h.ctx);
h.call("ui.resize", json!({"width":1400,"height":1100}));
h.app.run("solid.box", json!({"name":"PresetFixture","length":40,"width":30,"height":20})).unwrap();
h.app.session.selection = vec![Sel::Face { body: "PresetFixture".into(), index: 5, point: Vec3::new(10.0, 10.0, 20.0) }];
h.app.start("solid.hole");
h.frames(4);
h.step(&json!({"click":{"handle":"dialog:section:hole_presets.title"}})).unwrap();
h.frames(2);
h
}
fn preset_name(h: &mut Harness, name: &str) {
h.step(&json!({"click":{"handle":"dialog:hole_presets.name"}})).unwrap();
h.step(&json!({"key":"A","cmd":true})).unwrap();
h.step(&json!({"text":name})).unwrap();
}
fn confirm_preset_name(h: &mut Harness) {
h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap();
}
fn save_preset(h: &mut Harness, name: &str) {
h.step(&json!({"widget":"Save new"})).unwrap();
preset_name(h, name);
confirm_preset_name(h);
}
fn choose_preset(h: &mut Harness, name: &str) {
h.step(&json!({"click":{"handle":"dialog:hole_presets.preset"}})).unwrap();
h.step(&json!({"click":{"handle":format!("dialog:hole_presets.preset:{name}")}})).unwrap();
}
#[test]
fn hole_presets_retain_independent_bottom_choice_for_counterbore_and_countersink() {
for (style, kind) in [("counterbore", 1), ("countersink", 2)] {
for angled in [false, true] {
let mut h = personal_preset_harness();
let row = json!({"name":"Bottom choice","style":style,"extent":"distance",
"diameter":"4 mm","depth":"12 mm","cb_diameter":"8 mm","cb_depth":"3 mm",
"cs_diameter":"8 mm","cs_angle":"90 deg","tip_angle":"129 deg",
"tapped":false,"thread":"M5","angled_bottom":angled});
h.app.preferences.hole_presets = serde_json::from_value(json!([row])).unwrap();
assert_eq!(
serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[0]["angled_bottom"],
angled,
"recess bottom choice must survive preference serialization independently of style"
);
if let Kind::Hole { opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
opts.angled = !angled;
}
h.frames(2);
choose_preset(&mut h, "Bottom choice");
assert!(
matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole { kind:k,opts,.. } if *k==kind && opts.angled==angled && opts.tip_angle=="129 deg")
);
save_preset(&mut h, "Bottom copy");
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[1]["angled_bottom"], angled);
assert_eq!(h.app.session.doc.features.len(), 1);
}
}
}
#[test]
fn hole_presets_legacy_drilled_and_recess_records_keep_their_original_bottom() {
for (style, kind, angled) in [("drilled", 0, true), ("counterbore", 1, false), ("countersink", 2, false)] {
let mut h = personal_preset_harness();
let row = json!({"name":"Legacy","style":style,"extent":"distance",
"diameter":"4 mm","depth":"12 mm","cb_diameter":"8 mm","cb_depth":"3 mm",
"cs_diameter":"8 mm","cs_angle":"90 deg","tip_angle":"129 deg","tapped":false,"thread":"M5"});
h.app.preferences.hole_presets = serde_json::from_value(json!([row])).unwrap();
h.frames(2);
choose_preset(&mut h, "Legacy");
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole { kind:k,opts,.. } if *k==kind && opts.angled==angled));
}
}
#[test]
fn hole_presets_through_bottom_keeps_inactive_empty_angle_text() {
for style in [0, 1, 2] {
let mut h = personal_preset_harness();
if let Kind::Hole { kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*kind = style;
opts.all = true;
opts.angled = true;
opts.tip_angle.clear();
}
h.frames(2);
save_preset(&mut h, "Through");
let rows = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(rows.as_array().unwrap().len(), 1, "inactive bottom angle must not block a through preset, style={style}");
assert_eq!(rows[0]["tip_angle"], "");
assert_eq!(rows[0]["angled_bottom"], true);
}
}
#[test]
fn hole_presets_automatically_recall_only_changed_selection_without_persistent_name_or_recall_button() {
let mut h = personal_preset_harness();
h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"],"not_shown":"Recall"}})).unwrap();
if let Kind::Hole { diameter, depth, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "4.2 mm".into();
*depth = "0.5 in".into();
opts.tapped = true;
opts.thread = "M5".into();
}
save_preset(&mut h, "Workshop");
if let Kind::Hole { diameter, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "8 mm".into();
}
save_preset(&mut h, "Other");
let document = serde_json::to_value(&*h.app.session.doc).unwrap();
let inputs = format!("{:?}", h.app.dialog.as_ref().unwrap().inputs);
choose_preset(&mut h, "Workshop");
assert!(
matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {diameter,depth,opts,..} if diameter=="4.2 mm" && depth=="0.5 in" && opts.tapped && opts.thread=="M5")
);
if let Kind::Hole { diameter, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "9 mm".into();
}
h.frames(8);
assert!(
matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {diameter,..} if diameter=="9 mm"),
"an unchanged selection must not overwrite manual edits every frame"
);
choose_preset(&mut h, "Select a preset");
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {diameter,..} if diameter=="9 mm"));
choose_preset(&mut h, "Workshop");
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {diameter,..} if diameter=="4.2 mm"));
assert_eq!(serde_json::to_value(&*h.app.session.doc).unwrap(), document);
assert_eq!(format!("{:?}", h.app.dialog.as_ref().unwrap().inputs), inputs);
h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"],"not_shown":"Recall"}})).unwrap();
h.step(&json!({"key":"Escape"})).unwrap();
assert!(h.app.dialog.is_none());
h.app.start("solid.hole");
h.frames(4);
if let Kind::Hole { diameter, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "9 mm".into();
}
h.frames(2);
choose_preset(&mut h, "Workshop");
assert!(
matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {diameter,..} if diameter=="4.2 mm"),
"the same preset can be selected in a fresh Hole dialog"
);
h.step(&json!({"widget":"Save new"})).unwrap();
// Closing the tool programmatically must not leave a prompt in its next instance.
h.app.dialog = None;
h.frames(2);
h.app.start("solid.hole");
h.frames(4);
h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"]}})).unwrap();
}
#[test]
fn hole_presets_name_prompt_keeps_keyboard_when_canvas_requests_value_focus() {
let mut h = personal_preset_harness();
let document = h.app.session.doc.to_json();
let fields = format!("{:?}", h.app.dialog.as_ref().unwrap().kind);
h.step(&json!({"widget":"Save new"})).unwrap();
preset_name(&mut h, "FocusTarget");
h.app.dialog.as_mut().unwrap().restore_value_focus = true;
h.frames(2);
h.step(&json!({"text":"-kept"})).unwrap();
h.step(&json!({"key":"Enter"})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[0]["name"], "FocusTarget-kept");
assert_eq!(h.app.session.doc.to_json(), document);
assert_eq!(format!("{:?}", h.app.dialog.as_ref().unwrap().kind), fields);
}
#[test]
fn hole_presets_name_prompt_cancel_duplicate_invalid_and_prefilled_rename_leave_document_untouched() {
let mut h = personal_preset_harness();
save_preset(&mut h, "Workshop");
let bank = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
let document = serde_json::to_value(&*h.app.session.doc).unwrap();
let form = format!("{:?}", h.app.dialog);
for action in ["Save new", "Rename"] {
h.step(&json!({"widget":action})).unwrap();
preset_name(&mut h, "Discard this");
h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), bank);
assert_eq!(format!("{:?}", h.app.dialog), form);
}
h.step(&json!({"widget":"Save new"})).unwrap();
h.step(&json!({"key":"Escape"})).unwrap();
assert!(h.app.dialog.is_some(), "Escape closes only the name prompt");
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), bank);
h.step(&json!({"widget":"Save new"})).unwrap();
confirm_preset_name(&mut h);
h.step(&json!({"expect":{"shown":"Enter a short name without line breaks or control characters."}})).unwrap();
preset_name(&mut h, "workshop");
confirm_preset_name(&mut h);
h.step(&json!({"expect":{"shown":"A preset with this name already exists. Use a different name."}})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), bank);
h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
h.step(&json!({"widget":"Rename"})).unwrap();
confirm_preset_name(&mut h); // The current name was prefilled; renaming to itself is valid.
h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"]}})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), bank);
h.step(&json!({"widget":"Rename"})).unwrap();
preset_name(&mut h, "Renamed");
h.step(&json!({"key":"Enter"})).unwrap();
assert!(h.app.dialog.is_some(), "Enter confirms the name, never applies the Hole");
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[0]["name"], "Renamed");
assert_eq!(serde_json::to_value(&*h.app.session.doc).unwrap(), document);
assert_eq!(format!("{:?}", h.app.dialog), form);
}
#[test]
fn hole_presets_save_explicit_source_units_including_mm_without_document_edits() {
for unit in ["in", "mm"] {
let mut h = personal_preset_harness();
h.app.session.doc_mut().units = unit.into();
if let Kind::Hole { diameter, depth, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "0.25".into();
*depth = "2 * 3".into();
}
save_preset(&mut h, "Portable");
let presets = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(presets[0]["diameter"], format!("0.25 {unit}"));
assert_eq!(presets[0]["depth"], format!("(2 * 3) * 1 {unit}"));
assert_eq!(h.app.session.doc.features.len(), 1);
assert!(h.app.dialog.is_some());
}
}
#[test]
fn hole_presets_save_rename_delete_and_enter_only_change_the_form_or_profile() {
let mut h = personal_preset_harness();
save_preset(&mut h, "Workshop");
let saved = h.app.prefs();
h.step(&json!({"widget":"Rename"})).unwrap();
preset_name(&mut h, "Renamed");
confirm_preset_name(&mut h);
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[0]["name"], "Renamed");
h.step(&json!({"widget":"Delete"})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap().as_array().unwrap().len(), 1);
h.step(&json!({"widget":"Confirm delete"})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), json!([]));
assert_eq!(h.app.session.doc.features.len(), 1);
let mut other = crate::SolveApp::new(Default::default(), Default::default());
other.load_prefs(&saved);
assert_eq!(serde_json::to_value(&other.preferences.hole_presets).unwrap()[0]["name"], "Workshop");
}
#[test]
fn hole_presets_inactive_incomplete_dimensions_do_not_block_valid_simple_all_preset() {
let mut h = personal_preset_harness();
if let Kind::Hole { diameter, depth, cb_depth, cs_diameter, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "4 mm".into();
*depth = "unfinished(".into();
*cb_depth = "missing_parameter".into();
*cs_diameter = "3 deg".into();
opts.all = true;
}
save_preset(&mut h, "Simple through");
let saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(saved[0]["name"], "Simple through");
assert_eq!(saved[0]["extent"], "all");
assert_eq!(saved[0]["depth"], "unfinished(");
assert_eq!(saved[0]["cb_depth"], "missing_parameter");
assert_eq!(saved[0]["cs_diameter"], "3 deg");
assert_eq!(h.app.session.doc.features.len(), 1);
assert!(h.app.dialog.is_some());
}
#[test]
fn hole_presets_unknown_options_refuse_automatic_recall_without_changing_any_hole_fields() {
let mut h = personal_preset_harness();
save_preset(&mut h, "Future");
let mut saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
saved[0]["thread_options"]["starts"] = json!(2);
h.app.preferences.hole_presets = serde_json::from_value(saved).unwrap();
choose_preset(&mut h, "Select a preset");
if let Kind::Hole { diameter, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*diameter = "9 mm".into();
}
let before = serde_json::to_value(&*h.app.session.doc).unwrap();
let form = format!("{:?}", h.app.dialog);
choose_preset(&mut h, "Future");
assert_eq!(format!("{:?}", h.app.dialog), form, "unsupported options must not partially change the draft");
assert_eq!(serde_json::to_value(&*h.app.session.doc).unwrap(), before);
h.step(&json!({"expect":{"shown":"This preset uses thread options that this version cannot recall."}})).unwrap();
h.step(&json!({"widget":"Rename"})).unwrap();
preset_name(&mut h, "Future renamed");
confirm_preset_name(&mut h);
let retained = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(retained[0]["name"], "Future renamed");
assert_eq!(retained[0]["thread_options"]["starts"], 2);
}
/// A 40 × 30 × 20 block, seen from the top, with a sketch on its top face: a circle of radius 4
/// about (12, 9). Returns the circle centre in the world.
fn block_with_circle() -> (Harness, Vec3) {
@@ -584,3 +877,228 @@ fn a_face_place_snaps_to_the_points_of_shown_geometry_only() {
assert_eq!(taken, if hide { 1 } else { 1 + 4 + 1 }, "the origin, and unless hidden the face's corners and the lost point");
}
}
#[test]
fn combined_recessed_point_presets_keep_left_partial_across_units_and_legacy_defaults() {
use solidcraft_engine::doc::ThreadHandedness;
for recessed in [1, 2] {
let mut h = personal_preset_harness();
if let Kind::Hole { diameter, kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
diameter.clear(); // Inactive for tapped holes; Custom supplies its drill size.
*kind = recessed;
opts.angled = true;
opts.tip_angle = "118 deg".into();
opts.tapped = true;
opts.thread = "M8x1.2".into();
opts.handedness = ThreadHandedness::Left;
opts.thread_full_depth = false;
opts.thread_depth = "5".into();
}
save_preset(&mut h, "Combined point");
let stored = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(stored[0]["angled_bottom"], true);
assert_eq!(stored[0]["thread_options"]["handedness"], "left");
assert_eq!(stored[0]["thread_options"]["depth"], "5 mm");
h.app.preferences.hole_presets = serde_json::from_value(stored.clone()).unwrap();
h.app.session.doc_mut().units = "in".into();
choose_preset(&mut h, "Select a preset");
if let Kind::Hole { kind, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*kind = 0;
opts.angled = false;
opts.handedness = ThreadHandedness::Right;
opts.thread_full_depth = true;
}
let before = h.app.session.doc.to_json();
choose_preset(&mut h, "Combined point");
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {kind,opts,..}
if *kind==recessed && opts.angled && opts.tip_angle=="118 deg" && opts.handedness==ThreadHandedness::Left
&& !opts.thread_full_depth && opts.thread_depth=="5 mm" && opts.thread=="M8x1.2"
&& opts.custom_thread.as_ref().is_none_or(|draft| draft.error.is_none())));
assert_eq!(h.app.session.doc.to_json(), before, "automatic recall only changes the form");
assert!((h.app.session.doc.eval("5 mm", solidcraft_engine::doc::expr::Kind::Length).unwrap() - 5.0).abs() < 1e-9);
// Old recessed presets omit the additive fields: flat, Right and Full remain their defaults.
choose_preset(&mut h, "Select a preset");
let mut legacy = stored.clone();
legacy[0].as_object_mut().unwrap().remove("angled_bottom");
legacy[0].as_object_mut().unwrap().remove("thread_options");
h.app.preferences.hole_presets = serde_json::from_value(legacy).unwrap();
choose_preset(&mut h, "Combined point");
assert!(matches!(&h.app.dialog.as_ref().unwrap().kind, Kind::Hole {kind,opts,..}
if *kind==recessed && !opts.angled && opts.handedness==ThreadHandedness::Right && opts.thread_full_depth));
choose_preset(&mut h, "Select a preset");
let mut future = stored;
future[0]["thread_options"]["starts"] = json!(2);
h.app.preferences.hole_presets = serde_json::from_value(future).unwrap();
let draft = format!("{:?}", h.app.dialog);
choose_preset(&mut h, "Combined point");
assert_eq!(format!("{:?}", h.app.dialog), draft, "unknown options must refuse before changing any bottom/thread field");
}
}
fn preset_dirty_save_enabled(h: &Harness) -> bool {
let node = h
.output
.accesskit_update
.as_ref()
.unwrap()
.nodes
.iter()
.rev()
.find(|(_, node)| node.label() == Some("Save changes to selected preset"))
.map(|(_, node)| node)
.expect("the small Save action must be present");
!node.is_disabled()
}
fn dirty_depth(h: &mut Harness, text: &str) {
if let Kind::Hole { depth, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*depth = text.into();
}
h.frames(3);
}
fn dirty_save(h: &mut Harness) {
h.step(&json!({"click":{"handle":"dialog:hole_presets:overwrite"}})).unwrap();
}
#[test]
fn hole_presets_dirty_indicator_and_disabled_save_follow_changes_and_revert() {
let mut h = personal_preset_harness();
assert!(!preset_dirty_save_enabled(&h));
dirty_depth(&mut h, "12 mm");
save_preset(&mut h, "Workshop");
let library = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
h.frames(8);
assert!(!preset_dirty_save_enabled(&h), "unchanged frames must not dirty a saved preset");
dirty_save(&mut h);
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), library);
dirty_depth(&mut h, "13 mm");
assert!(preset_dirty_save_enabled(&h));
h.step(&json!({"expect":{"shown":"* Workshop"}})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap()[0]["name"], "Workshop");
let field = crate::scenario::rect_of("dialog:widget:hole_presets.preset").unwrap();
let save = crate::scenario::rect_of("dialog:hole_presets:overwrite").unwrap();
assert!(save.left() >= field.right() && save.width() <= 32.0, "small save belongs right of the name");
choose_preset(&mut h, "Select a preset");
assert!(!preset_dirty_save_enabled(&h));
choose_preset(&mut h, "Workshop");
dirty_depth(&mut h, "13 mm");
dirty_depth(&mut h, "12 mm");
assert!(!preset_dirty_save_enabled(&h), "reverting the parameter clears dirty state without saving");
h.step(&json!({"expect":{"not_shown":"* Workshop"}})).unwrap();
}
#[test]
fn hole_presets_dirty_overwrite_keeps_name_and_all_pointed_left_partial_parameters() {
let mut h = personal_preset_harness();
if let Kind::Hole { kind, depth, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*kind = 2;
*depth = "12 mm".into();
opts.angled = true;
opts.tapped = true;
opts.thread = "M8".into();
opts.handedness = solidcraft_engine::doc::ThreadHandedness::Left;
opts.thread_full_depth = false;
opts.thread_depth = "5 mm".into();
}
save_preset(&mut h, "Workshop");
let document = h.app.session.doc.to_json();
dirty_depth(&mut h, "13 mm");
dirty_save(&mut h);
let saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(saved.as_array().unwrap().len(), 1);
assert_eq!(saved[0]["name"], "Workshop");
assert_eq!(saved[0]["depth"], "13 mm");
assert_eq!(saved[0]["angled_bottom"], true);
assert_eq!(saved[0]["thread_options"]["handedness"], "left");
assert_eq!(saved[0]["thread_options"]["depth"], "5 mm");
assert!(!preset_dirty_save_enabled(&h));
h.step(&json!({"expect":{"hidden_handles":["dialog:hole_presets.name"],"not_shown":"* Workshop"}})).unwrap();
assert_eq!(h.app.session.doc.to_json(), document, "overwrite edits only the personal library");
}
#[test]
fn hole_presets_dirty_legacy_drilled_bottom_is_unchanged_after_recall_and_revert() {
let mut h = personal_preset_harness();
dirty_depth(&mut h, "12 mm");
save_preset(&mut h, "Legacy");
let mut saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
assert_eq!(saved[0]["style"], "drilled");
saved[0].as_object_mut().unwrap().remove("angled_bottom");
choose_preset(&mut h, "Select a preset");
h.app.preferences.hole_presets = serde_json::from_value(saved).unwrap();
choose_preset(&mut h, "Legacy");
h.frames(8);
assert!(!preset_dirty_save_enabled(&h), "legacy Drilled implies the same effective angled bottom");
dirty_depth(&mut h, "13 mm");
assert!(preset_dirty_save_enabled(&h));
dirty_depth(&mut h, "12 mm");
assert!(!preset_dirty_save_enabled(&h));
}
#[test]
fn hole_presets_dirty_invalid_expression_refuses_overwrite_and_cancel_changes_no_data() {
let mut h = personal_preset_harness();
dirty_depth(&mut h, "12 mm");
save_preset(&mut h, "Workshop");
let saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
let doc = h.app.session.doc.to_json();
dirty_depth(&mut h, "bad length");
assert!(preset_dirty_save_enabled(&h));
dirty_save(&mut h);
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), saved);
h.step(&json!({"expect":{"shown":"Complete the hole parameters using valid expressions of reasonable length."}})).unwrap();
assert!(preset_dirty_save_enabled(&h));
h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), saved);
assert_eq!(h.app.session.doc.to_json(), doc);
}
#[test]
fn hole_presets_dirty_unknown_options_are_never_dropped_by_overwrite() {
let mut h = personal_preset_harness();
dirty_depth(&mut h, "12 mm");
save_preset(&mut h, "Future");
let mut saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
saved[0]["thread_options"]["starts"] = json!(2);
choose_preset(&mut h, "Select a preset");
h.app.preferences.hole_presets = serde_json::from_value(saved.clone()).unwrap();
choose_preset(&mut h, "Future");
dirty_depth(&mut h, "13 mm");
assert!(preset_dirty_save_enabled(&h));
dirty_save(&mut h);
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), saved);
assert!(preset_dirty_save_enabled(&h));
h.step(&json!({"expect":{"shown":"This preset contains options that cannot be overwritten safely."}})).unwrap();
}
#[test]
fn hole_presets_dirty_invalid_active_scalars_refuse_overwrite() {
for invalid in ["negative depth", "point angle", "countersink angle", "partial depth"] {
let mut h = personal_preset_harness();
if let Kind::Hole { kind, depth, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
*kind = 2;
*depth = "12 mm".into();
opts.tapped = true;
opts.thread = "M8".into();
opts.angled = true;
opts.thread_full_depth = false;
opts.thread_depth = "5 mm".into();
}
save_preset(&mut h, "Workshop");
let saved = serde_json::to_value(&h.app.preferences.hole_presets).unwrap();
if let Kind::Hole { depth, cs_angle, opts, .. } = &mut h.app.dialog.as_mut().unwrap().kind {
match invalid {
"negative depth" => *depth = "-1 mm".into(),
"point angle" => opts.tip_angle = "bad angle".into(),
"countersink angle" => *cs_angle = "0 deg".into(),
_ => opts.thread_depth = "-1 mm".into(),
}
}
h.frames(3);
assert!(preset_dirty_save_enabled(&h));
dirty_save(&mut h);
assert_eq!(serde_json::to_value(&h.app.preferences.hole_presets).unwrap(), saved, "{invalid}");
assert!(preset_dirty_save_enabled(&h));
}
}
+553
View File
@@ -0,0 +1,553 @@
//! Personal, cross-design Hole parameter presets. Geometry references never enter this
//! library; recalling a preset only edits the open dialog, never the document.
use serde::{Deserialize, Serialize, de};
use solidcraft_engine::doc::{DocError, Document, expr};
use std::collections::BTreeMap;
use crate::dialogs::{Dialog, Kind};
use crate::i18n::tr;
use crate::ui_kit::{self, Button, Text};
const MAX_PRESETS: usize = 64;
const MAX_NAME: usize = 96;
const MAX_EXPRESSION: usize = 512;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Style {
Simple,
Drilled,
Counterbore,
Countersink,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Extent {
Distance,
All,
ToObject,
}
/// Additive thread options retain their defaults in older presets. Known options map to
/// the Hole form without design IDs; unknown options survive rename and refuse recall.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
struct ThreadOptions {
handedness: String,
full_length: bool,
depth: Option<String>,
#[serde(flatten)]
unknown: BTreeMap<String, serde_json::Value>,
}
impl Default for ThreadOptions {
fn default() -> Self {
Self { handedness: "right".into(), full_length: true, depth: None, unknown: BTreeMap::new() }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Preset {
name: String,
style: Style,
#[serde(default)]
angled_bottom: bool,
extent: Extent,
diameter: String,
depth: String,
cb_diameter: String,
cb_depth: String,
cs_diameter: String,
cs_angle: String,
tip_angle: String,
tapped: bool,
thread: String,
#[serde(default)]
thread_options: ThreadOptions,
}
fn valid_text(text: &str, max: usize) -> bool {
text.len() <= max && !text.chars().any(char::is_control)
}
fn valid_name(name: &str) -> bool {
!name.trim().is_empty() && name == name.trim() && valid_text(name, MAX_NAME)
}
impl Preset {
fn validate(&self) -> Result<(), &'static str> {
if !valid_name(&self.name) {
return Err("hole_presets.invalid_name");
}
let expressions =
[&self.diameter, &self.depth, &self.cb_diameter, &self.cb_depth, &self.cs_diameter, &self.cs_angle, &self.tip_angle, &self.thread];
if expressions.into_iter().any(|text| !valid_text(text, MAX_EXPRESSION)) {
return Err("hole_presets.invalid_parameters");
}
let mut required = if self.tapped { Vec::new() } else { vec![&self.diameter] };
if self.extent == Extent::Distance {
required.push(&self.depth);
}
match self.style {
Style::Drilled if self.extent != Extent::All => required.push(&self.tip_angle),
Style::Counterbore => required.extend([&self.cb_diameter, &self.cb_depth]),
Style::Countersink => required.extend([&self.cs_diameter, &self.cs_angle]),
Style::Simple | Style::Drilled => {}
}
if self.angled_bottom && self.extent != Extent::All && self.style != Style::Drilled {
required.push(&self.tip_angle);
}
if self.tapped {
required.push(&self.thread);
if !self.thread_options.full_length {
required.push(self.thread_options.depth.as_ref().ok_or("hole_presets.invalid_parameters")?);
}
}
if required.into_iter().any(|text| text.trim().is_empty())
|| !["right", "left"].contains(&self.thread_options.handedness.as_str())
|| self.thread_options.depth.as_ref().is_some_and(|text| !valid_text(text, MAX_EXPRESSION))
|| self.thread_options.unknown.len() > 8
|| self.thread_options.unknown.iter().any(|(key, value)| {
key.is_empty()
|| !valid_text(key, 64)
|| match value {
serde_json::Value::String(text) => !valid_text(text, MAX_EXPRESSION),
serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::Null => false,
_ => true,
}
})
{
return Err("hole_presets.invalid_parameters");
}
Ok(())
}
fn capture(d: &Dialog, name: &str, doc: &Document) -> Result<Self, &'static str> {
let Kind::Hole { diameter, depth, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &d.kind else {
return Err("hole_presets.invalid_parameters");
};
if opts.tapped && opts.custom_thread.as_ref().is_some_and(|draft| draft.error.is_some()) {
return Err("hole_presets.invalid_parameters");
}
let (values, _) = doc.param_values();
let lookup = |name: &str| values.get(name).copied().ok_or_else(|| DocError::Expr(format!("unknown parameter `{name}`")));
let portable_length = |text: &str, active: bool| -> Result<String, &'static str> {
if text.trim().is_empty() {
return Ok(text.into());
}
let checked = expr::eval_with(text, &lookup).and_then(|value| {
value.to_kind(expr::Kind::Length)?;
Ok(value)
});
let value = match checked {
Ok(value) => value,
// Hidden fields may contain an unfinished edit. Keep bounded text for
// later editing; only dimensions used by this style/extent must parse.
Err(_) if !active => return Ok(text.into()),
Err(_) => return Err("hole_presets.invalid_parameters"),
};
if value.unitless() {
let unit = expr::length_unit_or_mm(&doc.units);
// Keep the expression, not its evaluated number. Explicit mm matters too:
// an unsuffixed value would otherwise acquire the destination design's unit.
Ok(if expr::is_bare_number(text) { format!("{} {unit}", text.trim()) } else { format!("({text}) * 1 {unit}") })
} else {
Ok(text.into())
}
};
let preset = Self {
name: name.trim().into(),
style: match *kind {
0 if opts.angled => Style::Drilled,
0 => Style::Simple,
1 => Style::Counterbore,
2 => Style::Countersink,
_ => return Err("hole_presets.invalid_parameters"),
},
angled_bottom: opts.angled,
extent: if d.inputs.iter().any(|input| input.label == "To Object") {
Extent::ToObject
} else if opts.all {
Extent::All
} else {
Extent::Distance
},
diameter: portable_length(diameter, !opts.tapped)?,
depth: portable_length(depth, !opts.all && !d.inputs.iter().any(|input| input.label == "To Object"))?,
cb_diameter: portable_length(cb_diameter, *kind == 1)?,
cb_depth: portable_length(cb_depth, *kind == 1)?,
cs_diameter: portable_length(cs_diameter, *kind == 2)?,
cs_angle: cs_angle.clone(),
tip_angle: opts.tip_angle.clone(),
tapped: opts.tapped,
thread: opts.thread.clone(),
thread_options: if opts.tapped {
ThreadOptions {
handedness: if opts.handedness.is_right() { "right".into() } else { "left".into() },
full_length: opts.thread_full_depth,
depth: if opts.thread_full_depth { None } else { Some(portable_length(&opts.thread_depth, true)?) },
unknown: BTreeMap::new(),
}
} else {
ThreadOptions::default()
},
};
preset.validate()?;
Ok(preset)
}
fn same_parameters(&self, other: &Self) -> bool {
let normalized = |preset: &Self| {
let mut p = preset.clone();
p.name.clear();
p.angled_bottom |= p.style == Style::Drilled;
if p.style == Style::Drilled {
p.style = Style::Simple;
}
// Unknown options cannot be captured by this form and cannot be overwritten.
p.thread_options.unknown.clear();
if !p.tapped {
p.thread_options = ThreadOptions::default();
} else if p.thread_options.full_length {
p.thread_options.depth = None;
}
p
};
normalized(self) == normalized(other)
}
fn validate_active(&self, doc: &Document) -> Result<(), &'static str> {
let length = |text: &str| doc.eval(text, expr::Kind::Length).is_ok_and(|v| v.is_finite() && v > 0.0);
let angle = |text: &str| doc.eval(text, expr::Kind::Angle).is_ok_and(|v| v.is_finite() && v > 0.0 && v < std::f64::consts::PI);
let style_valid = match self.style {
Style::Counterbore => length(&self.cb_diameter) && length(&self.cb_depth),
Style::Countersink => length(&self.cs_diameter) && angle(&self.cs_angle),
Style::Simple | Style::Drilled => true,
};
if !style_valid
|| (!self.tapped && !length(&self.diameter))
|| (self.extent == Extent::Distance && !length(&self.depth))
|| (self.extent != Extent::All && (self.angled_bottom || self.style == Style::Drilled) && !angle(&self.tip_angle))
|| (self.tapped && solidcraft_engine::doc::parse_metric_thread(&self.thread).is_none())
|| (self.tapped && !self.thread_options.full_length && self.thread_options.depth.as_deref().is_none_or(|text| !length(text)))
{
return Err("hole_presets.invalid_parameters");
}
Ok(())
}
fn recall(&self, d: &mut Dialog) -> Result<(), &'static str> {
self.validate()?;
if !self.thread_options.unknown.is_empty() {
return Err("hole_presets.unsupported_options");
}
let Kind::Hole { diameter, depth, kind, cb_diameter, cb_depth, cs_diameter, cs_angle, opts } = &mut d.kind else {
return Err("hole_presets.invalid_parameters");
};
diameter.clone_from(&self.diameter);
depth.clone_from(&self.depth);
*kind = match self.style {
Style::Simple | Style::Drilled => 0,
Style::Counterbore => 1,
Style::Countersink => 2,
};
cb_diameter.clone_from(&self.cb_diameter);
cb_depth.clone_from(&self.cb_depth);
cs_diameter.clone_from(&self.cs_diameter);
cs_angle.clone_from(&self.cs_angle);
// Drilled is the legacy representation; recesses have an independent bottom choice.
opts.angled = self.angled_bottom || self.style == Style::Drilled;
opts.tip_angle.clone_from(&self.tip_angle);
opts.all = self.extent == Extent::All;
opts.tapped = self.tapped;
opts.thread.clone_from(&self.thread);
opts.custom_thread = None;
opts.handedness = if self.thread_options.handedness == "left" {
solidcraft_engine::doc::ThreadHandedness::Left
} else {
solidcraft_engine::doc::ThreadHandedness::Right
};
opts.thread_full_depth = self.thread_options.full_length;
opts.thread_depth = self.thread_options.depth.clone().unwrap_or_else(|| crate::dialogs::HoleOpts::default().thread_depth);
// Existing placement picks stay with this dialog. To Object stores its mode only:
// recalling it always asks for a fresh destination in the current design.
crate::dialogs::preset_to_object(d, self.extent == Extent::ToObject);
Ok(())
}
}
/// Stored as one preference array. A malformed row cannot discard unrelated preferences
/// or valid rows. Bound the retained rows and all user-controlled strings.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[serde(transparent)]
pub struct Library(Vec<Preset>);
impl<'de> Deserialize<'de> for Library {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct LibraryVisitor;
impl<'de> de::Visitor<'de> for LibraryVisitor {
type Value = Library;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an array of personal Hole presets")
}
fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Library, A::Error> {
let mut library = Library::default();
for _ in 0..MAX_PRESETS {
let Some(row) = seq.next_element::<serde_json::Value>()? else { return Ok(library) };
if let Ok(preset) = serde_json::from_value::<Preset>(row)
&& preset.validate().is_ok()
&& library.find(&preset.name).is_none()
{
library.0.push(preset);
}
}
while seq.next_element::<de::IgnoredAny>()?.is_some() {}
Ok(library)
}
}
deserializer.deserialize_seq(LibraryVisitor)
}
}
impl Library {
fn find(&self, name: &str) -> Option<usize> {
let name = name.to_lowercase();
self.0.iter().position(|preset| preset.name.to_lowercase() == name)
}
fn save(&mut self, d: &Dialog, name: &str, doc: &Document) -> Result<(), &'static str> {
if self.find(name.trim()).is_some() {
return Err("hole_presets.name_exists");
}
if self.0.len() >= MAX_PRESETS {
return Err("hole_presets.full");
}
self.0.push(Preset::capture(d, name, doc)?);
Ok(())
}
fn modified(&self, selected: &str, d: &Dialog, doc: &Document) -> bool {
self.find(selected).and_then(|index| self.0.get(index)).is_some_and(|saved| match Preset::capture(d, &saved.name, doc) {
Ok(current) => !current.same_parameters(saved),
Err(_) => true,
})
}
fn overwrite(&mut self, selected: &str, d: &Dialog, doc: &Document) -> Result<(), &'static str> {
let index = self.find(selected).ok_or("hole_presets.missing")?;
let saved = self.0.get(index).ok_or("hole_presets.missing")?;
if !saved.thread_options.unknown.is_empty() {
return Err("hole_presets.unsupported_overwrite");
}
let candidate = Preset::capture(d, &saved.name, doc)?;
candidate.validate_active(doc)?;
// Capture and all validation finish before the existing record is replaced.
*self.0.get_mut(index).ok_or("hole_presets.missing")? = candidate;
Ok(())
}
fn rename(&mut self, old: &str, new: &str) -> Result<(), &'static str> {
let new = new.trim();
if !valid_name(new) {
return Err("hole_presets.invalid_name");
}
let index = self.find(old).ok_or("hole_presets.missing")?;
if self.find(new).is_some_and(|other| other != index) {
return Err("hole_presets.name_exists");
}
let preset = self.0.get_mut(index).ok_or("hole_presets.missing")?;
preset.name = new.into();
Ok(())
}
}
#[derive(Clone)]
struct NamePrompt {
name: String,
renaming: bool,
}
#[derive(Clone, Default)]
struct PanelState {
selected: String,
prompt: Option<NamePrompt>,
confirming_delete: bool,
error: Option<&'static str>,
}
/// One hook above the existing Hole form. Only the library is persisted in preferences;
/// selection, errors and the naming prompt belong to this dialog's temporary UI state.
pub(crate) fn rows(ui: &mut egui::Ui, d: &mut Dialog, library: &mut Library, doc: &Document, reset: bool) {
if !matches!(d.kind, Kind::Hole { .. }) {
return;
}
let id = egui::Id::new("personal_hole_presets_panel");
let mut state = if reset { PanelState::default() } else { ui.ctx().data_mut(|data| data.get_temp::<PanelState>(id)).unwrap_or_default() };
ui_kit::section(ui, "personal_hole_presets", "hole_presets.title", false, |ui| {
ui.label(tr("hole_presets.scope"));
crate::dialogs::form_row(ui, "hole_presets.preset", |ui| {
let before = library.find(&state.selected).map_or(0, |index| index + 1);
let mut selected = before;
let dirty = library.modified(&state.selected, d, doc);
let display = library.find(&state.selected).and_then(|index| library.0.get(index)).map_or_else(
|| tr("hole_presets.select").to_string(),
|preset| {
if dirty { format!("* {}", preset.name) } else { preset.name.clone() }
},
);
let height = ui_kit::row_height();
let width = (ui.available_width() - height - ui.spacing().item_spacing.x).max(1.0);
ui.allocate_ui_with_layout(egui::vec2(width, height), egui::Layout::left_to_right(egui::Align::Center), |ui| {
let response = ui_kit::dropdown_menu(ui, "personal_hole_preset_choice", &display, |ui| {
let placeholder = ui_kit::list_picker(ui, "hole_presets_select", tr("hole_presets.select"), selected == 0);
if placeholder.clicked() {
selected = 0;
}
crate::scenario::publish_handle(&format!("dialog:hole_presets.preset:{}", tr("hole_presets.select")), placeholder.rect.center());
for (index, preset) in library.0.iter().enumerate() {
let option = ui_kit::list_picker(ui, &format!("hole_preset_{index}"), &preset.name, selected == index + 1);
if option.clicked() {
selected = index + 1;
}
crate::scenario::publish_handle(&format!("dialog:hole_presets.preset:{}", preset.name), option.rect.center());
}
});
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, ui.is_enabled(), tr("hole_presets.preset"));
info.current_text_value = Some(display.clone());
info
});
});
if selected != before {
let preset = selected.checked_sub(1).and_then(|index| library.0.get(index));
state.selected = preset.map_or_else(String::new, |preset| preset.name.clone());
state.error = preset.and_then(|preset| preset.recall(d).err());
state.prompt = None;
state.confirming_delete = false;
}
let modified = library.modified(&state.selected, d, doc);
ui.add_enabled_ui(modified, |ui| {
let (rect, _) = ui.allocate_exact_size(egui::vec2(height, height), egui::Sense::hover());
let save = ui_kit::icon_button_at(ui, rect, "save", tr("hole_presets.overwrite"));
crate::scenario::publish_target("dialog:hole_presets:overwrite", save.rect);
if save.clicked() {
state.error = library.overwrite(&state.selected, d, doc).err();
state.confirming_delete = false;
}
});
});
let chosen = library.find(&state.selected);
ui.horizontal_wrapped(|ui| {
if ui_kit::button(ui, tr("hole_presets.save"), Button::Normal).clicked() {
state.prompt = Some(NamePrompt { name: String::new(), renaming: false });
state.error = None;
state.confirming_delete = false;
}
if ui_kit::button(ui, tr("hole_presets.rename"), ui_kit::Button::Enabled(chosen.is_some())).clicked() {
state.prompt = Some(NamePrompt { name: state.selected.clone(), renaming: true });
state.error = None;
state.confirming_delete = false;
}
if ui_kit::button(ui, tr("hole_presets.delete"), ui_kit::Button::Enabled(chosen.is_some())).clicked() {
state.confirming_delete = true;
state.error = None;
}
});
if state.confirming_delete {
ui.label(tr("hole_presets.delete_prompt"));
ui.horizontal_wrapped(|ui| {
if ui_kit::button(ui, tr("hole_presets.confirm_delete"), Button::Normal).clicked() {
if let Some(index) = library.find(&state.selected) {
library.0.remove(index);
}
state = PanelState::default();
}
if ui_kit::button(ui, tr("ui.cancel"), Button::Normal).clicked() {
state.confirming_delete = false;
}
});
}
if state.prompt.is_none()
&& let Some(error) = state.error
{
ui_kit::text(ui, tr(error), Text::Report("hole_presets_error", true));
}
});
ui.ctx().data_mut(|data| data.insert_temp(id, state));
}
/// Global shortcuts run before dialogs. A pending name modal owns their keyboard even
/// when Escape has already blurred its text field. Stale state cannot block other tools.
pub(crate) fn name_prompt_open(ctx: &egui::Context, dialog: Option<&Dialog>) -> bool {
dialog.is_some_and(|d| matches!(&d.kind, Kind::Hole { .. }))
&& ctx.data_mut(|data| data.get_temp::<PanelState>(egui::Id::new("personal_hole_presets_panel"))).is_some_and(|state| state.prompt.is_some())
}
/// Draw after the Hole card so the modal owns input and its footer handles. `true` also
/// covers the confirmation frame: Enter/Cancel must never reach the underlying Hole.
pub(crate) fn name_prompt(ctx: &egui::Context, d: &mut Dialog, library: &mut Library, doc: &Document) -> bool {
if !matches!(d.kind, Kind::Hole { .. }) {
return false;
}
let id = egui::Id::new("personal_hole_presets_panel");
let mut state = ctx.data_mut(|data| data.get_temp::<PanelState>(id)).unwrap_or_default();
let Some(mut prompt) = state.prompt.take() else { return false };
let title = tr(if prompt.renaming { "hole_presets.rename" } else { "hole_presets.save" });
let (closed, action) = ui_kit::Confirm::new(egui::Id::new("personal_hole_preset_name"), "save", title)
.actions(if prompt.renaming { tr("hole_presets.rename") } else { crate::i18n::tr_label("Save") }, "Cancel", None)
.show(ctx, true, |ui| {
ui_kit::row(ui, "hole_presets.name", |ui| ui_kit::focused_text_field(ui, &mut prompt.name, tr("hole_presets.name_hint")));
// Retain over-limit names for a clear validation error, but bound UI storage too.
if prompt.name.len() > MAX_EXPRESSION {
let end = prompt.name.char_indices().map(|(index, _)| index).take_while(|index| *index <= MAX_EXPRESSION).last().unwrap_or(0);
prompt.name.truncate(end);
}
if let Some(error) = state.error {
ui_kit::text(ui, tr(error), Text::Report("hole_presets_name_error", true));
}
});
ctx.input_mut(|input| {
input.consume_key(egui::Modifiers::NONE, egui::Key::Enter);
input.consume_key(egui::Modifiers::NONE, egui::Key::Escape);
});
if closed || action == ui_kit::Action::Cancel {
state.error = None;
} else if action == ui_kit::Action::Ok {
state.error = if prompt.renaming { library.rename(&state.selected, &prompt.name).err() } else { library.save(d, &prompt.name, doc).err() };
if state.error.is_none() {
state.selected = prompt.name.trim().into();
} else {
state.prompt = Some(prompt);
}
} else {
state.prompt = Some(prompt);
}
ctx.data_mut(|data| data.insert_temp(id, state));
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hole_presets_recall_preserves_current_reference_distances() {
let harness = crate::scenario::Harness::new();
let mut dialog = Dialog::for_command(&harness.app, "solid.hole").unwrap();
let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("expected Hole") };
opts.refs.distance = ["10 mm".into(), "12 mm".into()];
let preset = Preset::capture(&dialog, "Portable", &Document::default()).unwrap();
let saved = serde_json::to_value(&preset).unwrap();
assert!(saved.get("references").is_none() && saved.get("refs").is_none());
let Kind::Hole { opts, .. } = &mut dialog.kind else { panic!("expected Hole") };
opts.refs.distance = ["17 mm".into(), "18 mm".into()];
let references = opts.refs.clone();
let inputs = dialog.inputs.clone();
preset.recall(&mut dialog).unwrap();
let Kind::Hole { opts, .. } = &dialog.kind else { panic!("expected Hole") };
assert_eq!(*opts.refs, *references);
assert_eq!(dialog.inputs, inputs);
}
}
+1
View File
@@ -73,6 +73,7 @@ pub(crate) mod hole_place;
mod hole_place_ui_tests;
#[cfg(test)]
mod hole_placement_ui_tests;
pub mod hole_presets;
pub(crate) mod hole_refs;
#[cfg(test)]
mod hole_refs_ui_tests;
+65
View File
@@ -677,6 +677,9 @@ preference_settings! {
/// The variant last started in each split tool family (Rectangle, Circle, Arc, Slot, Polygon, Line,
/// Spline): the family's button and shortcut start it again (`sketch_families`).
sketch_variants: crate::sketch_families::Choices = crate::sketch_families::Choices::default();
/// Personal Hole parameter combinations, shared by every design in this profile.
/// No page reset discards this user-authored library.
hole_presets: crate::hole_presets::Library = crate::hole_presets::Library::default();
save_mesh_format: String = "stl".into();
/// Hidden edges in the current-view DXF export (false: omit, true: dashed).
view_dxf_dashed: bool = false;
@@ -3396,6 +3399,68 @@ mod tests {
assert!(app.session.auto_project);
}
fn hole_preset_row(name: &str) -> serde_json::Value {
serde_json::json!({
"name": name, "style": "counterbore", "extent": "distance",
"diameter": "shaft_diameter + 0.2 mm", "depth": "0.5 in",
"cb_diameter": "10 mm", "cb_depth": "3 mm", "cs_diameter": "10 mm",
"cs_angle": "90 deg", "tip_angle": "118 deg", "tapped": true, "thread": "M5"
})
}
#[test]
fn hole_presets_corrupt_rows_and_limits_do_not_discard_other_preferences() {
use serde_json::json;
let good = hole_preset_row("Workshop");
let mut oversized = hole_preset_row("Too long");
oversized["diameter"] = json!("x".repeat(513));
let mut duplicate = good.clone();
duplicate["name"] = json!("WORKSHOP");
let p = super::lenient(&json!({"length_decimals":4,"hole_presets":[null,good,oversized,duplicate,{"name":"incomplete"}]}));
assert_eq!(p.length_decimals, 4);
let rows = serde_json::to_value(&p.hole_presets).unwrap();
assert_eq!(rows.as_array().unwrap().len(), 1);
assert_eq!(rows[0]["name"], "Workshop");
assert_eq!(rows[0]["diameter"], "shaft_diameter + 0.2 mm");
assert_eq!(rows[0]["depth"], "0.5 in");
let corrupt = super::lenient(&json!({"length_decimals":3,"hole_presets":{"unexpected":true}}));
assert_eq!(corrupt.length_decimals, 3);
assert_eq!(serde_json::to_value(corrupt.hole_presets).unwrap(), json!([]));
let many: Vec<_> = (0..100).map(|i| hole_preset_row(&format!("Preset {i}"))).collect();
let capped = super::lenient(&json!({"hole_presets":many}));
assert_eq!(serde_json::to_value(capped.hole_presets).unwrap().as_array().unwrap().len(), 64);
}
#[test]
fn hole_presets_survive_application_preferences_roundtrip_and_page_resets() {
use serde_json::json;
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
let mut row = hole_preset_row("Fixture");
row["thread_options"] = json!({"handedness":"left","full_length":false,"depth":"4 mm"});
super::set(&mut app, &json!({"hole_presets":[row]})).unwrap();
let expected = serde_json::to_value(&app.preferences.hole_presets).unwrap();
assert_eq!(expected[0]["thread_options"]["handedness"], "left");
for page in 0..super::PAGES.len() {
super::reset_preferences(&mut app.preferences, page);
}
assert_eq!(serde_json::to_value(&app.preferences.hole_presets).unwrap(), expected);
let saved = app.prefs();
let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
other.load_prefs(&saved);
assert_eq!(serde_json::to_value(&other.preferences.hole_presets).unwrap(), expected);
assert!(other.session.doc.features.is_empty());
}
#[test]
fn hole_presets_keep_unknown_thread_options_for_safe_future_recall() {
use serde_json::json;
let mut row = hole_preset_row("Newer version");
row["thread_options"] = json!({"starts":2});
let p = super::lenient(&json!({"hole_presets":[row]}));
let saved = serde_json::to_value(p.hole_presets).unwrap();
assert_eq!(saved[0]["thread_options"]["starts"], 2, "unknown thread semantics must not silently become the defaults");
}
/// The interface font (#1290): a font that can be read, or empty for the built-in one; saved
/// with the others and reset by Restore Defaults.
#[test]
+6 -1
View File
@@ -1999,7 +1999,12 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
}
// A dimension value that is taking the keyboard: letters belong to it (a parameter name
// starting with L or D), even on the frame before its field holds the focus.
if egui::Popup::is_any_open(ctx) || ctx.egui_wants_keyboard_input() || crate::dim_view::editing() || crate::dialogs_save_mesh::popup_open(ctx) {
if egui::Popup::is_any_open(ctx)
|| ctx.egui_wants_keyboard_input()
|| crate::dim_view::editing()
|| crate::dialogs_save_mesh::popup_open(ctx)
|| crate::hole_presets::name_prompt_open(ctx, app.dialog.as_ref())
{
return;
}
let (keys, mods) = ctx.input(|i| {
+57
View File
@@ -0,0 +1,57 @@
# Personal Hole presets
Open **Hole**, expand **Personal presets**, and choose **Save new**. Enter a name
in the confirmation prompt to store the current hole parameters in this application's personal profile. The presets are
available in every project using that profile and survive restarting the application.
Selecting a different saved name immediately fills the open Hole form. The same
selection is not reapplied every frame, so subsequent manual edits stay intact.
A modified selected preset displays `* ` before its name. The small Save icon to the
right overwrites that same preset without a naming prompt; it is disabled when no
preset is selected or the parameters are unchanged. Reverting the parameters clears
the marker. A successful save clears the marker and disables Save again. Invalid
active values or unrecognized future options report an error without replacing the
stored preset. The marker is display-only and never becomes part of the preset name.
Each newly opened Hole starts with no selected preset. Recall does not create or edit a feature;
the normal Hole **OK/Apply** operation validates and commits it. Cancel closes the
Hole form without changing the model. Saving, renaming or deleting a personal preset
is a preference change, independent of cancelling the Hole operation.
Presets include simple or drilled holes, counterbores, countersinks, tapping and
the extent mode. Dimensions, thread designations, expression text and explicit units
and the independent flat/angled bottom choice are retained without baking them into numeric results. Implicit length units are
written explicitly when saving, including mm; unitless expressions keep their text
inside an explicit unit expression. An expression using a named project parameter is evaluated
in the destination project by the normal Hole operation; the preset does not copy
that project's parameters.
Positions, faces, sketch identifiers, placement mode, target bodies, direction picks,
history and connection data are excluded. **To Object** retains only the extent
choice and requires a fresh destination selection after selecting the preset. Current placement
picks remain in the open form.
Use **Rename** to open a name prompt prefilled with the selected name. Confirm
to rename it; Cancel leaves the library and Hole form unchanged. Empty, overlong
or duplicate names report an error in the prompt. **Delete** asks for a second
confirmation and removes only the personal preset. Neither operation edits existing
holes. Names are unique ignoring case. **Save new** with an existing name reports a conflict
instead of replacing it silently; the adjacent Save icon explicitly updates the selected preset.
The library is limited to 64 entries, names to 96 UTF-8 bytes and each parameter
expression to 512 UTF-8 bytes. Malformed saved rows are ignored without discarding
other valid preferences. Preference-page resets do not erase the library. There is
no design-file format change or dependency on a project, PDM service or connection.
Older drilled presets still imply an angled bottom; older recess presets default to flat.
Presets retain Right/Left thread direction and Full/Partial tapping independently
of drill depth. Partial-depth expressions carry explicit source units, so recalling
an mm preset in an inch design keeps the same physical depth. Older records without
these options retain Right/Full defaults. A recalled preset clears an unfinished
Custom thread draft; saving an invalid active Custom draft reports an error instead
of saving its last valid value. Inactive diameter and full-depth fields do not block
saving a valid tapped preset.
Unrecognized future thread options survive renaming and serialization. Recall
rejects them before changing any Hole field, rather than silently discarding them.