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, 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, Copy, PartialEq, Eq)]
120enum Jump {
121 Symbol,
122 Pads,
123 Model,
124}
125
126pub struct QualifyPanel {
128 hits: HashMap<String, egui::Rect>,
129 selected: Option<String>,
133 adopted: Option<(&'static str, String)>,
138 gizmo_armed_for: Option<String>,
144 pin_seats: Vec<super::pin_seats::PinSeat>,
147 pin_seats_at: Option<(u64, u64)>,
148}
149
150impl Default for QualifyPanel {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156impl QualifyPanel {
157 pub fn new() -> Self {
158 Self { hits: HashMap::new(), selected: None, adopted: None, gizmo_armed_for: None, pin_seats: Vec::new(), pin_seats_at: None }
159 }
160
161 pub fn hits_json(&self) -> String {
162 crate::automation::hit_rects::hits_json(&self.hits)
163 }
164
165 pub fn clear_hits(&mut self) {
168 self.hits.clear();
169 }
170
171 pub fn state_json(&self) -> String {
174 serde_json::json!({
175 "selected": self.selected,
176 "gizmoArmedFor": self.gizmo_armed_for,
177 "pinSeats": self.pin_seats,
178 })
179 .to_string()
180 }
181
182 pub fn show(
185 &mut self,
186 ui: &mut egui::Ui,
187 engine: &mut EngineState,
188 ecad: &mut Editors,
189 target: Option<Target>,
190 ) {
191 self.hits.clear();
192 self.hits.insert("qualify:panel:clip".into(), ui.clip_rect());
193
194 let groups: Vec<PortDeclaration> = engine
195 .history
196 .ports_block()
197 .cloned()
198 .and_then(|block| serde_json::from_value(block).ok())
199 .unwrap_or_default();
200
201 let at = (engine.applied_generation(), engine.history.revision());
202 if self.pin_seats_at != Some(at) {
203 self.pin_seats = super::pin_seats::pin_seats(engine);
204 self.pin_seats_at = Some(at);
205 }
206
207 self.adopt_editor_selection(engine, ecad, target);
209 if let Some(address) = &self.selected {
212 if !groups.iter().any(|group| {
213 group.points.iter().any(|point| &brep_kernel::port_address(&group.name, &point.name) == address)
214 }) {
215 self.selected = None;
216 }
217 }
218
219 let mut edit: Option<(Edit, Option<String>)> = None;
220 let mut jump: Option<Jump> = None;
221 let mut pick: Option<Option<String>> = None;
222 let mut refs: Option<(String, PortRefField, bool)> = None;
225
226 let points: usize = groups.iter().map(|group| group.points.len()).sum();
228 ui.horizontal(|ui| {
229 let add = ui
230 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add group")).small())
231 .on_hover_text("Declare another port group on this part — a second connector, or a port with a different purpose");
232 self.hits.insert("qualify:add_group".into(), add.rect);
233 if add.clicked() {
234 edit = Some((Edit::AddGroup, None));
235 }
236 ui.label(
237 egui::RichText::new(format!(
238 "{} group{} | {points} point{}",
239 groups.len(),
240 if groups.len() == 1 { "" } else { "s" },
241 if points == 1 { "" } else { "s" },
242 ))
243 .weak(),
244 );
245 });
246 if self.selected.is_none() {
247 let hint = ui.label(
250 egui::RichText::new(
251 "Select a point to place it, seat it on geometry and cross to its pin and pad",
252 )
253 .weak()
254 .small(),
255 );
256 self.hits.insert("qualify:hint".into(), hint.rect);
257 }
258 ui.add_space(2.0);
259
260 for (gi, group) in groups.iter().enumerate() {
262 egui::Frame::group(ui.style())
263 .inner_margin(egui::Margin::same(4))
264 .show(ui, |ui| {
265 let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
270 ui.set_width(ui.available_width().min(room));
271 if let Some(asked) = self.group_header(ui, gi, group) {
272 edit = Some(asked);
273 }
274 for (pi, point) in group.points.iter().enumerate() {
275 let address = brep_kernel::port_address(&group.name, &point.name);
276 let selected = self.selected.as_deref() == Some(address.as_str());
277 if let Some(asked) = self
278 .point_row(ui, engine, gi, pi, point, &address, selected, &mut pick)
279 {
280 edit = Some(asked);
281 }
282 if let Some(seat) = self.pin_seats.iter().find(|seat| seat.address == address).cloned() {
283 self.pin_seat_line(ui, &seat);
284 }
285 if selected {
286 if let Some(asked) = self
287 .point_fields(ui, engine, gi, pi, point, &address, target, &mut refs)
288 {
289 edit = Some(asked);
290 }
291 if let Some(asked) = self.jump_row(ui, &address, target) {
292 jump = Some(asked);
293 }
294 }
295 }
296 let add = ui
297 .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add point")).small())
298 .on_hover_text("Add a connection point to this group. It arrives at the part origin, facing +X; place it below.");
299 self.hits.insert(format!("qualify:group:{gi}:add_point"), add.rect);
300 if add.clicked() {
301 edit = Some((Edit::AddPoint(gi), None));
302 }
303 });
304 }
305
306 ui.add_space(4.0);
308 self.reports(ui, engine);
309
310 if let Some(pick) = pick {
312 self.pick(engine, ecad, target, pick);
313 }
314 if let Some((address, field, enter)) = refs {
315 match enter {
316 true => engine.begin_ref_select_for_port_point(&address, field),
317 false => engine.clear_port_point_ref(&address, field),
318 }
319 }
320 if let Some((edit, coalesce)) = edit {
321 self.apply(engine, edit, coalesce.as_deref());
322 }
323 if let Some(jump) = jump {
324 self.jump(engine, ecad, jump);
325 }
326 self.follow_gizmo(engine, target);
328 }
329
330 fn follow_gizmo(&mut self, engine: &mut EngineState, target: Option<Target>) {
338 let wanted = match target.is_none() && !engine.ref_select_active() {
339 true => self.selected.clone(),
340 false => None,
341 };
342 let refusal = wanted
359 .as_deref()
360 .and_then(|address| engine.port_point_gizmo_refusal(address));
361 let settled = wanted == self.gizmo_armed_for
362 && (wanted.is_none() || engine.transform_armed() || refusal.is_some());
363 if settled {
364 return;
365 }
366 self.gizmo_armed_for = wanted.clone();
367 match wanted {
368 Some(address) => {
372 engine.arm_transform_for_port_point(&address);
373 }
374 None => {
378 if engine.transform_armed_port_point().is_some() {
379 engine.disarm_transform();
380 }
381 }
382 }
383 }
384
385 fn pick(
396 &mut self,
397 engine: &mut EngineState,
398 ecad: &mut Editors,
399 target: Option<Target>,
400 address: Option<String>,
401 ) {
402 self.selected = address.clone();
403 match target {
404 Some(target) => {
405 if let Some((_, name)) =
409 address.as_deref().and_then(brep_kernel::split_address)
410 {
411 ecad.focus(target, name.to_string());
412 ecad.apply_focus(target);
413 }
414 self.adopted = editor_selection(ecad, target)
420 .map(|held| (surface_of(target), held));
421 }
422 None => {
426 if let Some(address) = address.as_deref() {
427 if resolved(engine, address) {
428 engine.select_by_name("solid", address);
429 }
430 }
431 self.adopted = engine
437 .selected_port_point()
438 .map(|held| (MODEL_SURFACE, held));
439 }
440 }
441 }
442
443 fn group_header(
445 &mut self,
446 ui: &mut egui::Ui,
447 gi: usize,
448 group: &PortDeclaration,
449 ) -> Option<(Edit, Option<String>)> {
450 let mut asked = None;
451 ui.horizontal(|ui| {
452 let mut name = group.name.clone();
453 let field = ui
454 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
455 .on_hover_text("The group's name — the first half of every address in it (`J1` in `J1.VCC`). `:`, `.` and `/` are refused.");
456 self.hits.insert(format!("qualify:group:{gi}:name"), field.rect);
457 if field.changed() {
458 asked = Some((Edit::GroupName(gi, name), Some(format!("group:{gi}:name"))));
459 }
460
461 let mut purpose = group.purpose.clone();
462 let combo = egui::ComboBox::from_id_salt(("qualify-purpose", gi))
463 .selected_text(if purpose.is_empty() { "purpose" } else { purpose.as_str() })
464 .width(76.0)
465 .show_ui(ui, |ui| {
466 let mut offered: Vec<String> =
472 PURPOSES.iter().map(|p| (*p).to_string()).collect();
473 if !group.purpose.is_empty() && !PURPOSES.contains(&group.purpose.as_str()) {
474 offered.push(group.purpose.clone());
475 }
476 for candidate in offered {
477 let item = ui.selectable_label(purpose == candidate, &candidate);
478 self.hits
479 .insert(format!("qualify:group:{gi}:purpose:{candidate}"), item.rect);
480 if item.clicked() {
481 purpose = candidate;
482 }
483 }
484 });
485 self.hits.insert(format!("qualify:group:{gi}:purpose"), combo.response.rect);
486 if purpose != group.purpose {
487 asked = Some((Edit::GroupPurpose(gi, purpose), None));
488 }
489
490 ui.label(egui::RichText::new("unit").weak());
491 let mut unit = group.symbol_unit.map(|unit| unit.to_string()).unwrap_or_default();
492 let field = ui
493 .add(egui::TextEdit::singleline(&mut unit).desired_width(24.0))
494 .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.");
495 self.hits.insert(format!("qualify:group:{gi}:unit"), field.rect);
496 if field.changed() {
497 let parsed = unit.trim().parse::<u32>().ok();
498 if parsed.is_some() || unit.trim().is_empty() {
502 asked = Some((Edit::GroupUnit(gi, parsed), Some(format!("group:{gi}:unit"))));
503 }
504 }
505
506 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
507 let remove = ui
508 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
509 .on_hover_text("Remove this group and every point in it — and the pins bound to them");
510 self.hits.insert(format!("qualify:group:{gi}:remove"), remove.rect);
511 if remove.clicked() {
512 asked = Some((Edit::RemoveGroup(gi), None));
513 }
514 });
515 });
516 asked
517 }
518
519 #[allow(clippy::too_many_arguments)]
524 fn point_row(
525 &mut self,
526 ui: &mut egui::Ui,
527 engine: &EngineState,
528 gi: usize,
529 pi: usize,
530 point: &brep_kernel::PortPoint,
531 address: &str,
532 selected: bool,
533 pick: &mut Option<Option<String>>,
534 ) -> Option<(Edit, Option<String>)> {
535 let mut asked = None;
536 ui.horizontal(|ui| {
537 let label = crate::icon_text::selectable_icon_label(ui, selected, GLYPH_SELECT)
538 .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"));
539 self.hits.insert(format!("qualify:point:{gi}:{pi}:select"), label.rect);
540 if label.clicked() {
541 *pick = Some((!selected).then(|| address.to_string()));
542 }
543 let mut name = point.name.clone();
544 let field = ui
545 .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
546 .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.");
547 self.hits.insert(format!("qualify:point:{gi}:{pi}:name"), field.rect);
548 if field.changed() {
549 asked = Some((Edit::PointName(gi, pi, name), Some(format!("point:{gi}:{pi}:name"))));
550 }
551 ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
552 let remove = ui
553 .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
554 .on_hover_text("Remove this connection point — and the pin bound to it");
555 self.hits.insert(format!("qualify:point:{gi}:{pi}:remove"), remove.rect);
556 if remove.clicked() {
557 asked = Some((Edit::RemovePoint(gi, pi), None));
558 }
559 ui.add_space(4.0);
560 self.presence(ui, engine, gi, pi, address, &point.name);
561 });
562 });
563 asked
564 }
565
566 fn point_fields(
575 &mut self,
576 ui: &mut egui::Ui,
577 engine: &EngineState,
578 gi: usize,
579 pi: usize,
580 point: &brep_kernel::PortPoint,
581 address: &str,
582 target: Option<Target>,
583 refs: &mut Option<(String, PortRefField, bool)>,
584 ) -> Option<(Edit, Option<String>)> {
585 let mut asked = None;
586 let mapped = point
592 .maps_to
593 .as_deref()
594 .map(str::trim)
595 .is_some_and(|target| !target.is_empty());
596 ui.indent(("qualify-point", gi, pi), |ui| {
597 if mapped {
598 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
599 asked = Some(mapped_asked);
600 }
601 self.seat_line(ui, engine, address, point);
602 return;
603 }
604 let seat_fields: &[(PortRefField, &str, &str)] = &[
608 (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."),
609 (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."),
610 (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}."),
611 ];
612 self.section(ui, "Seated on");
613 for &(field, caption, hover) in seat_fields {
614 ui.horizontal(|ui| {
615 ui.label(egui::RichText::new(caption).weak());
616 let key = field.key();
617 let mut text = optional_text(point, key);
618 let field_ui = ui
619 .add(egui::TextEdit::singleline(&mut text).desired_width(120.0))
620 .on_hover_text(hover);
621 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field_ui.rect);
622 if field_ui.changed() {
623 asked = Some((
624 Edit::PointText(gi, pi, key, text),
625 Some(format!("point:{gi}:{pi}:{key}")),
626 ));
627 }
628 let pickable = target.is_none();
632 let pick = ui
633 .add_enabled(
634 pickable,
635 crate::icon_text::icon_button(ui, GLYPH_PICK).small(),
636 )
637 .on_hover_text("Pick it in the 3D view")
638 .on_disabled_hover_text("Go to the 3D model to pick geometry");
639 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:pick"), pick.rect);
640 if pick.clicked() {
641 *refs = Some((address.to_string(), field, true));
642 }
643 let has = !optional_text(point, key).trim().is_empty();
644 let clear = ui
645 .add_enabled(
646 has,
647 crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small(),
648 )
649 .on_hover_text("Unseat it — the offset below stays as it is, read from the part origin");
650 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:clear"), clear.rect);
651 if clear.clicked() {
652 *refs = Some((address.to_string(), field, false));
653 }
654 });
655 }
656 self.seat_line(ui, engine, address, point);
657 if let Some(flip) = self.contact_line(ui, engine, gi, pi, address, point) {
658 asked = Some(flip);
659 }
660
661 self.section(ui, "Placement");
663 let seated = point.point_ref.is_some()
664 || point.direction_ref.is_some()
665 || point.contact_body.is_some();
666 for (key, caption, hover) in [
667 ("position", "Offset", if seated {
668 "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."
669 } else {
670 "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."
671 }),
672 ("rotationEuler", "Angle", if seated {
673 "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\"."
674 } else {
675 "The rotation applied to +X to get the direction a wire leaves along, in degrees."
676 }),
677 ] {
678 ui.horizontal(|ui| {
679 ui.label(egui::RichText::new(caption).weak());
680 for axis in 0..3 {
681 let mut text = transform_component(point, key, axis);
682 let field = ui
683 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
684 .on_hover_text(hover);
685 self.hits
686 .insert(format!("qualify:point:{gi}:{pi}:{key}{axis}"), field.rect);
687 if field.changed() {
688 asked = Some((
689 Edit::PointTransform(gi, pi, key, axis, text),
690 Some(format!("point:{gi}:{pi}:{key}{axis}")),
691 ));
692 }
693 }
694 });
695 }
696 self.gizmo_line(ui, engine, address, target);
697
698 self.section(ui, "Wire");
700 ui.horizontal(|ui| {
701 for (key, caption, hover) in [
702 ("extension", "Extension", "The straight run a wire keeps before it may bend. Empty takes the default."),
703 ("displayLength", "Drawn", "How long the point's line is drawn. Empty takes the default."),
704 ] {
705 ui.label(egui::RichText::new(caption).weak());
706 let mut text = optional_text(point, key);
707 let field = ui
708 .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
709 .on_hover_text(hover);
710 self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field.rect);
711 if field.changed() {
712 asked = Some((
713 Edit::PointText(gi, pi, key, text),
714 Some(format!("point:{gi}:{pi}:{key}")),
715 ));
716 }
717 }
718 });
719 let mut reverse = point.reverse_direction;
720 let toggle = ui
721 .checkbox(&mut reverse, "Leaves the other way")
722 .on_hover_text("Flip the direction a wire leaves along, without disturbing the seat");
723 self.hits.insert(format!("qualify:point:{gi}:{pi}:reverse"), toggle.rect);
724 if toggle.changed() {
725 asked = Some((Edit::PointReverse(gi, pi, reverse), None));
726 }
727
728 if !engine.assembly_components().is_empty() {
733 if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
734 asked = Some(mapped_asked);
735 }
736 }
737 });
738 asked
739 }
740
741 fn maps_to_field(
744 &mut self,
745 ui: &mut egui::Ui,
746 gi: usize,
747 pi: usize,
748 point: &brep_kernel::PortPoint,
749 ) -> Option<(Edit, Option<String>)> {
750 let mut asked = None;
751 self.section(ui, "Assembly");
752 ui.horizontal(|ui| {
753 ui.label(egui::RichText::new("Maps to").weak());
754 let mut text = optional_text(point, "mapsTo");
755 let field = ui
756 .add(egui::TextEdit::singleline(&mut text).desired_width(130.0))
757 .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.");
758 self.hits.insert(format!("qualify:point:{gi}:{pi}:mapsTo"), field.rect);
759 if field.changed() {
760 asked = Some((
761 Edit::PointText(gi, pi, "mapsTo", text),
762 Some(format!("point:{gi}:{pi}:mapsTo")),
763 ));
764 }
765 });
766 asked
767 }
768
769 fn section(&mut self, ui: &mut egui::Ui, caption: &str) {
771 ui.add_space(3.0);
772 ui.label(egui::RichText::new(caption).small().strong());
773 }
774
775 fn pin_seat_line(&mut self, ui: &mut egui::Ui, seat: &super::pin_seats::PinSeat) {
781 let text = match &seat.message {
782 Some(message) => egui::RichText::new(message).color(WARN_COLOR).small(),
783 None => egui::RichText::new(format!("Pin {} is on pad {}", seat.pin, seat.pin)).color(OK_COLOR).small(),
784 };
785 let label = ui.label(text);
786 self.hits.insert(format!("qualify:pinseat:{}", seat.address), label.rect);
787 }
788
789 fn seat_line(
790 &mut self,
791 ui: &mut egui::Ui,
792 engine: &EngineState,
793 address: &str,
794 point: &brep_kernel::PortPoint,
795 ) {
796 let seated = !optional_text(point, "pointRef").trim().is_empty()
797 || !optional_text(point, "directionRef").trim().is_empty()
798 || !optional_text(point, "contactBody").trim().is_empty();
799 let text = match engine.port_point_row(address) {
800 Some(row) if seated => format!(
801 "seated at ({}), facing ({})",
802 triple(row.seat.origin),
803 triple(row.seat.x),
804 ),
805 Some(row) => format!("at ({}), facing ({})", triple(row.position), triple(row.direction)),
806 None => "not resolved by the last run".to_string(),
809 };
810 let label = ui.label(egui::RichText::new(text).weak().small());
811 self.hits.insert("qualify:seat".into(), label.rect);
812 }
813
814 fn contact_line(
820 &mut self,
821 ui: &mut egui::Ui,
822 engine: &EngineState,
823 gi: usize,
824 pi: usize,
825 address: &str,
826 point: &brep_kernel::PortPoint,
827 ) -> Option<(Edit, Option<String>)> {
828 let contact = engine.port_point_row(address)?.contact.clone()?;
829 let mut asked = None;
830 ui.horizontal(|ui| {
831 let text = if contact.seats_origin {
832 format!(
833 "wire end: the {} end of {} at ({})",
834 contact.end,
835 contact.body,
836 triple(contact.wire_end)
837 )
838 } else {
839 format!("axis of {} ({}); the point is seated above", contact.body, triple(contact.axis))
840 };
841 let label = ui.label(egui::RichText::new(text).weak().small());
842 self.hits.insert("qualify:contact".into(), label.rect);
843 if contact.seats_origin {
844 let flip = ui
845 .small_button("Other end")
846 .on_hover_text("Attach the wire at the body's other end (Leaves the other way)");
847 self.hits.insert(format!("qualify:point:{gi}:{pi}:contact:flip"), flip.rect);
848 if flip.clicked() {
849 asked = Some((Edit::PointReverse(gi, pi, !point.reverse_direction), None));
850 }
851 }
852 });
853 asked
854 }
855
856 fn gizmo_line(
858 &mut self,
859 ui: &mut egui::Ui,
860 engine: &EngineState,
861 address: &str,
862 target: Option<Target>,
863 ) {
864 let text = match (target, engine.port_point_gizmo_refusal(address)) {
869 (Some(_), _) => "the move/rotate handles arm on the 3D surface".to_string(),
870 (None, Some(expression)) => format!(
871 "no handles: '{expression}' places this point, and a drag writes numbers"
872 ),
873 (None, None) => {
874 "the move/rotate handles are on it — a drag writes the offset above".to_string()
875 }
876 };
877 let label = ui.label(egui::RichText::new(text).weak().small());
878 self.hits.insert("qualify:gizmo".into(), label.rect);
879 }
880
881 fn presence(
886 &mut self,
887 ui: &mut egui::Ui,
888 engine: &EngineState,
889 gi: usize,
890 pi: usize,
891 address: &str,
892 name: &str,
893 ) {
894 let pinned = engine
895 .history
896 .pin_point_report()
897 .map(|report| report.pairs.iter().any(|pair| pair.point == address));
898 let padded = pad_numbers(engine).iter().any(|number| number == name);
899 for (key, state, present, absent) in [
900 (
901 "symbol",
902 pinned,
903 "a symbol pin carries this name",
904 "no symbol pin carries this name, so nothing on the schematic is this point",
905 ),
906 (
907 "pads",
908 Some(padded),
909 "a pad carries this number",
910 "no pad carries this number",
911 ),
912 (
913 "model",
914 Some(resolved(engine, address)),
915 "the last run resolved it in 3D",
916 "the last run did not resolve it, so there is no geometry to show",
917 ),
918 ] {
919 let (glyph, color, hover) = match state {
920 Some(true) => (GLYPH_PRESENT, OK_COLOR, present),
921 Some(false) => (GLYPH_ABSENT, WARN_COLOR, absent),
922 None => (
925 GLYPH_ABSENT,
926 ui.visuals().weak_text_color(),
927 "this part has no symbol",
928 ),
929 };
930 let lamp = lamp(ui, glyph, color).on_hover_text(format!("{key}: {hover}"));
931 self.hits
932 .insert(format!("qualify:point:{gi}:{pi}:lamp:{key}"), lamp.rect);
933 }
934 }
935
936 fn jump_row(&mut self, ui: &mut egui::Ui, address: &str, target: Option<Target>) -> Option<Jump> {
939 let mut asked = None;
940 ui.horizontal(|ui| {
941 ui.label(egui::RichText::new("Look at it in").weak());
942 for (jump, key, label, hover) in [
943 (Jump::Symbol, "symbol", "Symbol", "Open the schematic symbol with this point's PIN selected"),
944 (Jump::Pads, "pads", "Pads", "Open the footprint with this point's PAD selected"),
945 (Jump::Model, "model", "3D", "Show the model with this point's geometry selected"),
946 ] {
947 let here = match jump {
948 Jump::Symbol => target == Some(Target::Symbol),
949 Jump::Pads => target == Some(Target::Pads),
950 Jump::Model => target.is_none(),
951 };
952 let button = ui
953 .add_enabled(!here, egui::Button::new(label).small())
954 .on_hover_text(format!("{hover} ({address})"))
955 .on_disabled_hover_text("You are looking at it");
956 self.hits.insert(format!("qualify:jump:{key}"), button.rect);
957 if button.clicked() {
958 asked = Some(jump);
959 }
960 }
961 });
962 asked
963 }
964
965 fn reports(&mut self, ui: &mut egui::Ui, engine: &EngineState) {
968 let mut problem = 0usize;
969 let mut line = |ui: &mut egui::Ui,
970 hits: &mut HashMap<String, egui::Rect>,
971 text: String,
972 color: egui::Color32| {
973 let label = ui.label(egui::RichText::new(text).weak().color(color));
974 hits.insert(format!("qualify:problem:{problem}"), label.rect);
975 problem += 1;
976 };
977
978 ui.label(egui::RichText::new("Pins and points").strong());
979 match engine.history.pin_point_report() {
980 None => {
981 ui.label(
982 egui::RichText::new("this part has no symbol, so its points bind to no pins")
983 .weak(),
984 );
985 }
986 Some(PinPointReport { pairs, problems }) => {
987 ui.label(
988 egui::RichText::new(format!(
989 "{} pin{} paired",
990 pairs.len(),
991 if pairs.len() == 1 { "" } else { "s" }
992 ))
993 .weak()
994 .color(if problems.is_empty() { OK_COLOR } else { WARN_COLOR }),
995 );
996 for entry in &problems {
997 line(ui, &mut self.hits, entry.message(), WARN_COLOR);
998 }
999 }
1000 }
1001 if let Some(hold) = engine.history.pin_port_hold() {
1005 line(ui, &mut self.hits, format!("not carried to the pins: {hold}"), WARN_COLOR);
1006 }
1007
1008 ui.add_space(2.0);
1009 ui.label(egui::RichText::new("Ports").strong());
1010 match engine.ports_report() {
1011 None => {
1012 ui.label(egui::RichText::new("the model has not run yet").weak());
1013 }
1014 Some(report) => {
1015 ui.label(
1016 egui::RichText::new(format!(
1017 "{} point{} resolved | {}",
1018 report.points.len(),
1019 if report.points.len() == 1 { "" } else { "s" },
1020 if report.boundary {
1021 "a boundary: a parent sees only what this document declares"
1022 } else {
1023 "transparent: a parent sees this document's children too"
1024 },
1025 ))
1026 .weak()
1027 .color(if report.problems.is_empty() { OK_COLOR } else { ERROR_COLOR }),
1028 )
1029 .on_hover_text(if report.boundary {
1030 "A board hides its components behind the ports it declares itself (`portBoundary`, or a `pcb` block)."
1031 } else {
1032 "An enclosure does not hide the parts in it: their points are exported namespaced."
1033 });
1034 for entry in &report.problems {
1035 line(ui, &mut self.hits, entry.clone(), ERROR_COLOR);
1036 }
1037 }
1038 }
1039 if let Some(report) = engine.ports_report() {
1042 for row in report.points.iter().filter(|row| row.maps_to.is_some()) {
1043 let target = row.maps_to.clone().unwrap_or_default();
1044 line(
1045 ui,
1046 &mut self.hits,
1047 format!("{} \u{2192} {target}", row.address),
1048 ui.visuals().weak_text_color(),
1049 );
1050 }
1051 }
1052 }
1053
1054 fn apply(&mut self, engine: &mut EngineState, edit: Edit, coalesce: Option<&str>) {
1059 let mut block = engine
1060 .history
1061 .ports_block()
1062 .and_then(Value::as_array)
1063 .cloned()
1064 .unwrap_or_default();
1065 match edit {
1066 Edit::AddGroup => {
1067 block.push(serde_json::json!({
1068 "name": unique_group_name(&block),
1069 "purpose": PURPOSES[0],
1070 "points": [],
1071 }));
1072 }
1073 Edit::RemoveGroup(gi) => {
1074 if gi < block.len() {
1075 block.remove(gi);
1076 }
1077 }
1078 Edit::GroupName(gi, name) => {
1079 let was = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str);
1084 if let (Some(was), Some(address)) = (was, self.selected.clone()) {
1085 if let Some((port, point)) = brep_kernel::split_address(&address) {
1086 if port == was {
1087 self.selected = Some(brep_kernel::port_address(&name, point));
1088 }
1089 }
1090 }
1091 set_group(&mut block, gi, "name", Value::String(name));
1092 }
1093 Edit::GroupPurpose(gi, purpose) => {
1094 set_group(&mut block, gi, "purpose", Value::String(purpose));
1095 }
1096 Edit::GroupUnit(gi, unit) => match unit {
1097 Some(unit) => set_group(&mut block, gi, "symbolUnit", Value::from(unit)),
1098 None => remove_group_key(&mut block, gi, "symbolUnit"),
1099 },
1100 Edit::AddPoint(gi) => {
1101 if let Some(points) = points_mut(&mut block, gi) {
1102 let name = unique_point_name(points);
1103 points.push(serde_json::json!({
1104 "name": name,
1105 "transform": { "position": [0.0, 0.0, 0.0], "rotationEuler": [0.0, 0.0, 0.0] },
1106 }));
1107 }
1108 }
1109 Edit::RemovePoint(gi, pi) => {
1110 if let Some(points) = points_mut(&mut block, gi) {
1111 if pi < points.len() {
1112 points.remove(pi);
1113 }
1114 }
1115 }
1116 Edit::PointName(gi, pi, name) => {
1117 if let Some(group) = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str) {
1120 self.selected = Some(brep_kernel::port_address(group, &name));
1121 }
1122 set_point(&mut block, gi, pi, "name", Value::String(name));
1123 }
1124 Edit::PointText(gi, pi, key, text) => match text.trim().is_empty() {
1125 true => remove_point_key(&mut block, gi, pi, key),
1126 false => set_point(&mut block, gi, pi, key, match key {
1130 "pointRef" | "directionRef" | "contactBody" | "mapsTo" => {
1131 Value::String(text.trim().to_string())
1132 }
1133 _ => scalar(&text),
1134 }),
1135 },
1136 Edit::PointTransform(gi, pi, key, axis, text) => {
1137 set_transform_component(&mut block, gi, pi, key, axis, scalar(&text));
1138 }
1139 Edit::PointReverse(gi, pi, reverse) => match reverse {
1140 true => set_point(&mut block, gi, pi, "reverseDirection", Value::Bool(true)),
1141 false => remove_point_key(&mut block, gi, pi, "reverseDirection"),
1142 },
1143 }
1144 if block.is_empty() {
1149 engine.history.set_ports_block(None, None);
1150 engine.push_notice("the last connection-point group is gone; the Qualify pane closes with it");
1151 return;
1152 }
1153 engine.history.set_ports_block(Some(Value::Array(block)), coalesce);
1154 }
1155
1156 fn jump(&mut self, engine: &mut EngineState, ecad: &mut Editors, jump: Jump) {
1164 let Some(address) = self.selected.clone() else {
1165 return;
1166 };
1167 let Some((_, name)) = brep_kernel::split_address(&address) else {
1168 return;
1169 };
1170 let (target, workbench) = match jump {
1171 Jump::Symbol => (Some(Target::Symbol), "symbol"),
1172 Jump::Pads => (Some(Target::Pads), "pads"),
1173 Jump::Model => (None, MODEL_WORKBENCH),
1174 };
1175 match target {
1176 Some(target) => ecad.focus(target, name.to_string()),
1177 None => {
1178 if resolved(engine, &address) {
1183 engine.select_by_name("solid", &address);
1184 } else {
1185 engine.push_notice(format!(
1186 "{address} has no geometry yet \u{2014} the last run did not resolve it"
1187 ));
1188 }
1189 }
1190 }
1191 let already = match jump {
1195 Jump::Model => Target::of_workbench(&engine.settings.workbench).is_none(),
1196 _ => false,
1197 };
1198 if !already && engine.settings.workbench != workbench {
1199 let _ = engine
1204 .apply_settings_json(&serde_json::json!({ "workbench": workbench }).to_string());
1205 }
1206 }
1207
1208 fn adopt_editor_selection(&mut self, engine: &EngineState, ecad: &Editors, target: Option<Target>) {
1212 let (surface, label) = match target {
1217 None => (MODEL_SURFACE, engine.selected_port_point()),
1218 Some(target @ (Target::Symbol | Target::Pads)) => {
1219 (surface_of(target), editor_selection(ecad, target))
1220 }
1221 Some(_) => return,
1224 };
1225 let Some(label) = label else {
1226 if self.adopted.as_ref().is_some_and(|(from, _)| *from == surface) {
1229 self.adopted = None;
1230 }
1231 return;
1232 };
1233 if self.adopted.as_ref().is_some_and(|(from, what)| *from == surface && *what == label) {
1234 return;
1235 }
1236 self.adopted = Some((surface, label.clone()));
1237 if surface == MODEL_SURFACE {
1240 self.selected = Some(label);
1241 return;
1242 }
1243 let unit = engine
1246 .history
1247 .pins()
1248 .unwrap_or_default()
1249 .into_iter()
1250 .find(|pin| pin.label == label)
1251 .map(|pin| pin.unit)
1252 .unwrap_or(1);
1253 if let Some(group) = engine.history.port_group_for_unit(unit) {
1254 self.selected = Some(brep_kernel::port_address(&group, &label));
1255 }
1256 }
1257}
1258
1259fn resolved(engine: &EngineState, address: &str) -> bool {
1264 engine
1265 .ports_report()
1266 .is_some_and(|report| report.points.iter().any(|row| row.address == address))
1267}
1268
1269fn editor_selection(ecad: &Editors, target: Target) -> Option<String> {
1273 match target {
1274 Target::Symbol => ecad.symbol.selected_pin().map(str::to_string),
1275 Target::Pads => ecad.pads.selected_pad().map(str::to_string),
1276 Target::Pcb => None,
1277 }
1278}
1279
1280fn surface_of(target: Target) -> &'static str {
1285 match target {
1286 Target::Symbol => "symbol",
1287 Target::Pads => "pads",
1288 Target::Pcb => "pcb",
1289 }
1290}
1291
1292fn set_group(block: &mut [Value], gi: usize, key: &str, value: Value) {
1298 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1299 object.insert(key.into(), value);
1300 }
1301}
1302
1303fn remove_group_key(block: &mut [Value], gi: usize, key: &str) {
1304 if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1305 object.remove(key);
1306 }
1307}
1308
1309fn points_mut(block: &mut [Value], gi: usize) -> Option<&mut Vec<Value>> {
1310 let group = block.get_mut(gi)?.as_object_mut()?;
1311 group.entry("points").or_insert_with(|| Value::Array(Vec::new())).as_array_mut()
1312}
1313
1314fn point_mut<'a>(block: &'a mut [Value], gi: usize, pi: usize) -> Option<&'a mut serde_json::Map<String, Value>> {
1315 points_mut(block, gi)?.get_mut(pi)?.as_object_mut()
1316}
1317
1318fn set_point(block: &mut [Value], gi: usize, pi: usize, key: &str, value: Value) {
1319 if let Some(point) = point_mut(block, gi, pi) {
1320 point.insert(key.into(), value);
1321 }
1322}
1323
1324fn remove_point_key(block: &mut [Value], gi: usize, pi: usize, key: &str) {
1325 if let Some(point) = point_mut(block, gi, pi) {
1326 point.remove(key);
1327 }
1328}
1329
1330fn set_transform_component(
1333 block: &mut [Value],
1334 gi: usize,
1335 pi: usize,
1336 key: &str,
1337 axis: usize,
1338 value: Value,
1339) {
1340 let Some(point) = point_mut(block, gi, pi) else {
1341 return;
1342 };
1343 let transform = point
1344 .entry("transform")
1345 .or_insert_with(|| Value::Object(Default::default()));
1346 if !transform.is_object() {
1347 *transform = Value::Object(Default::default());
1348 }
1349 let Some(transform) = transform.as_object_mut() else {
1350 return;
1351 };
1352 let axes = transform
1353 .entry(key.to_string())
1354 .or_insert_with(|| Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]));
1355 if !axes.is_array() {
1356 *axes = Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]);
1357 }
1358 if let Some(axes) = axes.as_array_mut() {
1359 while axes.len() < 3 {
1360 axes.push(Value::from(0.0));
1361 }
1362 axes[axis] = value;
1363 }
1364}
1365
1366fn scalar(text: &str) -> Value {
1371 let text = text.trim();
1372 if text.is_empty() {
1373 return Value::from(0.0);
1374 }
1375 match text.parse::<f64>() {
1376 Ok(number) => Value::from(number),
1377 Err(_) => Value::String(text.to_string()),
1378 }
1379}
1380
1381fn transform_component(point: &brep_kernel::PortPoint, key: &str, axis: usize) -> String {
1385 match point.transform.get(key).and_then(Value::as_array).and_then(|axes| axes.get(axis)) {
1386 Some(Value::Number(number)) => match number.as_f64() {
1391 Some(value) => brep_render::formatting::compact_decimal(value, 6),
1392 None => number.to_string(),
1393 },
1394 Some(Value::String(expression)) => expression.clone(),
1395 _ => "0".to_string(),
1396 }
1397}
1398
1399fn optional_text(point: &brep_kernel::PortPoint, key: &str) -> String {
1402 match key {
1403 "pointRef" => point.point_ref.clone().unwrap_or_default(),
1404 "directionRef" => point.direction_ref.clone().unwrap_or_default(),
1405 "contactBody" => point.contact_body.clone().unwrap_or_default(),
1406 "mapsTo" => point.maps_to.clone().unwrap_or_default(),
1407 "extension" => point.extension.map(|v| v.to_string()).unwrap_or_default(),
1408 "displayLength" => point.display_length.map(|v| v.to_string()).unwrap_or_default(),
1409 _ => String::new(),
1410 }
1411}
1412
1413fn lamp(ui: &mut egui::Ui, glyph: &str, color: egui::Color32) -> egui::Response {
1416 match crate::icon_text::glyph(ui, glyph, color) {
1417 Some(art) => ui.add(art),
1418 None => ui.label(egui::RichText::new(glyph).color(color)),
1419 }
1420}
1421
1422fn triple(values: [f64; 3]) -> String {
1424 values
1425 .iter()
1426 .map(|value| {
1427 let rounded = (value * 1000.0).round() / 1000.0;
1428 if rounded == 0.0 { "0".to_string() } else { format!("{rounded}") }
1430 })
1431 .collect::<Vec<_>>()
1432 .join(", ")
1433}
1434
1435fn pad_numbers(engine: &EngineState) -> Vec<String> {
1439 engine
1440 .history
1441 .pads_block()
1442 .and_then(|block| block.get("pads"))
1443 .and_then(Value::as_array)
1444 .map(|pads| {
1445 pads.iter()
1446 .filter_map(|pad| pad.get("number").and_then(Value::as_str))
1447 .map(str::to_string)
1448 .collect()
1449 })
1450 .unwrap_or_default()
1451}
1452
1453fn unique_group_name(block: &[Value]) -> String {
1455 let taken: Vec<&str> = block
1456 .iter()
1457 .filter_map(|group| group.get("name").and_then(Value::as_str))
1458 .collect();
1459 (1..).map(|n| format!("J{n}")).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1460}
1461
1462fn unique_point_name(points: &[Value]) -> String {
1465 let taken: Vec<&str> = points
1466 .iter()
1467 .filter_map(|point| point.get("name").and_then(Value::as_str))
1468 .collect();
1469 (1..).map(|n| n.to_string()).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1470}
1471
1472pub static HIT_KEYS: &[HitKeyDoc] = &[
1473 HitKeyDoc { panel: "qualify", prefix: "qualify:panel:clip", meaning: "the visible region of the pane", command: None },
1474 HitKeyDoc { panel: "qualify", prefix: "qualify:add_group", meaning: "declare another port group", command: None },
1475 HitKeyDoc { panel: "qualify", prefix: "qualify:group:", meaning: "a port group's name, purpose, symbol unit, add-point or remove", command: None },
1476 HitKeyDoc { panel: "qualify", prefix: "qualify:point:", meaning: "a connection point's select, name, remove, or one of the selected point's fields", command: None },
1477 HitKeyDoc { panel: "qualify", prefix: "qualify:jump:", meaning: "carry the selected point to the symbol, the pads or the 3D model", command: None },
1478 HitKeyDoc { panel: "qualify", prefix: "qualify:hint", meaning: "what selecting a point is for, shown while none is", command: None },
1479 HitKeyDoc { panel: "qualify", prefix: "qualify:seat", meaning: "what the last run made of the selected point's seat", command: None },
1480 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 },
1481 HitKeyDoc { panel: "qualify", prefix: "qualify:gizmo", meaning: "whether the move/rotate handles are on the selected point", command: None },
1482 HitKeyDoc { panel: "qualify", prefix: "qualify:problem:", meaning: "one line of the pin/point or ports report", command: None },
1483];
1484