1use std::collections::HashMap;
58
59use eframe::egui;
60use serde_json::Value;
61
62use crate::automation::hit_keys::HitKeyDoc;
63use crate::workbench::ecad::{Editors, Target};
64use brep_render::brep_kernel::{self, PinPointReport, PortDeclaration};
65use brep_render::engine_state::{EngineState, MountPick, PortRefField};
66
67const GLYPH_SELECT: &str = "\u{25CE}"; const GLYPH_REMOVE: &str = "\u{2715}"; const GLYPH_ADD: &str = "\u{FF0B}"; const GLYPH_PICK: &str = "\u{2316}"; const GLYPH_PRESENT: &str = "\u{25CF}"; const GLYPH_ABSENT: &str = "\u{25CB}"; const PURPOSES: [&str; 3] = ["pcb", "wiring", "piping"];
81
82const WARN_COLOR: egui::Color32 = egui::Color32::from_rgb(0xd2, 0x99, 0x22);
84const ERROR_COLOR: egui::Color32 = egui::Color32::from_rgb(0xf8, 0x51, 0x49);
85const OK_COLOR: egui::Color32 = egui::Color32::from_rgb(0x3f, 0xb9, 0x50);
86const REMOVE_RED: egui::Color32 = egui::Color32::from_rgb(0xd8, 0x54, 0x4f);
88
89const MODEL_WORKBENCH: &str = "wireHarness";
94
95const MODEL_SURFACE: &str = "model";
98
99enum Edit {
101 GroupName(usize, String),
102 GroupPurpose(usize, String),
103 GroupUnit(usize, Option<u32>),
104 AddGroup,
105 RemoveGroup(usize),
106 PointName(usize, usize, String),
107 PointText(usize, usize, &'static str, String),
110 PointTransform(usize, usize, &'static str, usize, String),
113 PointReverse(usize, usize, bool),
114 AddPoint(usize),
115 RemovePoint(usize, usize),
116}
117
118#[derive(Clone, Debug, PartialEq)]
120enum MountEdit {
121 Pose([f64; 3], [f64; 3], String),
124 YUpToZUp,
126 Reset,
127 Pick(MountPick),
130 Align,
133}
134
135#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
138struct AlignOutcome {
139 written: Option<Value>,
141 largest: Option<f64>,
144 rms: Option<f64>,
145 worst: Option<String>,
146 pins: usize,
147 notes: Vec<String>,
148 error: Option<String>,
150}
151
152fn apply_mount(engine: &mut EngineState, edit: MountEdit) {
156 if let MountEdit::Pick(pick) = edit {
157 engine.begin_ref_select_for_mount(pick);
158 return;
159 }
160 let current = engine
161 .history
162 .mount_block()
163 .and_then(|block| brep_kernel::mount_from_block(block).ok());
164 let (mount, coalesce) = match edit {
165 MountEdit::Reset | MountEdit::Pick(_) | MountEdit::Align => (None, None),
166 MountEdit::Pose(translate, rotate, field) => {
167 let pose = serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate });
168 (brep_kernel::mount_from_block(&pose).ok(), Some(format!("field:{field}")))
169 }
170 MountEdit::YUpToZUp => {
171 let turn = brep_kernel::mount_from_block(&serde_json::json!({ "rotateEulerDeg": [90.0, 0.0, 0.0] }));
172 let composed = turn.and_then(|turn| match current {
173 Some(current) => turn.compose(¤t),
174 None => Ok(turn),
175 });
176 (composed.ok(), None)
177 }
178 };
179 let block = mount.as_ref().and_then(brep_kernel::mount_block_of);
180 if block.as_ref() == engine.history.mount_block() {
181 return;
182 }
183 engine.history.set_mount_block(block, coalesce.as_deref());
184}
185
186#[derive(Clone, Copy, PartialEq, Eq)]
188enum Jump {
189 Symbol,
190 Pads,
191 Model,
192}
193
194pub struct QualifyPanel {
196 hits: HashMap<String, egui::Rect>,
197 selected: Option<String>,
201 adopted: Option<(&'static str, String)>,
206 gizmo_armed_for: Option<String>,
212 pin_seats: Vec<super::pin_seats::PinSeat>,
215 pin_seats_at: Option<(u64, u64)>,
216 mount: Option<Value>,
218 align: Option<AlignOutcome>,
220}
221
222impl Default for QualifyPanel {
223 fn default() -> Self {
224 Self::new()
225 }
226}
227
228impl QualifyPanel {
229 pub fn new() -> Self {
230 Self { hits: HashMap::new(), selected: None, adopted: None, gizmo_armed_for: None, pin_seats: Vec::new(), pin_seats_at: None, mount: None, align: None }
231 }
232
233 pub fn hits_json(&self) -> String {
234 crate::automation::hit_rects::hits_json(&self.hits)
235 }
236
237 pub fn clear_hits(&mut self) {
240 self.hits.clear();
241 }
242
243 pub fn state_json(&self) -> String {
246 serde_json::json!({
247 "selected": self.selected,
248 "gizmoArmedFor": self.gizmo_armed_for,
249 "pinSeats": self.pin_seats,
250 "mount": self.mount,
251 "align": self.align,
252 })
253 .to_string()
254 }
255
256 pub fn show(
259 &mut self,
260 ui: &mut egui::Ui,
261 engine: &mut EngineState,
262 ecad: &mut Editors,
263 target: Option<Target>,
264 ) {
265 self.hits.clear();
266 self.hits.insert("qualify:panel:clip".into(), ui.clip_rect());
267
268 let groups: Vec<PortDeclaration> = engine
269 .history
270 .ports_block()
271 .cloned()
272 .and_then(|block| serde_json::from_value(block).ok())
273 .unwrap_or_default();
274
275 let at = (engine.applied_generation(), engine.history.revision());
276 if self.pin_seats_at != Some(at) {
277 self.pin_seats = super::pin_seats::pin_seats(engine);
278 self.mount = engine.history.mount_block().cloned();
279 self.pin_seats_at = Some(at);
280 }
281
282 self.adopt_editor_selection(engine, ecad, target);
284 if let Some(address) = &self.selected {
287 if !groups.iter().any(|group| {
288 group.points.iter().any(|point| &brep_kernel::port_address(&group.name, &point.name) == address)
289 }) {
290 self.selected = None;
291 }
292 }
293
294 let mut edit: Option<(Edit, Option<String>)> = None;
295 let mut jump: Option<Jump> = None;
296 let mut pick: Option<Option<String>> = None;
297 let mut refs: Option<(String, PortRefField, bool)> = None;
300
301 let points: usize = groups.iter().map(|group| group.points.len()).sum();
303 ui.horizontal(|ui| {
304 let add = ui
305 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add group")).small())
306 .on_hover_text("Declare another port group on this part — a second connector, or a port with a different purpose");
307 self.hits.insert("qualify:add_group".into(), add.rect);
308 if add.clicked() {
309 edit = Some((Edit::AddGroup, None));
310 }
311 ui.label(
312 egui::RichText::new(format!(
313 "{} group{} | {points} point{}",
314 groups.len(),
315 if groups.len() == 1 { "" } else { "s" },
316 if points == 1 { "" } else { "s" },
317 ))
318 .weak(),
319 );
320 });
321 if self.selected.is_none() {
322 let hint = ui.label(
325 egui::RichText::new(
326 "Select a point to place it, seat it on geometry and cross to its pin and pad",
327 )
328 .weak()
329 .small(),
330 );
331 self.hits.insert("qualify:hint".into(), hint.rect);
332 }
333 ui.add_space(2.0);
334
335 for (gi, group) in groups.iter().enumerate() {
337 egui::Frame::group(ui.style())
338 .inner_margin(egui::Margin::same(4))
339 .show(ui, |ui| {
340 let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
345 ui.set_width(ui.available_width().min(room));
346 if let Some(asked) = self.group_header(ui, gi, group) {
347 edit = Some(asked);
348 }
349 for (pi, point) in group.points.iter().enumerate() {
350 let address = brep_kernel::port_address(&group.name, &point.name);
351 let selected = self.selected.as_deref() == Some(address.as_str());
352 if let Some(asked) = self
353 .point_row(ui, engine, gi, pi, point, &address, selected, &mut pick)
354 {
355 edit = Some(asked);
356 }
357 if let Some(seat) = self.pin_seats.iter().find(|seat| seat.address == address).cloned() {
358 self.pin_seat_line(ui, &seat);
359 }
360 if selected {
361 if let Some(asked) = self
362 .point_fields(ui, engine, gi, pi, point, &address, target, &mut refs)
363 {
364 edit = Some(asked);
365 }
366 if let Some(asked) = self.jump_row(ui, &address, target) {
367 jump = Some(asked);
368 }
369 }
370 }
371 let add = ui
372 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add point")).small())
373 .on_hover_text("Add a connection point to this group. It arrives at the part origin, facing +X; place it below.");
374 self.hits.insert(format!("qualify:group:{gi}:add_point"), add.rect);
375 if add.clicked() {
376 edit = Some((Edit::AddPoint(gi), None));
377 }
378 });
379 }
380
381 let mount_edit = self.mount_section(ui, engine, target.is_none());
383
384 ui.add_space(4.0);
386 self.reports(ui, engine);
387
388 if let Some(pick) = pick {
390 self.pick(engine, ecad, target, pick);
391 }
392 if let Some((address, field, enter)) = refs {
393 match enter {
394 true => engine.begin_ref_select_for_port_point(&address, field),
395 false => engine.clear_port_point_ref(&address, field),
396 }
397 }
398 if let Some((edit, coalesce)) = edit {
399 self.apply(engine, edit, coalesce.as_deref());
400 }
401 if let Some(jump) = jump {
402 self.jump(engine, ecad, jump);
403 }
404 match mount_edit {
405 Some(MountEdit::Align) => self.align_mount(engine),
406 Some(mount_edit) => apply_mount(engine, mount_edit),
407 None => {}
408 }
409 self.follow_gizmo(engine, target);
411 }
412
413 fn follow_gizmo(&mut self, engine: &mut EngineState, target: Option<Target>) {
421 let wanted = match target.is_none() && !engine.ref_select_active() {
422 true => self.selected.clone(),
423 false => None,
424 };
425 let refusal = wanted
442 .as_deref()
443 .and_then(|address| engine.port_point_gizmo_refusal(address));
444 let settled = wanted == self.gizmo_armed_for
445 && (wanted.is_none() || engine.transform_armed() || refusal.is_some());
446 if settled {
447 return;
448 }
449 self.gizmo_armed_for = wanted.clone();
450 match wanted {
451 Some(address) => {
455 engine.arm_transform_for_port_point(&address);
456 }
457 None => {
461 if engine.transform_armed_port_point().is_some() {
462 engine.disarm_transform();
463 }
464 }
465 }
466 }
467
468 fn pick(
479 &mut self,
480 engine: &mut EngineState,
481 ecad: &mut Editors,
482 target: Option<Target>,
483 address: Option<String>,
484 ) {
485 self.selected = address.clone();
486 match target {
487 Some(target) => {
488 if let Some((_, name)) =
492 address.as_deref().and_then(brep_kernel::split_address)
493 {
494 ecad.focus(target, name.to_string());
495 ecad.apply_focus(target);
496 }
497 self.adopted = editor_selection(ecad, target)
503 .map(|held| (surface_of(target), held));
504 }
505 None => {
509 if let Some(address) = address.as_deref() {
510 if resolved(engine, address) {
511 engine.select_by_name("solid", address);
512 }
513 }
514 self.adopted = engine
520 .selected_port_point()
521 .map(|held| (MODEL_SURFACE, held));
522 }
523 }
524 }
525
526 fn group_header(
528 &mut self,
529 ui: &mut egui::Ui,
530 gi: usize,
531 group: &PortDeclaration,
532 ) -> Option<(Edit, Option<String>)> {
533 let mut asked = None;
534 ui.horizontal(|ui| {
535 let mut name = group.name.clone();
536 let field = ui
537 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
538 .on_hover_text("The group's name — the first half of every address in it (`J1` in `J1.VCC`). `:`, `.` and `/` are refused.");
539 self.hits.insert(format!("qualify:group:{gi}:name"), field.rect);
540 if field.changed() {
541 asked = Some((Edit::GroupName(gi, name), Some(format!("group:{gi}:name"))));
542 }
543
544 let mut purpose = group.purpose.clone();
545 let combo = egui::ComboBox::from_id_salt(("qualify-purpose", gi))
546 .selected_text(if purpose.is_empty() { "purpose" } else { purpose.as_str() })
547 .width(76.0)
548 .show_ui(ui, |ui| {
549 let mut offered: Vec<String> =
555 PURPOSES.iter().map(|p| (*p).to_string()).collect();
556 if !group.purpose.is_empty() && !PURPOSES.contains(&group.purpose.as_str()) {
557 offered.push(group.purpose.clone());
558 }
559 for candidate in offered {
560 let item = ui.selectable_label(purpose == candidate, &candidate);
561 self.hits
562 .insert(format!("qualify:group:{gi}:purpose:{candidate}"), item.rect);
563 if item.clicked() {
564 purpose = candidate;
565 }
566 }
567 });
568 self.hits.insert(format!("qualify:group:{gi}:purpose"), combo.response.rect);
569 if purpose != group.purpose {
570 asked = Some((Edit::GroupPurpose(gi, purpose), None));
571 }
572
573 ui.label(egui::RichText::new("unit").weak());
574 let mut unit = group.symbol_unit.map(|unit| unit.to_string()).unwrap_or_default();
575 let field = ui
576 .add(egui::TextEdit::singleline(&mut unit).desired_width(24.0))
577 .on_hover_text("The SYMBOL UNIT whose pins bind into this group, 1-based. Empty binds no pins — which is right for a piping port — unless this is the part's only group, when it takes unit 1.");
578 self.hits.insert(format!("qualify:group:{gi}:unit"), field.rect);
579 if field.changed() {
580 let parsed = unit.trim().parse::<u32>().ok();
581 if parsed.is_some() || unit.trim().is_empty() {
585 asked = Some((Edit::GroupUnit(gi, parsed), Some(format!("group:{gi}:unit"))));
586 }
587 }
588
589 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
590 let remove = ui
591 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
592 .on_hover_text("Remove this group and every point in it — and the pins bound to them");
593 self.hits.insert(format!("qualify:group:{gi}:remove"), remove.rect);
594 if remove.clicked() {
595 asked = Some((Edit::RemoveGroup(gi), None));
596 }
597 });
598 });
599 asked
600 }
601
602 #[allow(clippy::too_many_arguments)]
607 fn point_row(
608 &mut self,
609 ui: &mut egui::Ui,
610 engine: &EngineState,
611 gi: usize,
612 pi: usize,
613 point: &brep_kernel::PortPoint,
614 address: &str,
615 selected: bool,
616 pick: &mut Option<Option<String>>,
617 ) -> Option<(Edit, Option<String>)> {
618 let mut asked = None;
619 ui.horizontal(|ui| {
620 let label = crate::icon_text::selectable_icon_label(ui, selected, GLYPH_SELECT)
621 .on_hover_text(format!("Select {address} — it lights up on the surface you are on, its fields open below, and the jump buttons carry it to the others"));
622 self.hits.insert(format!("qualify:point:{gi}:{pi}:select"), label.rect);
623 if label.clicked() {
624 *pick = Some((!selected).then(|| address.to_string()));
625 }
626 let mut name = point.name.clone();
627 let field = ui
628 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
629 .on_hover_text("The point's name, which is its identity: the symbol pin of this name in this group's unit binds to it, and the pad of that number follows.");
630 self.hits.insert(format!("qualify:point:{gi}:{pi}:name"), field.rect);
631 if field.changed() {
632 asked = Some((Edit::PointName(gi, pi, name), Some(format!("point:{gi}:{pi}:name"))));
633 }
634 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
635 let remove = ui
636 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
637 .on_hover_text("Remove this connection point — and the pin bound to it");
638 self.hits.insert(format!("qualify:point:{gi}:{pi}:remove"), remove.rect);
639 if remove.clicked() {
640 asked = Some((Edit::RemovePoint(gi, pi), None));
641 }
642 ui.add_space(4.0);
643 self.presence(ui, engine, gi, pi, address, &point.name);
644 });
645 });
646 asked
647 }
648
649 fn point_fields(
658 &mut self,
659 ui: &mut egui::Ui,
660 engine: &EngineState,
661 gi: usize,
662 pi: usize,
663 point: &brep_kernel::PortPoint,
664 address: &str,
665 target: Option<Target>,
666 refs: &mut Option<(String, PortRefField, bool)>,
667 ) -> Option<(Edit, Option<String>)> {
668 let mut asked = None;
669 let mapped = point
675 .maps_to
676 .as_deref()
677 .map(str::trim)
678 .is_some_and(|target| !target.is_empty());
679 ui.indent(("qualify-point", gi, pi), |ui| {
680 if mapped {
681 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
682 asked = Some(mapped_asked);
683 }
684 self.seat_line(ui, engine, address, point);
685 return;
686 }
687 let seat_fields: &[(PortRefField, &str, &str)] = &[
691 (PortRefField::Point, "Point", "The geometry this point SITS on: a face, an edge, a circle's centre, a vertex, a datum frame. Pick it in the 3D view with \u{2316}. Empty places the point by the offset below alone."),
692 (PortRefField::Direction, "Direction", "The geometry it FACES along: a face's normal, a bore's axis, an edge, a datum frame. Empty takes the direction the point reference implies, or +X. Seat the POINT first where you can: a direction on its own still re-reads the offset in its own axes, so a placement you typed is zeroed rather than turned."),
693 (PortRefField::Body, "Body", "The SOLID that is this point's contact, when a pin is a whole body (an XLR pin, a jack sleeve, a crimp). It seats what Point and Direction leave empty: the point at the body's wire end, facing out along its axis. Pick it in the 3D view with \u{2316}."),
694 ];
695 self.section(ui, "Seated on");
696 for &(field, caption, hover) in seat_fields {
697 ui.horizontal(|ui| {
698 ui.label(egui::RichText::new(caption).weak());
699 let key = field.key();
700 let mut text = optional_text(point, key);
701 let field_ui = ui
702 .add(egui::TextEdit::singleline(&mut text).desired_width(120.0))
703 .on_hover_text(hover);
704 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field_ui.rect);
705 if field_ui.changed() {
706 asked = Some((
707 Edit::PointText(gi, pi, key, text),
708 Some(format!("point:{gi}:{pi}:{key}")),
709 ));
710 }
711 let pickable = target.is_none();
715 let pick = ui
716 .add_enabled(
717 pickable,
718 crate::icon_text::icon_button(ui, GLYPH_PICK).small(),
719 )
720 .on_hover_text("Pick it in the 3D view")
721 .on_disabled_hover_text("Go to the 3D model to pick geometry");
722 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:pick"), pick.rect);
723 if pick.clicked() {
724 *refs = Some((address.to_string(), field, true));
725 }
726 let has = !optional_text(point, key).trim().is_empty();
727 let clear = ui
728 .add_enabled(
729 has,
730 crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small(),
731 )
732 .on_hover_text("Unseat it — the offset below stays as it is, read from the part origin");
733 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:clear"), clear.rect);
734 if clear.clicked() {
735 *refs = Some((address.to_string(), field, false));
736 }
737 });
738 }
739 self.seat_line(ui, engine, address, point);
740 if let Some(flip) = self.contact_line(ui, engine, gi, pi, address, point) {
741 asked = Some(flip);
742 }
743
744 self.section(ui, "Placement");
746 let seated = point.point_ref.is_some()
747 || point.direction_ref.is_some()
748 || point.contact_body.is_some();
749 for (key, caption, hover) in [
750 ("position", "Offset", if seated {
751 "Where the point sits RELATIVE TO ITS SEAT, in millimetres: x runs along the direction the reference gives, y and z across it. A component that is not a number is kept as an EXPRESSION."
752 } else {
753 "Where the point sits, in millimetres from the part origin. Seat it on geometry above and these become an offset from that. A component that is not a number is kept as an EXPRESSION."
754 }),
755 ("rotationEuler", "Angle", if seated {
756 "The rotation applied to the seat's own axes to get the direction a wire leaves along, in degrees. All zero means \"straight out along the reference\"."
757 } else {
758 "The rotation applied to +X to get the direction a wire leaves along, in degrees."
759 }),
760 ] {
761 ui.horizontal(|ui| {
762 ui.label(egui::RichText::new(caption).weak());
763 for axis in 0..3 {
764 let mut text = transform_component(point, key, axis);
765 let field = ui
766 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
767 .on_hover_text(hover);
768 self.hits
769 .insert(format!("qualify:point:{gi}:{pi}:{key}{axis}"), field.rect);
770 if field.changed() {
771 asked = Some((
772 Edit::PointTransform(gi, pi, key, axis, text),
773 Some(format!("point:{gi}:{pi}:{key}{axis}")),
774 ));
775 }
776 }
777 });
778 }
779 self.gizmo_line(ui, engine, address, target);
780
781 self.section(ui, "Wire");
783 ui.horizontal(|ui| {
784 for (key, caption, hover) in [
785 ("extension", "Extension", "The straight run a wire keeps before it may bend. Empty takes the default."),
786 ("displayLength", "Drawn", "How long the point's line is drawn. Empty takes the default."),
787 ] {
788 ui.label(egui::RichText::new(caption).weak());
789 let mut text = optional_text(point, key);
790 let field = ui
791 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
792 .on_hover_text(hover);
793 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field.rect);
794 if field.changed() {
795 asked = Some((
796 Edit::PointText(gi, pi, key, text),
797 Some(format!("point:{gi}:{pi}:{key}")),
798 ));
799 }
800 }
801 });
802 let mut reverse = point.reverse_direction;
803 let toggle = ui
804 .checkbox(&mut reverse, "Leaves the other way")
805 .on_hover_text("Flip the direction a wire leaves along, without disturbing the seat");
806 self.hits.insert(format!("qualify:point:{gi}:{pi}:reverse"), toggle.rect);
807 if toggle.changed() {
808 asked = Some((Edit::PointReverse(gi, pi, reverse), None));
809 }
810
811 if !engine.assembly_components().is_empty() {
816 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
817 asked = Some(mapped_asked);
818 }
819 }
820 });
821 asked
822 }
823
824 fn maps_to_field(
827 &mut self,
828 ui: &mut egui::Ui,
829 gi: usize,
830 pi: usize,
831 point: &brep_kernel::PortPoint,
832 ) -> Option<(Edit, Option<String>)> {
833 let mut asked = None;
834 self.section(ui, "Assembly");
835 ui.horizontal(|ui| {
836 ui.label(egui::RichText::new("Maps to").weak());
837 let mut text = optional_text(point, "mapsTo");
838 let field = ui
839 .add(egui::TextEdit::singleline(&mut text).desired_width(130.0))
840 .on_hover_text("The descendant point this one IS, by address (`ACOMP2:J5.VCC`). It takes the target's resolved placement, so the interface follows the child — and this point has no seat, no offset and no handles of its own. Clear it to place this point here instead.");
841 self.hits.insert(format!("qualify:point:{gi}:{pi}:mapsTo"), field.rect);
842 if field.changed() {
843 asked = Some((
844 Edit::PointText(gi, pi, "mapsTo", text),
845 Some(format!("point:{gi}:{pi}:mapsTo")),
846 ));
847 }
848 });
849 asked
850 }
851
852 fn mount_section(&mut self, ui: &mut egui::Ui, engine: &EngineState, pickable: bool) -> Option<MountEdit> {
859 if engine.history.pads_block().is_none() {
860 return None;
861 }
862 let mut asked = None;
863 ui.add_space(4.0);
864 egui::Frame::group(ui.style()).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
865 let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
866 ui.set_width(ui.available_width().min(room));
867 self.section(ui, "Mount on board");
868 let block = engine.history.mount_block();
869 let pose = match block.map(brep_kernel::mount_from_block).transpose() {
870 Ok(mount) => mount.map(|mount| brep_kernel::transform_to_pose_params(&mount)),
871 Err(error) => {
872 let line = ui.label(
873 egui::RichText::new(format!("The mount block does not read as a pose ({error}), so no pin is checked. Reset it.")).color(WARN_COLOR).small(),
874 );
875 self.hits.insert("qualify:mount:status".into(), line.rect);
876 None
877 }
878 };
879 let triple = |key: &str| -> [f64; 3] {
880 let values = pose.as_ref().and_then(|pose| pose[key].as_array().cloned()).unwrap_or_default();
881 [0, 1, 2].map(|k| values.get(k).and_then(Value::as_f64).unwrap_or(0.0))
882 };
883 let status = if block.is_none() {
884 "The model is in its footprint's frame: top copper at z = 0, the footprint origin at 0, 0."
885 } else {
886 "Every solid of the part, with its seats, is moved by this onto its footprint wherever the part is placed. The features are not changed."
887 };
888 if block.is_none() || pose.is_some() {
889 let line = ui.label(egui::RichText::new(status).weak().small());
890 self.hits.insert("qualify:mount:status".into(), line.rect);
891 }
892 for (key, caption, speed, hover) in [
893 ("translate", "Move", 0.05, "Where the model's origin goes on the footprint, in millimetres (y up, top copper at z = 0)."),
894 ("rotateEulerDeg", "Turn", 1.0, "How the model is turned onto the footprint, in degrees about x, then y, then z."),
895 ] {
896 let values = triple(key);
897 ui.horizontal(|ui| {
898 ui.label(egui::RichText::new(caption).weak());
899 for (axis, value) in values.iter().enumerate() {
900 let mut edited = *value;
901 let field = ui.add(egui::DragValue::new(&mut edited).speed(speed).max_decimals(4)).on_hover_text(hover);
902 self.hits.insert(format!("qualify:mount:{key}{axis}"), field.rect);
903 if field.changed() && edited.is_finite() {
904 let mut translate = triple("translate");
905 let mut rotate = triple("rotateEulerDeg");
906 match key {
907 "translate" => translate[axis] = edited,
908 _ => rotate[axis] = edited,
909 }
910 asked = Some(MountEdit::Pose(translate, rotate, format!("{key}{axis}")));
911 }
912 }
913 });
914 }
915 ui.horizontal(|ui| {
916 let up = ui
917 .add(crate::icon_text::icon_button(ui, "Y up \u{2192} Z up").small())
918 .on_hover_text("Turn the model +90° about x: for a model built with y up, where a board's up is z");
919 self.hits.insert("qualify:mount:y_up".into(), up.rect);
920 if up.clicked() {
921 asked = Some(MountEdit::YUpToZUp);
922 }
923 let reset = ui
924 .add_enabled(block.is_some(), crate::icon_text::icon_button(ui, "Reset").small())
925 .on_hover_text("Clear the mount: the model is placed as it is built");
926 self.hits.insert("qualify:mount:reset".into(), reset.rect);
927 if reset.clicked() {
928 asked = Some(MountEdit::Reset);
929 }
930 });
931 ui.horizontal(|ui| {
933 for (key, caption, hover, pick) in [
934 ("seat", "Seat on face", "Pick the face the part sits on (lead undersides, a standoff, the body's underside): it is turned to face down and moved to the board's top, z = 0", MountPick::Seat),
935 ("origin", "Origin to point", "Pick the point that goes on the footprint origin (a pin's centre, a corner): the part moves in the board's plane, and its height stays", MountPick::Origin),
936 ] {
937 let button = ui
938 .add_enabled(pickable, crate::icon_text::icon_button(ui, &format!("{GLYPH_PICK} {caption}")).small())
939 .on_hover_text(hover)
940 .on_disabled_hover_text("Go to the 3D model to pick geometry");
941 self.hits.insert(format!("qualify:mount:{key}"), button.rect);
942 if button.clicked() {
943 asked = Some(MountEdit::Pick(pick));
944 }
945 }
946 });
947 let align = ui
948 .add(crate::icon_text::icon_button(ui, "Align to footprint").small())
949 .on_hover_text("Fit the part onto its pads as one rigid move: the seating plane from the pins' wires (or the plane already set), then the pins matched to their pads by number. The leftover is shown below");
950 self.hits.insert("qualify:mount:align".into(), align.rect);
951 if align.clicked() {
952 asked = Some(MountEdit::Align);
953 }
954 if let Some(outcome) = self.align.clone().filter(|outcome| outcome.written.as_ref() == block) {
955 let mut lines = Vec::new();
956 match (&outcome.error, outcome.largest, outcome.rms) {
957 (Some(error), _, _) => lines.push((format!("Align refused: {error}."), true)),
958 (None, Some(largest), Some(rms)) => lines.push((
959 format!(
960 "Aligned {} pins: largest {largest:.3} mm (pin {}), RMS {rms:.3} mm.",
961 outcome.pins,
962 outcome.worst.as_deref().unwrap_or("?")
963 ),
964 false,
965 )),
966 _ => {}
967 }
968 lines.extend(outcome.notes.iter().map(|note| (format!("Note: {note}."), true)));
969 for (i, (text, warn)) in lines.into_iter().enumerate() {
970 let text = egui::RichText::new(text).small();
971 let line = ui.label(if warn { text.color(WARN_COLOR) } else { text.weak() });
972 self.hits.insert(format!("qualify:mount:align_report:{i}"), line.rect);
973 }
974 }
975 });
976 asked
977 }
978
979 fn align_mount(&mut self, engine: &mut EngineState) {
982 let outcome = match super::pin_seats::align_to_footprint(engine) {
983 Ok(report) => {
984 let block = brep_kernel::mount_block_of(&report.mount);
985 if block.as_ref() != engine.history.mount_block() {
986 engine.history.set_mount_block(block.clone(), None);
987 }
988 AlignOutcome {
989 written: block,
990 largest: Some(report.largest),
991 rms: Some(report.rms),
992 worst: Some(report.worst),
993 pins: report.pins,
994 notes: report.notes,
995 error: None,
996 }
997 }
998 Err(error) => AlignOutcome { written: engine.history.mount_block().cloned(), error: Some(error), ..AlignOutcome::default() },
999 };
1000 self.align = Some(outcome);
1001 }
1002
1003 fn section(&mut self, ui: &mut egui::Ui, caption: &str) {
1004 ui.add_space(3.0);
1005 ui.label(egui::RichText::new(caption).small().strong());
1006 }
1007
1008 fn pin_seat_line(&mut self, ui: &mut egui::Ui, seat: &super::pin_seats::PinSeat) {
1014 let text = match &seat.message {
1015 Some(message) => egui::RichText::new(message).color(WARN_COLOR).small(),
1016 None => egui::RichText::new(format!("Pin {} is on pad {}", seat.pin, seat.pin)).color(OK_COLOR).small(),
1017 };
1018 let label = ui.label(text);
1019 self.hits.insert(format!("qualify:pinseat:{}", seat.address), label.rect);
1020 }
1021
1022 fn seat_line(
1023 &mut self,
1024 ui: &mut egui::Ui,
1025 engine: &EngineState,
1026 address: &str,
1027 point: &brep_kernel::PortPoint,
1028 ) {
1029 let seated = !optional_text(point, "pointRef").trim().is_empty()
1030 || !optional_text(point, "directionRef").trim().is_empty()
1031 || !optional_text(point, "contactBody").trim().is_empty();
1032 let text = match engine.port_point_row(address) {
1033 Some(row) if seated => format!(
1034 "seated at ({}), facing ({})",
1035 triple(row.seat.origin),
1036 triple(row.seat.x),
1037 ),
1038 Some(row) => format!("at ({}), facing ({})", triple(row.position), triple(row.direction)),
1039 None => "not resolved by the last run".to_string(),
1042 };
1043 let label = ui.label(egui::RichText::new(text).weak().small());
1044 self.hits.insert("qualify:seat".into(), label.rect);
1045 }
1046
1047 fn contact_line(
1053 &mut self,
1054 ui: &mut egui::Ui,
1055 engine: &EngineState,
1056 gi: usize,
1057 pi: usize,
1058 address: &str,
1059 point: &brep_kernel::PortPoint,
1060 ) -> Option<(Edit, Option<String>)> {
1061 let contact = engine.port_point_row(address)?.contact.clone()?;
1062 let mut asked = None;
1063 ui.horizontal(|ui| {
1064 let text = if contact.seats_origin {
1065 format!(
1066 "wire end: the {} end of {} at ({})",
1067 contact.end,
1068 contact.body,
1069 triple(contact.wire_end)
1070 )
1071 } else {
1072 format!("axis of {} ({}); the point is seated above", contact.body, triple(contact.axis))
1073 };
1074 let label = ui.label(egui::RichText::new(text).weak().small());
1075 self.hits.insert("qualify:contact".into(), label.rect);
1076 if contact.seats_origin {
1077 let flip = ui
1078 .small_button("Other end")
1079 .on_hover_text("Attach the wire at the body's other end (Leaves the other way)");
1080 self.hits.insert(format!("qualify:point:{gi}:{pi}:contact:flip"), flip.rect);
1081 if flip.clicked() {
1082 asked = Some((Edit::PointReverse(gi, pi, !point.reverse_direction), None));
1083 }
1084 }
1085 });
1086 asked
1087 }
1088
1089 fn gizmo_line(
1091 &mut self,
1092 ui: &mut egui::Ui,
1093 engine: &EngineState,
1094 address: &str,
1095 target: Option<Target>,
1096 ) {
1097 let text = match (target, engine.port_point_gizmo_refusal(address)) {
1102 (Some(_), _) => "the move/rotate handles arm on the 3D surface".to_string(),
1103 (None, Some(expression)) => format!(
1104 "no handles: '{expression}' places this point, and a drag writes numbers"
1105 ),
1106 (None, None) => {
1107 "the move/rotate handles are on it — a drag writes the offset above".to_string()
1108 }
1109 };
1110 let label = ui.label(egui::RichText::new(text).weak().small());
1111 self.hits.insert("qualify:gizmo".into(), label.rect);
1112 }
1113
1114 fn presence(
1119 &mut self,
1120 ui: &mut egui::Ui,
1121 engine: &EngineState,
1122 gi: usize,
1123 pi: usize,
1124 address: &str,
1125 name: &str,
1126 ) {
1127 let pinned = engine
1128 .history
1129 .pin_point_report()
1130 .map(|report| report.pairs.iter().any(|pair| pair.point == address));
1131 let padded = pad_numbers(engine).iter().any(|number| number == name);
1132 for (key, state, present, absent) in [
1133 (
1134 "symbol",
1135 pinned,
1136 "a symbol pin carries this name",
1137 "no symbol pin carries this name, so nothing on the schematic is this point",
1138 ),
1139 (
1140 "pads",
1141 Some(padded),
1142 "a pad carries this number",
1143 "no pad carries this number",
1144 ),
1145 (
1146 "model",
1147 Some(resolved(engine, address)),
1148 "the last run resolved it in 3D",
1149 "the last run did not resolve it, so there is no geometry to show",
1150 ),
1151 ] {
1152 let (glyph, color, hover) = match state {
1153 Some(true) => (GLYPH_PRESENT, OK_COLOR, present),
1154 Some(false) => (GLYPH_ABSENT, WARN_COLOR, absent),
1155 None => (
1158 GLYPH_ABSENT,
1159 ui.visuals().weak_text_color(),
1160 "this part has no symbol",
1161 ),
1162 };
1163 let lamp = lamp(ui, glyph, color).on_hover_text(format!("{key}: {hover}"));
1164 self.hits
1165 .insert(format!("qualify:point:{gi}:{pi}:lamp:{key}"), lamp.rect);
1166 }
1167 }
1168
1169 fn jump_row(&mut self, ui: &mut egui::Ui, address: &str, target: Option<Target>) -> Option<Jump> {
1172 let mut asked = None;
1173 ui.horizontal(|ui| {
1174 ui.label(egui::RichText::new("Look at it in").weak());
1175 for (jump, key, label, hover) in [
1176 (Jump::Symbol, "symbol", "Symbol", "Open the schematic symbol with this point's PIN selected"),
1177 (Jump::Pads, "pads", "Pads", "Open the footprint with this point's PAD selected"),
1178 (Jump::Model, "model", "3D", "Show the model with this point's geometry selected"),
1179 ] {
1180 let here = match jump {
1181 Jump::Symbol => target == Some(Target::Symbol),
1182 Jump::Pads => target == Some(Target::Pads),
1183 Jump::Model => target.is_none(),
1184 };
1185 let button = ui
1186 .add_enabled(!here, egui::Button::new(label).small())
1187 .on_hover_text(format!("{hover} ({address})"))
1188 .on_disabled_hover_text("You are looking at it");
1189 self.hits.insert(format!("qualify:jump:{key}"), button.rect);
1190 if button.clicked() {
1191 asked = Some(jump);
1192 }
1193 }
1194 });
1195 asked
1196 }
1197
1198 fn reports(&mut self, ui: &mut egui::Ui, engine: &EngineState) {
1201 let mut problem = 0usize;
1202 let mut line = |ui: &mut egui::Ui,
1203 hits: &mut HashMap<String, egui::Rect>,
1204 text: String,
1205 color: egui::Color32| {
1206 let label = ui.label(egui::RichText::new(text).weak().color(color));
1207 hits.insert(format!("qualify:problem:{problem}"), label.rect);
1208 problem += 1;
1209 };
1210
1211 ui.label(egui::RichText::new("Pins and points").strong());
1212 match engine.history.pin_point_report() {
1213 None => {
1214 ui.label(
1215 egui::RichText::new("this part has no symbol, so its points bind to no pins")
1216 .weak(),
1217 );
1218 }
1219 Some(PinPointReport { pairs, problems }) => {
1220 ui.label(
1221 egui::RichText::new(format!(
1222 "{} pin{} paired",
1223 pairs.len(),
1224 if pairs.len() == 1 { "" } else { "s" }
1225 ))
1226 .weak()
1227 .color(if problems.is_empty() { OK_COLOR } else { WARN_COLOR }),
1228 );
1229 for entry in &problems {
1230 line(ui, &mut self.hits, entry.message(), WARN_COLOR);
1231 }
1232 }
1233 }
1234 if let Some(hold) = engine.history.pin_port_hold() {
1238 line(ui, &mut self.hits, format!("not carried to the pins: {hold}"), WARN_COLOR);
1239 }
1240
1241 ui.add_space(2.0);
1242 ui.label(egui::RichText::new("Ports").strong());
1243 match engine.ports_report() {
1244 None => {
1245 ui.label(egui::RichText::new("the model has not run yet").weak());
1246 }
1247 Some(report) => {
1248 ui.label(
1249 egui::RichText::new(format!(
1250 "{} point{} resolved | {}",
1251 report.points.len(),
1252 if report.points.len() == 1 { "" } else { "s" },
1253 if report.boundary {
1254 "a boundary: a parent sees only what this document declares"
1255 } else {
1256 "transparent: a parent sees this document's children too"
1257 },
1258 ))
1259 .weak()
1260 .color(if report.problems.is_empty() { OK_COLOR } else { ERROR_COLOR }),
1261 )
1262 .on_hover_text(if report.boundary {
1263 "A board hides its components behind the ports it declares itself (`portBoundary`, or a `pcb` block)."
1264 } else {
1265 "An enclosure does not hide the parts in it: their points are exported namespaced."
1266 });
1267 for entry in &report.problems {
1268 line(ui, &mut self.hits, entry.clone(), ERROR_COLOR);
1269 }
1270 }
1271 }
1272 if let Some(report) = engine.ports_report() {
1275 for row in report.points.iter().filter(|row| row.maps_to.is_some()) {
1276 let target = row.maps_to.clone().unwrap_or_default();
1277 line(
1278 ui,
1279 &mut self.hits,
1280 format!("{} \u{2192} {target}", row.address),
1281 ui.visuals().weak_text_color(),
1282 );
1283 }
1284 }
1285 }
1286
1287 fn apply(&mut self, engine: &mut EngineState, edit: Edit, coalesce: Option<&str>) {
1292 let mut block = engine
1293 .history
1294 .ports_block()
1295 .and_then(Value::as_array)
1296 .cloned()
1297 .unwrap_or_default();
1298 match edit {
1299 Edit::AddGroup => {
1300 block.push(serde_json::json!({
1301 "name": unique_group_name(&block),
1302 "purpose": PURPOSES[0],
1303 "points": [],
1304 }));
1305 }
1306 Edit::RemoveGroup(gi) => {
1307 if gi < block.len() {
1308 block.remove(gi);
1309 }
1310 }
1311 Edit::GroupName(gi, name) => {
1312 let was = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str);
1317 if let (Some(was), Some(address)) = (was, self.selected.clone()) {
1318 if let Some((port, point)) = brep_kernel::split_address(&address) {
1319 if port == was {
1320 self.selected = Some(brep_kernel::port_address(&name, point));
1321 }
1322 }
1323 }
1324 set_group(&mut block, gi, "name", Value::String(name));
1325 }
1326 Edit::GroupPurpose(gi, purpose) => {
1327 set_group(&mut block, gi, "purpose", Value::String(purpose));
1328 }
1329 Edit::GroupUnit(gi, unit) => match unit {
1330 Some(unit) => set_group(&mut block, gi, "symbolUnit", Value::from(unit)),
1331 None => remove_group_key(&mut block, gi, "symbolUnit"),
1332 },
1333 Edit::AddPoint(gi) => {
1334 if let Some(points) = points_mut(&mut block, gi) {
1335 let name = unique_point_name(points);
1336 points.push(serde_json::json!({
1337 "name": name,
1338 "transform": { "position": [0.0, 0.0, 0.0], "rotationEuler": [0.0, 0.0, 0.0] },
1339 }));
1340 }
1341 }
1342 Edit::RemovePoint(gi, pi) => {
1343 if let Some(points) = points_mut(&mut block, gi) {
1344 if pi < points.len() {
1345 points.remove(pi);
1346 }
1347 }
1348 }
1349 Edit::PointName(gi, pi, name) => {
1350 if let Some(group) = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str) {
1353 self.selected = Some(brep_kernel::port_address(group, &name));
1354 }
1355 set_point(&mut block, gi, pi, "name", Value::String(name));
1356 }
1357 Edit::PointText(gi, pi, key, text) => match text.trim().is_empty() {
1358 true => remove_point_key(&mut block, gi, pi, key),
1359 false => set_point(&mut block, gi, pi, key, match key {
1363 "pointRef" | "directionRef" | "contactBody" | "mapsTo" => {
1364 Value::String(text.trim().to_string())
1365 }
1366 _ => scalar(&text),
1367 }),
1368 },
1369 Edit::PointTransform(gi, pi, key, axis, text) => {
1370 set_transform_component(&mut block, gi, pi, key, axis, scalar(&text));
1371 }
1372 Edit::PointReverse(gi, pi, reverse) => match reverse {
1373 true => set_point(&mut block, gi, pi, "reverseDirection", Value::Bool(true)),
1374 false => remove_point_key(&mut block, gi, pi, "reverseDirection"),
1375 },
1376 }
1377 if block.is_empty() {
1382 engine.history.set_ports_block(None, None);
1383 engine.push_notice("the last connection-point group is gone; the Qualify pane closes with it");
1384 return;
1385 }
1386 engine.history.set_ports_block(Some(Value::Array(block)), coalesce);
1387 }
1388
1389 fn jump(&mut self, engine: &mut EngineState, ecad: &mut Editors, jump: Jump) {
1397 let Some(address) = self.selected.clone() else {
1398 return;
1399 };
1400 let Some((_, name)) = brep_kernel::split_address(&address) else {
1401 return;
1402 };
1403 let (target, workbench) = match jump {
1404 Jump::Symbol => (Some(Target::Symbol), "symbol"),
1405 Jump::Pads => (Some(Target::Pads), "pads"),
1406 Jump::Model => (None, MODEL_WORKBENCH),
1407 };
1408 match target {
1409 Some(target) => ecad.focus(target, name.to_string()),
1410 None => {
1411 if resolved(engine, &address) {
1416 engine.select_by_name("solid", &address);
1417 } else {
1418 engine.push_notice(format!(
1419 "{address} has no geometry yet \u{2014} the last run did not resolve it"
1420 ));
1421 }
1422 }
1423 }
1424 let already = match jump {
1428 Jump::Model => Target::of_workbench(&engine.settings.workbench).is_none(),
1429 _ => false,
1430 };
1431 if !already && engine.settings.workbench != workbench {
1432 let _ = engine
1437 .apply_settings_json(&serde_json::json!({ "workbench": workbench }).to_string());
1438 }
1439 }
1440
1441 fn adopt_editor_selection(&mut self, engine: &EngineState, ecad: &Editors, target: Option<Target>) {
1445 let (surface, label) = match target {
1450 None => (MODEL_SURFACE, engine.selected_port_point()),
1451 Some(target @ (Target::Symbol | Target::Pads)) => {
1452 (surface_of(target), editor_selection(ecad, target))
1453 }
1454 Some(_) => return,
1457 };
1458 let Some(label) = label else {
1459 if self.adopted.as_ref().is_some_and(|(from, _)| *from == surface) {
1462 self.adopted = None;
1463 }
1464 return;
1465 };
1466 if self.adopted.as_ref().is_some_and(|(from, what)| *from == surface && *what == label) {
1467 return;
1468 }
1469 self.adopted = Some((surface, label.clone()));
1470 if surface == MODEL_SURFACE {
1473 self.selected = Some(label);
1474 return;
1475 }
1476 let unit = engine
1479 .history
1480 .pins()
1481 .unwrap_or_default()
1482 .into_iter()
1483 .find(|pin| pin.label == label)
1484 .map(|pin| pin.unit)
1485 .unwrap_or(1);
1486 if let Some(group) = engine.history.port_group_for_unit(unit) {
1487 self.selected = Some(brep_kernel::port_address(&group, &label));
1488 }
1489 }
1490}
1491
1492fn resolved(engine: &EngineState, address: &str) -> bool {
1497 engine
1498 .ports_report()
1499 .is_some_and(|report| report.points.iter().any(|row| row.address == address))
1500}
1501
1502fn editor_selection(ecad: &Editors, target: Target) -> Option<String> {
1506 match target {
1507 Target::Symbol => ecad.symbol.selected_pin().map(str::to_string),
1508 Target::Pads => ecad.pads.selected_pad().map(str::to_string),
1509 Target::Pcb => None,
1510 }
1511}
1512
1513fn surface_of(target: Target) -> &'static str {
1518 match target {
1519 Target::Symbol => "symbol",
1520 Target::Pads => "pads",
1521 Target::Pcb => "pcb",
1522 }
1523}
1524
1525fn set_group(block: &mut [Value], gi: usize, key: &str, value: Value) {
1531 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1532 object.insert(key.into(), value);
1533 }
1534}
1535
1536fn remove_group_key(block: &mut [Value], gi: usize, key: &str) {
1537 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1538 object.remove(key);
1539 }
1540}
1541
1542fn points_mut(block: &mut [Value], gi: usize) -> Option<&mut Vec<Value>> {
1543 let group = block.get_mut(gi)?.as_object_mut()?;
1544 group.entry("points").or_insert_with(|| Value::Array(Vec::new())).as_array_mut()
1545}
1546
1547fn point_mut<'a>(block: &'a mut [Value], gi: usize, pi: usize) -> Option<&'a mut serde_json::Map<String, Value>> {
1548 points_mut(block, gi)?.get_mut(pi)?.as_object_mut()
1549}
1550
1551fn set_point(block: &mut [Value], gi: usize, pi: usize, key: &str, value: Value) {
1552 if let Some(point) = point_mut(block, gi, pi) {
1553 point.insert(key.into(), value);
1554 }
1555}
1556
1557fn remove_point_key(block: &mut [Value], gi: usize, pi: usize, key: &str) {
1558 if let Some(point) = point_mut(block, gi, pi) {
1559 point.remove(key);
1560 }
1561}
1562
1563fn set_transform_component(
1566 block: &mut [Value],
1567 gi: usize,
1568 pi: usize,
1569 key: &str,
1570 axis: usize,
1571 value: Value,
1572) {
1573 let Some(point) = point_mut(block, gi, pi) else {
1574 return;
1575 };
1576 let transform = point
1577 .entry("transform")
1578 .or_insert_with(|| Value::Object(Default::default()));
1579 if !transform.is_object() {
1580 *transform = Value::Object(Default::default());
1581 }
1582 let Some(transform) = transform.as_object_mut() else {
1583 return;
1584 };
1585 let axes = transform
1586 .entry(key.to_string())
1587 .or_insert_with(|| Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]));
1588 if !axes.is_array() {
1589 *axes = Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]);
1590 }
1591 if let Some(axes) = axes.as_array_mut() {
1592 while axes.len() < 3 {
1593 axes.push(Value::from(0.0));
1594 }
1595 axes[axis] = value;
1596 }
1597}
1598
1599fn scalar(text: &str) -> Value {
1604 let text = text.trim();
1605 if text.is_empty() {
1606 return Value::from(0.0);
1607 }
1608 match text.parse::<f64>() {
1609 Ok(number) => Value::from(number),
1610 Err(_) => Value::String(text.to_string()),
1611 }
1612}
1613
1614fn transform_component(point: &brep_kernel::PortPoint, key: &str, axis: usize) -> String {
1618 match point.transform.get(key).and_then(Value::as_array).and_then(|axes| axes.get(axis)) {
1619 Some(Value::Number(number)) => match number.as_f64() {
1624 Some(value) => brep_render::formatting::compact_decimal(value, 6),
1625 None => number.to_string(),
1626 },
1627 Some(Value::String(expression)) => expression.clone(),
1628 _ => "0".to_string(),
1629 }
1630}
1631
1632fn optional_text(point: &brep_kernel::PortPoint, key: &str) -> String {
1635 match key {
1636 "pointRef" => point.point_ref.clone().unwrap_or_default(),
1637 "directionRef" => point.direction_ref.clone().unwrap_or_default(),
1638 "contactBody" => point.contact_body.clone().unwrap_or_default(),
1639 "mapsTo" => point.maps_to.clone().unwrap_or_default(),
1640 "extension" => point.extension.map(|v| v.to_string()).unwrap_or_default(),
1641 "displayLength" => point.display_length.map(|v| v.to_string()).unwrap_or_default(),
1642 _ => String::new(),
1643 }
1644}
1645
1646fn lamp(ui: &mut egui::Ui, glyph: &str, color: egui::Color32) -> egui::Response {
1649 match crate::icon_text::glyph(ui, glyph, color) {
1650 Some(art) => ui.add(art),
1651 None => ui.label(egui::RichText::new(glyph).color(color)),
1652 }
1653}
1654
1655fn triple(values: [f64; 3]) -> String {
1657 values
1658 .iter()
1659 .map(|value| {
1660 let rounded = (value * 1000.0).round() / 1000.0;
1661 if rounded == 0.0 { "0".to_string() } else { format!("{rounded}") }
1663 })
1664 .collect::<Vec<_>>()
1665 .join(", ")
1666}
1667
1668fn pad_numbers(engine: &EngineState) -> Vec<String> {
1672 engine
1673 .history
1674 .pads_block()
1675 .and_then(|block| block.get("pads"))
1676 .and_then(Value::as_array)
1677 .map(|pads| {
1678 pads.iter()
1679 .filter_map(|pad| pad.get("number").and_then(Value::as_str))
1680 .map(str::to_string)
1681 .collect()
1682 })
1683 .unwrap_or_default()
1684}
1685
1686fn unique_group_name(block: &[Value]) -> String {
1688 let taken: Vec<&str> = block
1689 .iter()
1690 .filter_map(|group| group.get("name").and_then(Value::as_str))
1691 .collect();
1692 (1..).map(|n| format!("J{n}")).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1693}
1694
1695fn unique_point_name(points: &[Value]) -> String {
1698 let taken: Vec<&str> = points
1699 .iter()
1700 .filter_map(|point| point.get("name").and_then(Value::as_str))
1701 .collect();
1702 (1..).map(|n| n.to_string()).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1703}
1704
1705pub static HIT_KEYS: &[HitKeyDoc] = &[
1706 HitKeyDoc { panel: "qualify", prefix: "qualify:panel:clip", meaning: "the visible region of the pane", command: None },
1707 HitKeyDoc { panel: "qualify", prefix: "qualify:add_group", meaning: "declare another port group", command: None },
1708 HitKeyDoc { panel: "qualify", prefix: "qualify:group:", meaning: "a port group's name, purpose, symbol unit, add-point or remove", command: None },
1709 HitKeyDoc { panel: "qualify", prefix: "qualify:point:", meaning: "a connection point's select, name, remove, or one of the selected point's fields", command: None },
1710 HitKeyDoc { panel: "qualify", prefix: "qualify:jump:", meaning: "carry the selected point to the symbol, the pads or the 3D model", command: None },
1711 HitKeyDoc { panel: "qualify", prefix: "qualify:hint", meaning: "what selecting a point is for, shown while none is", command: None },
1712 HitKeyDoc { panel: "qualify", prefix: "qualify:seat", meaning: "what the last run made of the selected point's seat", command: None },
1713 HitKeyDoc { panel: "qualify", prefix: "qualify:pinseat:", meaning: "a pcb point's pin seat check, by address: whether its 3D seat lands on its pin's pad", command: None },
1714 HitKeyDoc { panel: "qualify", prefix: "qualify:gizmo", meaning: "whether the move/rotate handles are on the selected point", command: None },
1715 HitKeyDoc { panel: "qualify", prefix: "qualify:problem:", meaning: "one line of the pin/point or ports report", command: None },
1716 HitKeyDoc { panel: "qualify", prefix: "qualify:mount:", meaning: "the part's mount frame on the board: its status, a move or turn field (translate0..2, rotateEulerDeg0..2), Y up to Z up, reset, a pick (seat on a face, origin to a point), Align to footprint (align) and its report lines (align_report:N)", command: None },
1717];
1718