1use crate::ui_kit;
58use std::collections::HashMap;
59
60use eframe::egui;
61use serde_json::Value;
62
63use crate::automation::hit_keys::HitKeyDoc;
64use crate::workbench::ecad::{Editors, Target};
65use brep_render::brep_kernel::{self, PinPointReport, PortDeclaration};
66use brep_render::engine_state::{EngineState, MountPick, PortRefField};
67
68const 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"];
82
83const MODEL_WORKBENCH: &str = "wireHarness";
92
93const MODEL_SURFACE: &str = "model";
96
97enum Edit {
99 GroupName(usize, String),
100 GroupPurpose(usize, String),
101 GroupUnit(usize, Option<u32>),
102 AddGroup,
103 RemoveGroup(usize),
104 PointName(usize, usize, String),
105 PointText(usize, usize, &'static str, String),
108 PointTransform(usize, usize, &'static str, usize, String),
111 PointReverse(usize, usize, bool),
112 AddPoint(usize),
113 RemovePoint(usize, usize),
114}
115
116#[derive(Clone, Debug, PartialEq)]
118enum MountEdit {
119 Pose([f64; 3], [f64; 3], String),
122 YUpToZUp,
124 Reset,
125 Pick(MountPick),
128 Align,
131}
132
133#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
136struct AlignOutcome {
137 written: Option<Value>,
139 largest: Option<f64>,
142 rms: Option<f64>,
143 worst: Option<String>,
144 pins: usize,
145 notes: Vec<String>,
146 error: Option<String>,
148}
149
150fn apply_mount(engine: &mut EngineState, edit: MountEdit) {
154 if let MountEdit::Pick(pick) = edit {
155 engine.begin_ref_select_for_mount(pick);
156 return;
157 }
158 let current = engine
159 .history
160 .mount_block()
161 .and_then(|block| brep_kernel::mount_from_block(block).ok());
162 let (mount, coalesce) = match edit {
163 MountEdit::Reset | MountEdit::Pick(_) | MountEdit::Align => (None, None),
164 MountEdit::Pose(translate, rotate, field) => {
165 let pose = serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate });
166 (brep_kernel::mount_from_block(&pose).ok(), Some(format!("field:{field}")))
167 }
168 MountEdit::YUpToZUp => {
169 let turn = brep_kernel::mount_from_block(&serde_json::json!({ "rotateEulerDeg": [90.0, 0.0, 0.0] }));
170 let composed = turn.and_then(|turn| match current {
171 Some(current) => turn.compose(¤t),
172 None => Ok(turn),
173 });
174 (composed.ok(), None)
175 }
176 };
177 let block = mount.as_ref().and_then(brep_kernel::mount_block_of);
178 if block.as_ref() == engine.history.mount_block() {
179 return;
180 }
181 engine.history.set_mount_block(block, coalesce.as_deref());
182}
183
184#[derive(Clone, Copy, PartialEq, Eq)]
186enum Jump {
187 Symbol,
188 Pads,
189 Model,
190}
191
192pub struct QualifyPanel {
194 hits: HashMap<String, egui::Rect>,
195 selected: Option<String>,
199 adopted: Option<(&'static str, String)>,
204 gizmo_armed_for: Option<String>,
210 pin_seats: Vec<super::pin_seats::PinSeat>,
213 pin_seats_at: Option<(u64, u64)>,
214 mount: Option<Value>,
216 align: Option<AlignOutcome>,
218}
219
220impl Default for QualifyPanel {
221 fn default() -> Self {
222 Self::new()
223 }
224}
225
226impl QualifyPanel {
227 pub fn new() -> Self {
228 Self { hits: HashMap::new(), selected: None, adopted: None, gizmo_armed_for: None, pin_seats: Vec::new(), pin_seats_at: None, mount: None, align: None }
229 }
230
231 pub fn hits_json(&self) -> String {
232 crate::automation::hit_rects::hits_json(&self.hits)
233 }
234
235 pub fn clear_hits(&mut self) {
238 self.hits.clear();
239 }
240
241 pub fn state_json(&self) -> String {
244 serde_json::json!({
245 "selected": self.selected,
246 "gizmoArmedFor": self.gizmo_armed_for,
247 "pinSeats": self.pin_seats,
248 "mount": self.mount,
249 "align": self.align,
250 })
251 .to_string()
252 }
253
254 pub fn show(
257 &mut self,
258 ui: &mut egui::Ui,
259 engine: &mut EngineState,
260 ecad: &mut Editors,
261 target: Option<Target>,
262 ) {
263 self.hits.clear();
264 self.hits.insert("qualify:panel:clip".into(), ui.clip_rect());
265
266 let groups: Vec<PortDeclaration> = engine
267 .history
268 .ports_block()
269 .cloned()
270 .and_then(|block| serde_json::from_value(block).ok())
271 .unwrap_or_default();
272
273 let at = (engine.applied_generation(), engine.history.revision());
274 if self.pin_seats_at != Some(at) {
275 self.pin_seats = super::pin_seats::pin_seats(engine);
276 self.mount = engine.history.mount_block().cloned();
277 self.pin_seats_at = Some(at);
278 }
279
280 self.adopt_editor_selection(engine, ecad, target);
282 if let Some(address) = &self.selected {
285 if !groups.iter().any(|group| {
286 group.points.iter().any(|point| &brep_kernel::port_address(&group.name, &point.name) == address)
287 }) {
288 self.selected = None;
289 }
290 }
291
292 let mut edit: Option<(Edit, Option<String>)> = None;
293 let mut jump: Option<Jump> = None;
294 let mut pick: Option<Option<String>> = None;
295 let mut refs: Option<(String, PortRefField, bool)> = None;
298
299 let points: usize = groups.iter().map(|group| group.points.len()).sum();
301 ui.horizontal(|ui| {
302 let add = ui
303 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add group")).small())
304 .on_hover_text("Declare another port group on this part — a second connector, or a port with a different purpose");
305 self.hits.insert("qualify:add_group".into(), add.rect);
306 if add.clicked() {
307 edit = Some((Edit::AddGroup, None));
308 }
309 ui.label(
310 egui::RichText::new(format!(
311 "{} group{} | {points} point{}",
312 groups.len(),
313 if groups.len() == 1 { "" } else { "s" },
314 if points == 1 { "" } else { "s" },
315 ))
316 .weak(),
317 );
318 });
319 if self.selected.is_none() {
320 let hint = ui.label(
323 egui::RichText::new(
324 "Select a point to place it, seat it on geometry and cross to its pin and pad",
325 )
326 .weak()
327 .small(),
328 );
329 self.hits.insert("qualify:hint".into(), hint.rect);
330 }
331 ui.add_space(2.0);
332
333 for (gi, group) in groups.iter().enumerate() {
335 egui::Frame::group(ui.style())
336 .inner_margin(egui::Margin::same(4))
337 .show(ui, |ui| {
338 let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
343 ui.set_width(ui.available_width().min(room));
344 if let Some(asked) = self.group_header(ui, gi, group) {
345 edit = Some(asked);
346 }
347 for (pi, point) in group.points.iter().enumerate() {
348 let address = brep_kernel::port_address(&group.name, &point.name);
349 let selected = self.selected.as_deref() == Some(address.as_str());
350 if let Some(asked) = self
351 .point_row(ui, engine, gi, pi, point, &address, selected, &mut pick)
352 {
353 edit = Some(asked);
354 }
355 if let Some(seat) = self.pin_seats.iter().find(|seat| seat.address == address).cloned() {
356 self.pin_seat_line(ui, &seat);
357 }
358 if selected {
359 if let Some(asked) = self
360 .point_fields(ui, engine, gi, pi, point, &address, target, &mut refs)
361 {
362 edit = Some(asked);
363 }
364 if let Some(asked) = self.jump_row(ui, &address, target) {
365 jump = Some(asked);
366 }
367 }
368 }
369 let add = ui
370 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add point")).small())
371 .on_hover_text("Add a connection point to this group. It arrives at the part origin, facing +X; place it below.");
372 self.hits.insert(format!("qualify:group:{gi}:add_point"), add.rect);
373 if add.clicked() {
374 edit = Some((Edit::AddPoint(gi), None));
375 }
376 });
377 }
378
379 let mount_edit = self.mount_section(ui, engine, target.is_none());
381
382 ui.add_space(4.0);
384 self.reports(ui, engine);
385
386 if let Some(pick) = pick {
388 self.pick(engine, ecad, target, pick);
389 }
390 if let Some((address, field, enter)) = refs {
391 match enter {
392 true => engine.begin_ref_select_for_port_point(&address, field),
393 false => engine.clear_port_point_ref(&address, field),
394 }
395 }
396 if let Some((edit, coalesce)) = edit {
397 self.apply(engine, edit, coalesce.as_deref());
398 }
399 if let Some(jump) = jump {
400 self.jump(engine, ecad, jump);
401 }
402 match mount_edit {
403 Some(MountEdit::Align) => self.align_mount(engine),
404 Some(mount_edit) => apply_mount(engine, mount_edit),
405 None => {}
406 }
407 self.follow_gizmo(engine, target);
409 }
410
411 fn follow_gizmo(&mut self, engine: &mut EngineState, target: Option<Target>) {
419 let wanted = match target.is_none() && !engine.ref_select_active() {
420 true => self.selected.clone(),
421 false => None,
422 };
423 let refusal = wanted
440 .as_deref()
441 .and_then(|address| engine.port_point_gizmo_refusal(address));
442 let settled = wanted == self.gizmo_armed_for
443 && (wanted.is_none() || engine.transform_armed() || refusal.is_some());
444 if settled {
445 return;
446 }
447 self.gizmo_armed_for = wanted.clone();
448 match wanted {
449 Some(address) => {
453 engine.arm_transform_for_port_point(&address);
454 }
455 None => {
459 if engine.transform_armed_port_point().is_some() {
460 engine.disarm_transform();
461 }
462 }
463 }
464 }
465
466 fn pick(
477 &mut self,
478 engine: &mut EngineState,
479 ecad: &mut Editors,
480 target: Option<Target>,
481 address: Option<String>,
482 ) {
483 self.selected = address.clone();
484 match target {
485 Some(target) => {
486 if let Some((_, name)) =
490 address.as_deref().and_then(brep_kernel::split_address)
491 {
492 ecad.focus(target, name.to_string());
493 ecad.apply_focus(target);
494 }
495 self.adopted = editor_selection(ecad, target)
501 .map(|held| (surface_of(target), held));
502 }
503 None => {
507 if let Some(address) = address.as_deref() {
508 if resolved(engine, address) {
509 engine.select_by_name("solid", address);
510 }
511 }
512 self.adopted = engine
518 .selected_port_point()
519 .map(|held| (MODEL_SURFACE, held));
520 }
521 }
522 }
523
524 fn group_header(
526 &mut self,
527 ui: &mut egui::Ui,
528 gi: usize,
529 group: &PortDeclaration,
530 ) -> Option<(Edit, Option<String>)> {
531 let mut asked = None;
532 ui.horizontal(|ui| {
533 let mut name = group.name.clone();
534 let field = ui
535 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
536 .on_hover_text("The group's name — the first half of every address in it (`J1` in `J1.VCC`). `:`, `.` and `/` are refused.");
537 self.hits.insert(format!("qualify:group:{gi}:name"), field.rect);
538 if field.changed() {
539 asked = Some((Edit::GroupName(gi, name), Some(format!("group:{gi}:name"))));
540 }
541
542 let mut purpose = group.purpose.clone();
543 let combo = egui::ComboBox::from_id_salt(("qualify-purpose", gi))
544 .selected_text(if purpose.is_empty() { "purpose" } else { purpose.as_str() })
545 .width(76.0)
546 .show_ui(ui, |ui| {
547 let mut offered: Vec<String> =
553 PURPOSES.iter().map(|p| (*p).to_string()).collect();
554 if !group.purpose.is_empty() && !PURPOSES.contains(&group.purpose.as_str()) {
555 offered.push(group.purpose.clone());
556 }
557 for candidate in offered {
558 let item = ui.selectable_label(purpose == candidate, &candidate);
559 self.hits
560 .insert(format!("qualify:group:{gi}:purpose:{candidate}"), item.rect);
561 if item.clicked() {
562 purpose = candidate;
563 }
564 }
565 });
566 self.hits.insert(format!("qualify:group:{gi}:purpose"), combo.response.rect);
567 if purpose != group.purpose {
568 asked = Some((Edit::GroupPurpose(gi, purpose), None));
569 }
570
571 ui.label(egui::RichText::new("unit").weak());
572 let mut unit = group.symbol_unit.map(|unit| unit.to_string()).unwrap_or_default();
573 let field = ui
574 .add(egui::TextEdit::singleline(&mut unit).desired_width(24.0))
575 .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.");
576 self.hits.insert(format!("qualify:group:{gi}:unit"), field.rect);
577 if field.changed() {
578 let parsed = unit.trim().parse::<u32>().ok();
579 if parsed.is_some() || unit.trim().is_empty() {
583 asked = Some((Edit::GroupUnit(gi, parsed), Some(format!("group:{gi}:unit"))));
584 }
585 }
586
587 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
588 let remove = ui
589 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(ui_kit::status::danger(ui.ctx()))).small())
590 .on_hover_text("Remove this group and every point in it — and the pins bound to them");
591 self.hits.insert(format!("qualify:group:{gi}:remove"), remove.rect);
592 if remove.clicked() {
593 asked = Some((Edit::RemoveGroup(gi), None));
594 }
595 });
596 });
597 asked
598 }
599
600 #[allow(clippy::too_many_arguments)]
605 fn point_row(
606 &mut self,
607 ui: &mut egui::Ui,
608 engine: &EngineState,
609 gi: usize,
610 pi: usize,
611 point: &brep_kernel::PortPoint,
612 address: &str,
613 selected: bool,
614 pick: &mut Option<Option<String>>,
615 ) -> Option<(Edit, Option<String>)> {
616 let mut asked = None;
617 ui.horizontal(|ui| {
618 let label = crate::icon_text::selectable_icon_label(ui, selected, GLYPH_SELECT)
619 .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"));
620 self.hits.insert(format!("qualify:point:{gi}:{pi}:select"), label.rect);
621 if label.clicked() {
622 *pick = Some((!selected).then(|| address.to_string()));
623 }
624 let mut name = point.name.clone();
625 let field = ui
626 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
627 .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.");
628 self.hits.insert(format!("qualify:point:{gi}:{pi}:name"), field.rect);
629 if field.changed() {
630 asked = Some((Edit::PointName(gi, pi, name), Some(format!("point:{gi}:{pi}:name"))));
631 }
632 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
633 let remove = ui
634 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(ui_kit::status::danger(ui.ctx()))).small())
635 .on_hover_text("Remove this connection point — and the pin bound to it");
636 self.hits.insert(format!("qualify:point:{gi}:{pi}:remove"), remove.rect);
637 if remove.clicked() {
638 asked = Some((Edit::RemovePoint(gi, pi), None));
639 }
640 ui.add_space(4.0);
641 self.presence(ui, engine, gi, pi, address, &point.name);
642 });
643 });
644 asked
645 }
646
647 fn point_fields(
656 &mut self,
657 ui: &mut egui::Ui,
658 engine: &EngineState,
659 gi: usize,
660 pi: usize,
661 point: &brep_kernel::PortPoint,
662 address: &str,
663 target: Option<Target>,
664 refs: &mut Option<(String, PortRefField, bool)>,
665 ) -> Option<(Edit, Option<String>)> {
666 let mut asked = None;
667 let mapped = point
673 .maps_to
674 .as_deref()
675 .map(str::trim)
676 .is_some_and(|target| !target.is_empty());
677 ui.indent(("qualify-point", gi, pi), |ui| {
678 if mapped {
679 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
680 asked = Some(mapped_asked);
681 }
682 self.seat_line(ui, engine, address, point);
683 return;
684 }
685 let seat_fields: &[(PortRefField, &str, &str)] = &[
689 (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."),
690 (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."),
691 (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}."),
692 ];
693 self.section(ui, "Seated on");
694 for &(field, caption, hover) in seat_fields {
695 ui.horizontal(|ui| {
696 ui.label(egui::RichText::new(caption).weak());
697 let key = field.key();
698 let mut text = optional_text(point, key);
699 let field_ui = ui
700 .add(egui::TextEdit::singleline(&mut text).desired_width(120.0))
701 .on_hover_text(hover);
702 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field_ui.rect);
703 if field_ui.changed() {
704 asked = Some((
705 Edit::PointText(gi, pi, key, text),
706 Some(format!("point:{gi}:{pi}:{key}")),
707 ));
708 }
709 let pickable = target.is_none();
713 let pick = ui
714 .add_enabled(
715 pickable,
716 crate::icon_text::icon_button(ui, GLYPH_PICK).small(),
717 )
718 .on_hover_text("Pick it in the 3D view")
719 .on_disabled_hover_text("Go to the 3D model to pick geometry");
720 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:pick"), pick.rect);
721 if pick.clicked() {
722 *refs = Some((address.to_string(), field, true));
723 }
724 let has = !optional_text(point, key).trim().is_empty();
725 let clear = ui
726 .add_enabled(
727 has,
728 crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(ui_kit::status::danger(ui.ctx()))).small(),
729 )
730 .on_hover_text("Unseat it — the offset below stays as it is, read from the part origin");
731 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:clear"), clear.rect);
732 if clear.clicked() {
733 *refs = Some((address.to_string(), field, false));
734 }
735 });
736 }
737 self.seat_line(ui, engine, address, point);
738 if let Some(flip) = self.contact_line(ui, engine, gi, pi, address, point) {
739 asked = Some(flip);
740 }
741
742 self.section(ui, "Placement");
744 let seated = point.point_ref.is_some()
745 || point.direction_ref.is_some()
746 || point.contact_body.is_some();
747 for (key, caption, hover) in [
748 ("position", "Offset", if seated {
749 "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."
750 } else {
751 "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."
752 }),
753 ("rotationEuler", "Angle", if seated {
754 "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\"."
755 } else {
756 "The rotation applied to +X to get the direction a wire leaves along, in degrees."
757 }),
758 ] {
759 ui.horizontal(|ui| {
760 ui.label(egui::RichText::new(caption).weak());
761 for axis in 0..3 {
762 let mut text = transform_component(point, key, axis);
763 let field = ui
764 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
765 .on_hover_text(hover);
766 self.hits
767 .insert(format!("qualify:point:{gi}:{pi}:{key}{axis}"), field.rect);
768 if field.changed() {
769 asked = Some((
770 Edit::PointTransform(gi, pi, key, axis, text),
771 Some(format!("point:{gi}:{pi}:{key}{axis}")),
772 ));
773 }
774 }
775 });
776 }
777 self.gizmo_line(ui, engine, address, target);
778
779 self.section(ui, "Wire");
781 ui.horizontal(|ui| {
782 for (key, caption, hover) in [
783 ("extension", "Extension", "The straight run a wire keeps before it may bend. Empty takes the default."),
784 ("displayLength", "Drawn", "How long the point's line is drawn. Empty takes the default."),
785 ] {
786 ui.label(egui::RichText::new(caption).weak());
787 let mut text = optional_text(point, key);
788 let field = ui
789 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
790 .on_hover_text(hover);
791 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field.rect);
792 if field.changed() {
793 asked = Some((
794 Edit::PointText(gi, pi, key, text),
795 Some(format!("point:{gi}:{pi}:{key}")),
796 ));
797 }
798 }
799 });
800 let mut reverse = point.reverse_direction;
801 let toggle = ui_kit::checkbox(ui, &mut reverse, "Leaves the other way")
802 .on_hover_text("Flip the direction a wire leaves along, without disturbing the seat");
803 self.hits.insert(format!("qualify:point:{gi}:{pi}:reverse"), toggle.rect);
804 if toggle.changed() {
805 asked = Some((Edit::PointReverse(gi, pi, reverse), None));
806 }
807
808 if !engine.assembly_components().is_empty() {
813 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
814 asked = Some(mapped_asked);
815 }
816 }
817 });
818 asked
819 }
820
821 fn maps_to_field(
824 &mut self,
825 ui: &mut egui::Ui,
826 gi: usize,
827 pi: usize,
828 point: &brep_kernel::PortPoint,
829 ) -> Option<(Edit, Option<String>)> {
830 let mut asked = None;
831 self.section(ui, "Assembly");
832 ui.horizontal(|ui| {
833 ui.label(egui::RichText::new("Maps to").weak());
834 let mut text = optional_text(point, "mapsTo");
835 let field = ui
836 .add(egui::TextEdit::singleline(&mut text).desired_width(130.0))
837 .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.");
838 self.hits.insert(format!("qualify:point:{gi}:{pi}:mapsTo"), field.rect);
839 if field.changed() {
840 asked = Some((
841 Edit::PointText(gi, pi, "mapsTo", text),
842 Some(format!("point:{gi}:{pi}:mapsTo")),
843 ));
844 }
845 });
846 asked
847 }
848
849 fn mount_section(&mut self, ui: &mut egui::Ui, engine: &EngineState, pickable: bool) -> Option<MountEdit> {
856 if engine.history.pads_block().is_none() {
857 return None;
858 }
859 let mut asked = None;
860 ui.add_space(4.0);
861 egui::Frame::group(ui.style()).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
862 let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
863 ui.set_width(ui.available_width().min(room));
864 self.section(ui, "Mount on board");
865 let block = engine.history.mount_block();
866 let pose = match block.map(brep_kernel::mount_from_block).transpose() {
867 Ok(mount) => mount.map(|mount| brep_kernel::transform_to_pose_params(&mount)),
868 Err(error) => {
869 let line = ui.label(
870 egui::RichText::new(format!("The mount block does not read as a pose ({error}), so no pin is checked. Reset it.")).color(ui_kit::status::warning(ui.ctx())).small(),
871 );
872 self.hits.insert("qualify:mount:status".into(), line.rect);
873 None
874 }
875 };
876 let triple = |key: &str| -> [f64; 3] {
877 let values = pose.as_ref().and_then(|pose| pose[key].as_array().cloned()).unwrap_or_default();
878 [0, 1, 2].map(|k| values.get(k).and_then(Value::as_f64).unwrap_or(0.0))
879 };
880 let status = if block.is_none() {
881 "The model is in its footprint's frame: top copper at z = 0, the footprint origin at 0, 0."
882 } else {
883 "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."
884 };
885 if block.is_none() || pose.is_some() {
886 let line = ui.label(egui::RichText::new(status).weak().small());
887 self.hits.insert("qualify:mount:status".into(), line.rect);
888 }
889 for (key, caption, speed, hover) in [
890 ("translate", "Move", 0.05, "Where the model's origin goes on the footprint, in millimetres (y up, top copper at z = 0)."),
891 ("rotateEulerDeg", "Turn", 1.0, "How the model is turned onto the footprint, in degrees about x, then y, then z."),
892 ] {
893 let values = triple(key);
894 ui.horizontal(|ui| {
895 ui.label(egui::RichText::new(caption).weak());
896 for (axis, value) in values.iter().enumerate() {
897 let mut edited = *value;
898 let field = ui.add(egui::DragValue::new(&mut edited).speed(speed).max_decimals(4)).on_hover_text(hover);
899 self.hits.insert(format!("qualify:mount:{key}{axis}"), field.rect);
900 if field.changed() && edited.is_finite() {
901 let mut translate = triple("translate");
902 let mut rotate = triple("rotateEulerDeg");
903 match key {
904 "translate" => translate[axis] = edited,
905 _ => rotate[axis] = edited,
906 }
907 asked = Some(MountEdit::Pose(translate, rotate, format!("{key}{axis}")));
908 }
909 }
910 });
911 }
912 ui.horizontal(|ui| {
913 let up = ui
914 .add(crate::icon_text::icon_button(ui, "Y up \u{2192} Z up").small())
915 .on_hover_text("Turn the model +90° about x: for a model built with y up, where a board's up is z");
916 self.hits.insert("qualify:mount:y_up".into(), up.rect);
917 if up.clicked() {
918 asked = Some(MountEdit::YUpToZUp);
919 }
920 let reset = ui
921 .add_enabled(block.is_some(), crate::icon_text::icon_button(ui, "Reset").small())
922 .on_hover_text("Clear the mount: the model is placed as it is built");
923 self.hits.insert("qualify:mount:reset".into(), reset.rect);
924 if reset.clicked() {
925 asked = Some(MountEdit::Reset);
926 }
927 });
928 ui.horizontal(|ui| {
930 for (key, caption, hover, pick) in [
931 ("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),
932 ("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),
933 ] {
934 let button = ui
935 .add_enabled(pickable, crate::icon_text::icon_button(ui, &format!("{GLYPH_PICK} {caption}")).small())
936 .on_hover_text(hover)
937 .on_disabled_hover_text("Go to the 3D model to pick geometry");
938 self.hits.insert(format!("qualify:mount:{key}"), button.rect);
939 if button.clicked() {
940 asked = Some(MountEdit::Pick(pick));
941 }
942 }
943 });
944 let align = ui
945 .add(crate::icon_text::icon_button(ui, "Align to footprint").small())
946 .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");
947 self.hits.insert("qualify:mount:align".into(), align.rect);
948 if align.clicked() {
949 asked = Some(MountEdit::Align);
950 }
951 if let Some(outcome) = self.align.clone().filter(|outcome| outcome.written.as_ref() == block) {
952 let mut lines = Vec::new();
953 match (&outcome.error, outcome.largest, outcome.rms) {
954 (Some(error), _, _) => lines.push((format!("Align refused: {error}."), true)),
955 (None, Some(largest), Some(rms)) => lines.push((
956 format!(
957 "Aligned {} pins: largest {largest:.3} mm (pin {}), RMS {rms:.3} mm.",
958 outcome.pins,
959 outcome.worst.as_deref().unwrap_or("?")
960 ),
961 false,
962 )),
963 _ => {}
964 }
965 lines.extend(outcome.notes.iter().map(|note| (format!("Note: {note}."), true)));
966 for (i, (text, warn)) in lines.into_iter().enumerate() {
967 let text = egui::RichText::new(text).small();
968 let line = ui.label(if warn { text.color(ui_kit::status::warning(ui.ctx())) } else { text.weak() });
969 self.hits.insert(format!("qualify:mount:align_report:{i}"), line.rect);
970 }
971 }
972 });
973 asked
974 }
975
976 fn align_mount(&mut self, engine: &mut EngineState) {
979 let outcome = match super::pin_seats::align_to_footprint(engine) {
980 Ok(report) => {
981 let block = brep_kernel::mount_block_of(&report.mount);
982 if block.as_ref() != engine.history.mount_block() {
983 engine.history.set_mount_block(block.clone(), None);
984 }
985 AlignOutcome {
986 written: block,
987 largest: Some(report.largest),
988 rms: Some(report.rms),
989 worst: Some(report.worst),
990 pins: report.pins,
991 notes: report.notes,
992 error: None,
993 }
994 }
995 Err(error) => AlignOutcome { written: engine.history.mount_block().cloned(), error: Some(error), ..AlignOutcome::default() },
996 };
997 self.align = Some(outcome);
998 }
999
1000 fn section(&mut self, ui: &mut egui::Ui, caption: &str) {
1001 ui.add_space(3.0);
1002 ui.label(egui::RichText::new(caption).small().strong());
1003 }
1004
1005 fn pin_seat_line(&mut self, ui: &mut egui::Ui, seat: &super::pin_seats::PinSeat) {
1011 let text = match &seat.message {
1012 Some(message) => egui::RichText::new(message).color(ui_kit::status::warning(ui.ctx())).small(),
1013 None => egui::RichText::new(format!("Pin {} is on pad {}", seat.pin, seat.pin)).color(ui_kit::status::success(ui.ctx())).small(),
1014 };
1015 let label = ui.label(text);
1016 self.hits.insert(format!("qualify:pinseat:{}", seat.address), label.rect);
1017 }
1018
1019 fn seat_line(
1020 &mut self,
1021 ui: &mut egui::Ui,
1022 engine: &EngineState,
1023 address: &str,
1024 point: &brep_kernel::PortPoint,
1025 ) {
1026 let seated = !optional_text(point, "pointRef").trim().is_empty()
1027 || !optional_text(point, "directionRef").trim().is_empty()
1028 || !optional_text(point, "contactBody").trim().is_empty();
1029 let text = match engine.port_point_row(address) {
1030 Some(row) if seated => format!(
1031 "seated at ({}), facing ({})",
1032 triple(row.seat.origin),
1033 triple(row.seat.x),
1034 ),
1035 Some(row) => format!("at ({}), facing ({})", triple(row.position), triple(row.direction)),
1036 None => "not resolved by the last run".to_string(),
1039 };
1040 let label = ui.label(egui::RichText::new(text).weak().small());
1041 self.hits.insert("qualify:seat".into(), label.rect);
1042 }
1043
1044 fn contact_line(
1050 &mut self,
1051 ui: &mut egui::Ui,
1052 engine: &EngineState,
1053 gi: usize,
1054 pi: usize,
1055 address: &str,
1056 point: &brep_kernel::PortPoint,
1057 ) -> Option<(Edit, Option<String>)> {
1058 let contact = engine.port_point_row(address)?.contact.clone()?;
1059 let mut asked = None;
1060 ui.horizontal(|ui| {
1061 let text = if contact.seats_origin {
1062 format!(
1063 "wire end: the {} end of {} at ({})",
1064 contact.end,
1065 contact.body,
1066 triple(contact.wire_end)
1067 )
1068 } else {
1069 format!("axis of {} ({}); the point is seated above", contact.body, triple(contact.axis))
1070 };
1071 let label = ui.label(egui::RichText::new(text).weak().small());
1072 self.hits.insert("qualify:contact".into(), label.rect);
1073 if contact.seats_origin {
1074 let flip = ui.add(ui_kit::Button::new("Other end").size(ui_kit::Size::Sm))
1075 .on_hover_text("Attach the wire at the body's other end (Leaves the other way)");
1076 self.hits.insert(format!("qualify:point:{gi}:{pi}:contact:flip"), flip.rect);
1077 if flip.clicked() {
1078 asked = Some((Edit::PointReverse(gi, pi, !point.reverse_direction), None));
1079 }
1080 }
1081 });
1082 asked
1083 }
1084
1085 fn gizmo_line(
1087 &mut self,
1088 ui: &mut egui::Ui,
1089 engine: &EngineState,
1090 address: &str,
1091 target: Option<Target>,
1092 ) {
1093 let text = match (target, engine.port_point_gizmo_refusal(address)) {
1098 (Some(_), _) => "the move/rotate handles arm on the 3D surface".to_string(),
1099 (None, Some(expression)) => format!(
1100 "no handles: '{expression}' places this point, and a drag writes numbers"
1101 ),
1102 (None, None) => {
1103 "the move/rotate handles are on it — a drag writes the offset above".to_string()
1104 }
1105 };
1106 let label = ui.label(egui::RichText::new(text).weak().small());
1107 self.hits.insert("qualify:gizmo".into(), label.rect);
1108 }
1109
1110 fn presence(
1115 &mut self,
1116 ui: &mut egui::Ui,
1117 engine: &EngineState,
1118 gi: usize,
1119 pi: usize,
1120 address: &str,
1121 name: &str,
1122 ) {
1123 let pinned = engine
1124 .history
1125 .pin_point_report()
1126 .map(|report| report.pairs.iter().any(|pair| pair.point == address));
1127 let padded = pad_numbers(engine).iter().any(|number| number == name);
1128 for (key, state, present, absent) in [
1129 (
1130 "symbol",
1131 pinned,
1132 "a symbol pin carries this name",
1133 "no symbol pin carries this name, so nothing on the schematic is this point",
1134 ),
1135 (
1136 "pads",
1137 Some(padded),
1138 "a pad carries this number",
1139 "no pad carries this number",
1140 ),
1141 (
1142 "model",
1143 Some(resolved(engine, address)),
1144 "the last run resolved it in 3D",
1145 "the last run did not resolve it, so there is no geometry to show",
1146 ),
1147 ] {
1148 let (glyph, color, hover) = match state {
1149 Some(true) => (GLYPH_PRESENT, ui_kit::status::success(ui.ctx()), present),
1150 Some(false) => (GLYPH_ABSENT, ui_kit::status::warning(ui.ctx()), absent),
1151 None => (
1154 GLYPH_ABSENT,
1155 ui.visuals().weak_text_color(),
1156 "this part has no symbol",
1157 ),
1158 };
1159 let lamp = lamp(ui, glyph, color).on_hover_text(format!("{key}: {hover}"));
1160 self.hits
1161 .insert(format!("qualify:point:{gi}:{pi}:lamp:{key}"), lamp.rect);
1162 }
1163 }
1164
1165 fn jump_row(&mut self, ui: &mut egui::Ui, address: &str, target: Option<Target>) -> Option<Jump> {
1168 let mut asked = None;
1169 ui.horizontal(|ui| {
1170 ui.label(egui::RichText::new("Look at it in").weak());
1171 for (jump, key, label, hover) in [
1172 (Jump::Symbol, "symbol", "Symbol", "Open the schematic symbol with this point's PIN selected"),
1173 (Jump::Pads, "pads", "Pads", "Open the footprint with this point's PAD selected"),
1174 (Jump::Model, "model", "3D", "Show the model with this point's geometry selected"),
1175 ] {
1176 let here = match jump {
1177 Jump::Symbol => target == Some(Target::Symbol),
1178 Jump::Pads => target == Some(Target::Pads),
1179 Jump::Model => target.is_none(),
1180 };
1181 let button = ui_kit::button::add_enabled(ui, !here, ui_kit::Button::new(&label).size(ui_kit::Size::Sm))
1182 .on_hover_text(format!("{hover} ({address})"))
1183 .on_disabled_hover_text("You are looking at it");
1184 self.hits.insert(format!("qualify:jump:{key}"), button.rect);
1185 if button.clicked() {
1186 asked = Some(jump);
1187 }
1188 }
1189 });
1190 asked
1191 }
1192
1193 fn reports(&mut self, ui: &mut egui::Ui, engine: &EngineState) {
1196 let mut problem = 0usize;
1197 let mut line = |ui: &mut egui::Ui,
1198 hits: &mut HashMap<String, egui::Rect>,
1199 text: String,
1200 color: egui::Color32| {
1201 let label = ui.label(egui::RichText::new(text).weak().color(color));
1202 hits.insert(format!("qualify:problem:{problem}"), label.rect);
1203 problem += 1;
1204 };
1205
1206 ui.label(egui::RichText::new("Pins and points").strong());
1207 match engine.history.pin_point_report() {
1208 None => {
1209 ui.label(
1210 egui::RichText::new("this part has no symbol, so its points bind to no pins")
1211 .weak(),
1212 );
1213 }
1214 Some(PinPointReport { pairs, problems }) => {
1215 ui.label(
1216 egui::RichText::new(format!(
1217 "{} pin{} paired",
1218 pairs.len(),
1219 if pairs.len() == 1 { "" } else { "s" }
1220 ))
1221 .weak()
1222 .color(if problems.is_empty() { ui_kit::status::success(ui.ctx()) } else { ui_kit::status::warning(ui.ctx()) }),
1223 );
1224 for entry in &problems {
1225 line(ui, &mut self.hits, entry.message(), ui_kit::status::warning(ui.ctx()));
1226 }
1227 }
1228 }
1229 if let Some(hold) = engine.history.pin_port_hold() {
1233 line(ui, &mut self.hits, format!("not carried to the pins: {hold}"), ui_kit::status::warning(ui.ctx()));
1234 }
1235
1236 ui.add_space(2.0);
1237 ui.label(egui::RichText::new("Ports").strong());
1238 match engine.ports_report() {
1239 None => {
1240 ui.label(egui::RichText::new("the model has not run yet").weak());
1241 }
1242 Some(report) => {
1243 ui.label(
1244 egui::RichText::new(format!(
1245 "{} point{} resolved | {}",
1246 report.points.len(),
1247 if report.points.len() == 1 { "" } else { "s" },
1248 if report.boundary {
1249 "a boundary: a parent sees only what this document declares"
1250 } else {
1251 "transparent: a parent sees this document's children too"
1252 },
1253 ))
1254 .weak()
1255 .color(if report.problems.is_empty() { ui_kit::status::success(ui.ctx()) } else { ui_kit::status::danger(ui.ctx()) }),
1256 )
1257 .on_hover_text(if report.boundary {
1258 "A board hides its components behind the ports it declares itself (`portBoundary`, or a `pcb` block)."
1259 } else {
1260 "An enclosure does not hide the parts in it: their points are exported namespaced."
1261 });
1262 for entry in &report.problems {
1263 line(ui, &mut self.hits, entry.clone(), ui_kit::status::danger(ui.ctx()));
1264 }
1265 }
1266 }
1267 if let Some(report) = engine.ports_report() {
1270 for row in report.points.iter().filter(|row| row.maps_to.is_some()) {
1271 let target = row.maps_to.clone().unwrap_or_default();
1272 line(
1273 ui,
1274 &mut self.hits,
1275 format!("{} \u{2192} {target}", row.address),
1276 ui.visuals().weak_text_color(),
1277 );
1278 }
1279 }
1280 }
1281
1282 fn apply(&mut self, engine: &mut EngineState, edit: Edit, coalesce: Option<&str>) {
1287 let mut block = engine
1288 .history
1289 .ports_block()
1290 .and_then(Value::as_array)
1291 .cloned()
1292 .unwrap_or_default();
1293 match edit {
1294 Edit::AddGroup => {
1295 block.push(serde_json::json!({
1296 "name": unique_group_name(&block),
1297 "purpose": PURPOSES[0],
1298 "points": [],
1299 }));
1300 }
1301 Edit::RemoveGroup(gi) => {
1302 if gi < block.len() {
1303 block.remove(gi);
1304 }
1305 }
1306 Edit::GroupName(gi, name) => {
1307 let was = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str);
1312 if let (Some(was), Some(address)) = (was, self.selected.clone()) {
1313 if let Some((port, point)) = brep_kernel::split_address(&address) {
1314 if port == was {
1315 self.selected = Some(brep_kernel::port_address(&name, point));
1316 }
1317 }
1318 }
1319 set_group(&mut block, gi, "name", Value::String(name));
1320 }
1321 Edit::GroupPurpose(gi, purpose) => {
1322 set_group(&mut block, gi, "purpose", Value::String(purpose));
1323 }
1324 Edit::GroupUnit(gi, unit) => match unit {
1325 Some(unit) => set_group(&mut block, gi, "symbolUnit", Value::from(unit)),
1326 None => remove_group_key(&mut block, gi, "symbolUnit"),
1327 },
1328 Edit::AddPoint(gi) => {
1329 if let Some(points) = points_mut(&mut block, gi) {
1330 let name = unique_point_name(points);
1331 points.push(serde_json::json!({
1332 "name": name,
1333 "transform": { "position": [0.0, 0.0, 0.0], "rotationEuler": [0.0, 0.0, 0.0] },
1334 }));
1335 }
1336 }
1337 Edit::RemovePoint(gi, pi) => {
1338 if let Some(points) = points_mut(&mut block, gi) {
1339 if pi < points.len() {
1340 points.remove(pi);
1341 }
1342 }
1343 }
1344 Edit::PointName(gi, pi, name) => {
1345 if let Some(group) = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str) {
1348 self.selected = Some(brep_kernel::port_address(group, &name));
1349 }
1350 set_point(&mut block, gi, pi, "name", Value::String(name));
1351 }
1352 Edit::PointText(gi, pi, key, text) => match text.trim().is_empty() {
1353 true => remove_point_key(&mut block, gi, pi, key),
1354 false => set_point(&mut block, gi, pi, key, match key {
1358 "pointRef" | "directionRef" | "contactBody" | "mapsTo" => {
1359 Value::String(text.trim().to_string())
1360 }
1361 _ => scalar(&text),
1362 }),
1363 },
1364 Edit::PointTransform(gi, pi, key, axis, text) => {
1365 set_transform_component(&mut block, gi, pi, key, axis, scalar(&text));
1366 }
1367 Edit::PointReverse(gi, pi, reverse) => match reverse {
1368 true => set_point(&mut block, gi, pi, "reverseDirection", Value::Bool(true)),
1369 false => remove_point_key(&mut block, gi, pi, "reverseDirection"),
1370 },
1371 }
1372 if block.is_empty() {
1377 engine.history.set_ports_block(None, None);
1378 engine.push_notice("the last connection-point group is gone; the Qualify pane closes with it");
1379 return;
1380 }
1381 engine.history.set_ports_block(Some(Value::Array(block)), coalesce);
1382 }
1383
1384 fn jump(&mut self, engine: &mut EngineState, ecad: &mut Editors, jump: Jump) {
1392 let Some(address) = self.selected.clone() else {
1393 return;
1394 };
1395 let Some((_, name)) = brep_kernel::split_address(&address) else {
1396 return;
1397 };
1398 let (target, workbench) = match jump {
1399 Jump::Symbol => (Some(Target::Symbol), "symbol"),
1400 Jump::Pads => (Some(Target::Pads), "pads"),
1401 Jump::Model => (None, MODEL_WORKBENCH),
1402 };
1403 match target {
1404 Some(target) => ecad.focus(target, name.to_string()),
1405 None => {
1406 if resolved(engine, &address) {
1411 engine.select_by_name("solid", &address);
1412 } else {
1413 engine.push_notice(format!(
1414 "{address} has no geometry yet \u{2014} the last run did not resolve it"
1415 ));
1416 }
1417 }
1418 }
1419 let already = match jump {
1423 Jump::Model => Target::of_workbench(&engine.settings.workbench).is_none(),
1424 _ => false,
1425 };
1426 if !already && engine.settings.workbench != workbench {
1427 let _ = engine
1432 .apply_settings_json(&serde_json::json!({ "workbench": workbench }).to_string());
1433 }
1434 }
1435
1436 fn adopt_editor_selection(&mut self, engine: &EngineState, ecad: &Editors, target: Option<Target>) {
1440 let (surface, label) = match target {
1445 None => (MODEL_SURFACE, engine.selected_port_point()),
1446 Some(target @ (Target::Symbol | Target::Pads)) => {
1447 (surface_of(target), editor_selection(ecad, target))
1448 }
1449 Some(_) => return,
1452 };
1453 let Some(label) = label else {
1454 if self.adopted.as_ref().is_some_and(|(from, _)| *from == surface) {
1457 self.adopted = None;
1458 }
1459 return;
1460 };
1461 if self.adopted.as_ref().is_some_and(|(from, what)| *from == surface && *what == label) {
1462 return;
1463 }
1464 self.adopted = Some((surface, label.clone()));
1465 if surface == MODEL_SURFACE {
1468 self.selected = Some(label);
1469 return;
1470 }
1471 let unit = engine
1474 .history
1475 .pins()
1476 .unwrap_or_default()
1477 .into_iter()
1478 .find(|pin| pin.label == label)
1479 .map(|pin| pin.unit)
1480 .unwrap_or(1);
1481 if let Some(group) = engine.history.port_group_for_unit(unit) {
1482 self.selected = Some(brep_kernel::port_address(&group, &label));
1483 }
1484 }
1485}
1486
1487fn resolved(engine: &EngineState, address: &str) -> bool {
1492 engine
1493 .ports_report()
1494 .is_some_and(|report| report.points.iter().any(|row| row.address == address))
1495}
1496
1497fn editor_selection(ecad: &Editors, target: Target) -> Option<String> {
1501 match target {
1502 Target::Symbol => ecad.symbol.selected_pin().map(str::to_string),
1503 Target::Pads => ecad.pads.selected_pad().map(str::to_string),
1504 Target::Pcb => None,
1505 }
1506}
1507
1508fn surface_of(target: Target) -> &'static str {
1513 match target {
1514 Target::Symbol => "symbol",
1515 Target::Pads => "pads",
1516 Target::Pcb => "pcb",
1517 }
1518}
1519
1520fn set_group(block: &mut [Value], gi: usize, key: &str, value: Value) {
1526 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1527 object.insert(key.into(), value);
1528 }
1529}
1530
1531fn remove_group_key(block: &mut [Value], gi: usize, key: &str) {
1532 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1533 object.remove(key);
1534 }
1535}
1536
1537fn points_mut(block: &mut [Value], gi: usize) -> Option<&mut Vec<Value>> {
1538 let group = block.get_mut(gi)?.as_object_mut()?;
1539 group.entry("points").or_insert_with(|| Value::Array(Vec::new())).as_array_mut()
1540}
1541
1542fn point_mut<'a>(block: &'a mut [Value], gi: usize, pi: usize) -> Option<&'a mut serde_json::Map<String, Value>> {
1543 points_mut(block, gi)?.get_mut(pi)?.as_object_mut()
1544}
1545
1546fn set_point(block: &mut [Value], gi: usize, pi: usize, key: &str, value: Value) {
1547 if let Some(point) = point_mut(block, gi, pi) {
1548 point.insert(key.into(), value);
1549 }
1550}
1551
1552fn remove_point_key(block: &mut [Value], gi: usize, pi: usize, key: &str) {
1553 if let Some(point) = point_mut(block, gi, pi) {
1554 point.remove(key);
1555 }
1556}
1557
1558fn set_transform_component(
1561 block: &mut [Value],
1562 gi: usize,
1563 pi: usize,
1564 key: &str,
1565 axis: usize,
1566 value: Value,
1567) {
1568 let Some(point) = point_mut(block, gi, pi) else {
1569 return;
1570 };
1571 let transform = point
1572 .entry("transform")
1573 .or_insert_with(|| Value::Object(Default::default()));
1574 if !transform.is_object() {
1575 *transform = Value::Object(Default::default());
1576 }
1577 let Some(transform) = transform.as_object_mut() else {
1578 return;
1579 };
1580 let axes = transform
1581 .entry(key.to_string())
1582 .or_insert_with(|| Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]));
1583 if !axes.is_array() {
1584 *axes = Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]);
1585 }
1586 if let Some(axes) = axes.as_array_mut() {
1587 while axes.len() < 3 {
1588 axes.push(Value::from(0.0));
1589 }
1590 axes[axis] = value;
1591 }
1592}
1593
1594fn scalar(text: &str) -> Value {
1599 let text = text.trim();
1600 if text.is_empty() {
1601 return Value::from(0.0);
1602 }
1603 match text.parse::<f64>() {
1604 Ok(number) => Value::from(number),
1605 Err(_) => Value::String(text.to_string()),
1606 }
1607}
1608
1609fn transform_component(point: &brep_kernel::PortPoint, key: &str, axis: usize) -> String {
1613 match point.transform.get(key).and_then(Value::as_array).and_then(|axes| axes.get(axis)) {
1614 Some(Value::Number(number)) => match number.as_f64() {
1619 Some(value) => brep_render::formatting::compact_decimal(value, 6),
1620 None => number.to_string(),
1621 },
1622 Some(Value::String(expression)) => expression.clone(),
1623 _ => "0".to_string(),
1624 }
1625}
1626
1627fn optional_text(point: &brep_kernel::PortPoint, key: &str) -> String {
1630 match key {
1631 "pointRef" => point.point_ref.clone().unwrap_or_default(),
1632 "directionRef" => point.direction_ref.clone().unwrap_or_default(),
1633 "contactBody" => point.contact_body.clone().unwrap_or_default(),
1634 "mapsTo" => point.maps_to.clone().unwrap_or_default(),
1635 "extension" => point.extension.map(|v| v.to_string()).unwrap_or_default(),
1636 "displayLength" => point.display_length.map(|v| v.to_string()).unwrap_or_default(),
1637 _ => String::new(),
1638 }
1639}
1640
1641fn lamp(ui: &mut egui::Ui, glyph: &str, color: egui::Color32) -> egui::Response {
1644 match crate::icon_text::glyph(ui, glyph, color) {
1645 Some(art) => ui.add(art),
1646 None => ui.label(egui::RichText::new(glyph).color(color)),
1647 }
1648}
1649
1650fn triple(values: [f64; 3]) -> String {
1652 values
1653 .iter()
1654 .map(|value| {
1655 let rounded = (value * 1000.0).round() / 1000.0;
1656 if rounded == 0.0 { "0".to_string() } else { format!("{rounded}") }
1658 })
1659 .collect::<Vec<_>>()
1660 .join(", ")
1661}
1662
1663fn pad_numbers(engine: &EngineState) -> Vec<String> {
1667 engine
1668 .history
1669 .pads_block()
1670 .and_then(|block| block.get("pads"))
1671 .and_then(Value::as_array)
1672 .map(|pads| {
1673 pads.iter()
1674 .filter_map(|pad| pad.get("number").and_then(Value::as_str))
1675 .map(str::to_string)
1676 .collect()
1677 })
1678 .unwrap_or_default()
1679}
1680
1681fn unique_group_name(block: &[Value]) -> String {
1683 let taken: Vec<&str> = block
1684 .iter()
1685 .filter_map(|group| group.get("name").and_then(Value::as_str))
1686 .collect();
1687 (1..).map(|n| format!("J{n}")).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1688}
1689
1690fn unique_point_name(points: &[Value]) -> String {
1693 let taken: Vec<&str> = points
1694 .iter()
1695 .filter_map(|point| point.get("name").and_then(Value::as_str))
1696 .collect();
1697 (1..).map(|n| n.to_string()).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1698}
1699
1700pub static HIT_KEYS: &[HitKeyDoc] = &[
1701 HitKeyDoc { panel: "qualify", prefix: "qualify:panel:clip", meaning: "the visible region of the pane", command: None },
1702 HitKeyDoc { panel: "qualify", prefix: "qualify:add_group", meaning: "declare another port group", command: None },
1703 HitKeyDoc { panel: "qualify", prefix: "qualify:group:", meaning: "a port group's name, purpose, symbol unit, add-point or remove", command: None },
1704 HitKeyDoc { panel: "qualify", prefix: "qualify:point:", meaning: "a connection point's select, name, remove, or one of the selected point's fields", command: None },
1705 HitKeyDoc { panel: "qualify", prefix: "qualify:jump:", meaning: "carry the selected point to the symbol, the pads or the 3D model", command: None },
1706 HitKeyDoc { panel: "qualify", prefix: "qualify:hint", meaning: "what selecting a point is for, shown while none is", command: None },
1707 HitKeyDoc { panel: "qualify", prefix: "qualify:seat", meaning: "what the last run made of the selected point's seat", command: None },
1708 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 },
1709 HitKeyDoc { panel: "qualify", prefix: "qualify:gizmo", meaning: "whether the move/rotate handles are on the selected point", command: None },
1710 HitKeyDoc { panel: "qualify", prefix: "qualify:problem:", meaning: "one line of the pin/point or ports report", command: None },
1711 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 },
1712];
1713