Skip to main content

brep_app/panels/
qualify.rs

1//! The **Qualify** panel — a part's declared CONNECTION POINTS, on whichever
2//! surface the user is looking at.
3//!
4//! A part document carries `ports` beside `features`, `symbol` and `pads`: a
5//! list of named GROUPS, each with a `purpose` (`pcb`, `wiring`, `piping`, …)
6//! and a list of points whose NAME is their identity. The kernel resolves that
7//! block at the tail of every history run (`brep_kernel`'s `ports`), binds each
8//! point to the symbol pin of the same name within its unit's group
9//! (`part_pins`), and reports what does not hold. Until now nothing drew any of
10//! it: the block was written by the KiCad import, by editing a pin, or by hand.
11//!
12//! This panel is that UI. It is ONE panel on THREE surfaces — the schematic
13//! symbol, the pads, and the 3D model — because a connection point is one thing
14//! seen from three places, and the job it exists for is crossing between them:
15//! pick a point here and jump to its pin, its pad or its geometry with the
16//! point still selected on the other side.
17//!
18//! # What it draws
19//!
20//! * the port GROUPS, each with its name, its purpose and the symbol unit whose
21//!   pins bind into it, and the points in it;
22//! * the SELECTED point's fields, expanded in place: its placement (position
23//!   and rotation, each component a number or an expression string, exactly as
24//!   the block carries it), the geometry that seats it (`pointRef` /
25//!   `directionRef`), its straight run, and — for an ASSEMBLY — the descendant
26//!   point it maps to;
27//! * the three JUMP buttons, which switch surface AND carry the selection;
28//! * the two CONSISTENCY REPORTS the model already produces: `History::pin_point_report`
29//!   (every pin paired with its point, and everything that does not pair) and
30//!   the ports tail's own report (`EngineState::ports_report` — whether this
31//!   document is an encapsulation boundary, every point it resolved, and every
32//!   name it refused).
33//!
34//! # When it is on screen
35//!
36//! Exactly while the part declares a connection point. That is not a workbench
37//! claim — it is a DOCUMENT condition ([`crate::workbench::PANEL_CONDITIONS`]),
38//! so the pane appears on every surface at once and a part with no connection
39//! points is not offered an empty panel. The first group therefore comes from
40//! somewhere else: the KiCad import, the pin binding, or the Wire harness
41//! workbench's **Declare connection point** button, which exists for exactly
42//! this reason.
43//!
44//! # Edits
45//!
46//! Every edit is a write of the WHOLE `ports` block through
47//! `History::set_ports_block`, which carries the pin/point follow inside it: a
48//! renamed point renames its pin (and the pad matching that pin) in the same
49//! undo step, a new point gets a pin, and a removed point loses one. The block
50//! is edited as raw JSON rather than round-tripped through
51//! [`brep_kernel::PortDeclaration`], so a field this panel does not know about
52//! survives an edit to the field beside it.
53//!
54//! Each field carries its own COALESCE KEY, so typing a name is one undo entry
55//! and not one per keystroke — the same key the eCAD editors hand the history.
56
57use 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
67/// The row glyphs, every one catalogued artwork (`assets/glyphs`) drawn by
68/// [`crate::icon_text`] — this app ships no icon font, so an uncatalogued
69/// character paints as tofu.
70const GLYPH_SELECT: &str = "\u{25CE}"; // ◎ select this connection point
71const GLYPH_REMOVE: &str = "\u{2715}"; // ✕ remove
72const GLYPH_ADD: &str = "\u{FF0B}"; // + add
73const GLYPH_PICK: &str = "\u{2316}"; // ⌖ pick this reference in the 3D view
74const GLYPH_PRESENT: &str = "\u{25CF}"; // ● this surface carries the point
75const GLYPH_ABSENT: &str = "\u{25CB}"; // ○ it does not
76
77/// The purposes offered in the dropdown. The kernel never enumerates
78/// `purpose` — it carries the string — so a value the document already holds is
79/// offered beside these rather than silently rewritten.
80const PURPOSES: [&str; 3] = ["pcb", "wiring", "piping"];
81
82/// A problem's amber and a refusal's red, as the harness panel uses them.
83const 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);
86/// The destructive red the other panels use for a remove affordance.
87const REMOVE_RED: egui::Color32 = egui::Color32::from_rgb(0xd8, 0x54, 0x4f);
88
89/// The 3D workbench a jump from an eCAD editor lands in. A part's connection
90/// points are the harness's wire ends, so this is where looking at one in 3D
91/// means something; a jump from a workbench that ALREADY draws the model does
92/// not switch at all (see [`QualifyPanel::jump`]).
93const MODEL_WORKBENCH: &str = "wireHarness";
94
95/// The key the 3D surface's adopted selection is remembered under, beside the
96/// two eCAD editors'.
97const MODEL_SURFACE: &str = "model";
98
99/// One edit the panel's draw asked for, applied after it.
100enum 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    /// One of the point's optional STRING fields, by JSON key; an empty string
108    /// removes the key.
109    PointText(usize, usize, &'static str, String),
110    /// One component of `transform.position` / `transform.rotationEuler`: a
111    /// number when it parses as one, else an expression string.
112    PointTransform(usize, usize, &'static str, usize, String),
113    PointReverse(usize, usize, bool),
114    AddPoint(usize),
115    RemovePoint(usize, usize),
116}
117
118/// Where a jump goes.
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Jump {
121    Symbol,
122    Pads,
123    Model,
124}
125
126/// The panel's transient UI state. Everything it draws comes from the engine.
127pub struct QualifyPanel {
128    hits: HashMap<String, egui::Rect>,
129    /// The selected connection point, by part-local ADDRESS (`J1.VCC`). Held
130    /// by address rather than by index so an edit that reorders the block does
131    /// not move the selection to another point.
132    selected: Option<String>,
133    /// The editor selection last adopted, so an eCAD pick is adopted ONCE: a
134    /// user who picks a point here and then a different pin there gets the pin,
135    /// and one who picks here and leaves the editor alone keeps their pick.
136    /// The 3D surface goes through the same field under [`MODEL_SURFACE`].
137    adopted: Option<(&'static str, String)>,
138    /// The selection this panel last acted on for the GIZMO. The gizmo is
139    /// shared — the History panel arms it on a feature — so this panel acts on
140    /// a CHANGE of selection and not every frame: otherwise it would take the
141    /// handles back off a feature dialog on the frame after it armed them, and
142    /// it would re-ask (and re-notice) a refusal once a frame.
143    gizmo_armed_for: Option<String>,
144    /// The pin seat check of the open part (`pin_seats`), with the run and
145    /// history revision it was read at: it cuts meshes, so not once a frame.
146    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    /// Drop the published rects: the dock calls this for a pane it did not
166    /// draw this frame (`DockState::ui`), whose widgets are not on screen.
167    pub fn clear_hits(&mut self) {
168        self.hits.clear();
169    }
170
171    /// The panel's verifier global: the selected address and the surface it is
172    /// drawn on, beside the block and report the engine publishes.
173    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    /// Draw the panel. `target` is the eCAD editor on screen, or `None` where
183    /// the central tile draws the 3D model.
184    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        // An eCAD pick is a pick of the same thing: adopt it, once.
208        self.adopt_editor_selection(engine, ecad, target);
209        // A selection whose point is gone (removed, or renamed out from under
210        // it) is dropped rather than kept as a stale address.
211        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        // `(address, field, enter the picker)` — clearing a reference is the
223        // same act said with `false`, so both go through one commit.
224        let mut refs: Option<(String, PortRefField, bool)> = None;
225
226        // --- header -----------------------------------------------------------
227        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            // A pane whose whole lower half is blank until something is
248            // selected should say what to select and what it will get.
249            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        // --- the groups -------------------------------------------------------
261        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                    // The frame must not lay out wider than what is on screen,
266                    // or its right-aligned ✕ is published past the pane's edge
267                    // and a click aims into the viewport (the same clamp the
268                    // spline-anchor rows carry, for the same reason).
269                    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        // --- the reports ------------------------------------------------------
307        ui.add_space(4.0);
308        self.reports(ui, engine);
309
310        // --- act on what the draw asked for (at most one of each) --------------
311        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        // Last, so it follows whatever the frame just did to the selection.
327        self.follow_gizmo(engine, target);
328    }
329
330    /// Put the move/rotate handles on the selected point, or take them off.
331    ///
332    /// Selecting a row IS arming the gizmo, which is the convention the spline
333    /// anchors panel already set: one affordance, not a select and then a
334    /// separate arm. Only on the 3D surface, because an eCAD editor has no
335    /// viewport to drag handles in, and never while the reference picker is
336    /// up, because that picker owns the clicks.
337    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        // The gizmo is ONE shared widget, so this is deliberately not "arm what
343        // is selected, every frame". It is SETTLED — and left alone — when the
344        // selection has not changed AND one of three things is true:
345        //
346        // * nothing is wanted (and the disarm below has already run);
347        // * SOMETHING is armed. Whose it is does not matter: if a feature
348        //   dialog has taken the handles, re-arming would take them straight
349        //   back on the next frame, and this pane is drawn beside every
350        //   feature dialog in the product;
351        // * the point REFUSES the handles, which would otherwise re-ask —
352        //   and re-push its notice — sixty times a second.
353        //
354        // What that leaves is the case the plain change check got wrong: the
355        // reference picker takes the handles off at its entry, and the pane is
356        // not drawn while it is up, so on the frame it closes the selection has
357        // NOT changed and nothing is armed. That is exactly when they go back.
358        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            // A refusal is asked ONCE — the arm pushes the notice — and the
369            // reason the gizmo line shows is read from the engine, not from
370            // anything kept here.
371            Some(address) => {
372                engine.arm_transform_for_port_point(&address);
373            }
374            // Take away only what THIS panel put there. A feature's gizmo,
375            // armed from the History panel, is not ours — and neither is one
376            // on another connection point that something else armed.
377            None => {
378                if engine.transform_armed_port_point().is_some() {
379                    engine.disarm_transform();
380                }
381            }
382        }
383    }
384
385    /// Take a pick made in the panel: select `address` (or nothing) and LIGHT
386    /// IT UP on the surface the user is on.
387    ///
388    /// Lighting it up is not decoration — it is the other half of the same
389    /// sentence the jump buttons speak, and without it a pick here means
390    /// nothing until the user leaves. It also has to drive the editor through
391    /// the SAME deferred path a jump uses: the editor's own selection is what
392    /// [`Self::adopt_editor_selection`] reads back, so a panel pick that left
393    /// the editor sitting on another pin would be overwritten by that pin on
394    /// the very next frame.
395    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                // Agreeing with the editor NOW as well as after its next draw:
406                // `apply_focus` is what survives a pull, and this is what makes
407                // the pin light up on the frame of the click.
408                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                // What is remembered is what the editor ACTUALLY holds now, not
415                // what was asked of it. They differ for a point with no pin —
416                // the focus finds nothing and the editor stays where it was —
417                // and remembering the ask would make the next frame read that
418                // stale pin as a NEW editor pick and overwrite the user's.
419                self.adopted = editor_selection(ecad, target)
420                    .map(|held| (surface_of(target), held));
421            }
422            // The 3D surface: the point's own scene entities are published
423            // under its address, so this is the selection a click in the
424            // viewport makes — the Scene tree's row click, by name.
425            None => {
426                if let Some(address) = address.as_deref() {
427                    if resolved(engine, address) {
428                        engine.select_by_name("solid", address);
429                    }
430                }
431                // The same rule, on this surface: what is remembered is what
432                // the VIEWPORT holds afterwards. Deselecting here leaves the
433                // geometry lit, and remembering the ask instead would make the
434                // next frame read that as a fresh viewport pick and undo the
435                // deselection.
436                self.adopted = engine
437                    .selected_port_point()
438                    .map(|held| (MODEL_SURFACE, held));
439            }
440        }
441    }
442
443    /// One group's header row: name, purpose, symbol unit, remove.
444    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                    // The document's own value is offered beside the three when
467                    // it is none of them: the kernel carries `purpose` as a
468                    // string and never enumerates it, so a purpose a later
469                    // slice invents must not vanish because this list has not
470                    // heard of it.
471                    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                // A field being cleared reads as "no unit"; a field holding
499                // something that is not a number keeps what was there, so a
500                // half-typed value never silently unbinds a group.
501                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    /// One point's row: select, name, remove. A click on ◎ is reported as a
520    /// PICK rather than applied here, because a pick is not only a selection:
521    /// it lights the point on whatever surface is on screen, which needs the
522    /// editors and the engine.
523    #[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    /// The selected point's fields, indented under its row, in four sections:
567    /// where it is SEATED, the PLACEMENT read in that seat, what a WIRE leaving
568    /// it does, and — for an assembly — the descendant it maps to.
569    ///
570    /// The sections are the point's own sentence in order: seat it, nudge it,
571    /// say how the wire leaves, and (an assembly only) say whose point it
572    /// really is. Before this they were one flat list of eight fields in which
573    /// `pointRef` and `extension` looked like the same kind of thing.
574    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        // A MAPPED point has no placement of its own: the kernel's
587        // `resolve_point` returns on `mapsTo` before it reads the transform or
588        // either reference. Offering a seat and an offset it will ignore is
589        // three sections of lie, so a mapped point shows only the one field
590        // that decides where it is.
591        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            // --- seat ---------------------------------------------------------
605            // Every purpose offers it. On a `pcb` group the seat is checked
606            // against the pin's pad (`pin_seats`, the line under the point).
607            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                    // Picking is offered only where there is a model to pick
629                    // IN. From an eCAD editor the button would open a picker
630                    // over a schematic, which has no faces.
631                    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            // --- placement ----------------------------------------------------
662            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            // --- the wire -----------------------------------------------------
699            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            // --- the assembly declaration -------------------------------------
729            // Shown only where it can mean something: `mapsTo` says "this point
730            // IS a descendant's point", so on a part with no components it is a
731            // field that can only ever be wrong.
732            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    /// The `mapsTo` field and its heading — the only field a MAPPED point has,
742    /// and the last section of an unmapped one in a document with components.
743    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    /// A section heading inside the selected point's fields.
770    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    /// What the last run made of the point's seat, in words: where it sits and
776    /// which way it faces. This is the answer to "did my pick take?", and
777    /// without it a reference field is a string the user must trust.
778    /// Whether the point's 3D seat lands on its pin's pad (`pin_seats`): the
779    /// finding in amber, or a quiet line when it does.
780    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            // The tail resolves at the END of the run, so a point just added
807            // has nothing yet — which is a state, not a fault.
808            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    /// Which end of its contact body the point took, with the one-click flip
815    /// beside it: the default wire end is a geometric rule (the end farther
816    /// from the rest of the part), and on a connector whose pins protrude
817    /// forward it picks the mating end, so the choice is shown, not hidden.
818    /// Drawn only when the last run derived the body's axis.
819    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    /// Whether the handles are on this point, and why not when they are not.
857    fn gizmo_line(
858        &mut self,
859        ui: &mut egui::Ui,
860        engine: &EngineState,
861        address: &str,
862        target: Option<Target>,
863    ) {
864        // Asked of the ENGINE rather than inferred from the gizmo not being
865        // armed: this line is drawn a moment before `follow_gizmo` runs, so on
866        // the frame a point is selected an inference would show the refusal
867        // reason for a point that is about to arm perfectly well.
868        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    /// Three lamps per point: does a symbol PIN carry this name, does a PAD,
882    /// and did the last run resolve it in 3D. A connection point is ONE thing
883    /// on three surfaces, and this row is where that claim is either true in
884    /// front of the user or visibly not.
885    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                // No symbol at all: the question does not arise, and an amber
923                // lamp on a 3D-only part would be a fault where there is none.
924                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    /// The three JUMP buttons for the selected point. The one for the surface
937    /// already on screen is drawn pressed and does nothing.
938    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    /// The two consistency reports, which exist to be shown and were shown
966    /// nowhere: the pin/point pairing and the ports tail's own resolution.
967    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        // A HOLD is the live state of the edit in flight, not a property of the
1002        // document: the last keystroke could not be carried to the other side,
1003        // and the next one will be diffed from the same base again.
1004        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        // A point that maps DOWN says where to, since `mapsTo` is the one field
1040        // whose meaning is another document's.
1041        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    // --- acting -------------------------------------------------------------
1055
1056    /// Apply one edit to the raw block and write it back. The write carries the
1057    /// pin/point follow, and sets the flag that re-runs the history next frame.
1058    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                // Renaming a group moves EVERY address in it, and the selection
1080                // is held by address — so carry it, exactly as a point rename
1081                // does, or the point being edited deselects itself the moment
1082                // its group's name is touched.
1083                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                // The selection is held by ADDRESS, so a rename has to move it
1118                // or the point the user is editing deselects itself mid-word.
1119                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                // A reference names geometry or a point: it is TEXT even when
1127                // it reads as a number. `scalar` stored `0` as `0.0`, which the
1128                // kernel's block read refused whole (a reported bug).
1129                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        // An EMPTY block is not a block: the kernel omits it on re-serialize,
1145        // and leaving `[]` behind would keep this pane up over a part with
1146        // nothing to qualify. Removing the last group therefore closes the pane,
1147        // which is worth saying out loud.
1148        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    /// Carry the selected point to another surface: switch the workbench and
1157    /// hand the editor the selection to make when it next draws.
1158    ///
1159    /// The editor selection is DEFERRED rather than set here: the editor is
1160    /// re-handed its block on the frame it is drawn (`viewport::ecad`'s pull),
1161    /// which clears whatever it had selected, so a selection set now would be
1162    /// wiped by the switch itself.
1163    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                // The part's OWN points resolve at the TAIL of the run, so one
1179                // the last run did not resolve has nothing in the scene to
1180                // select. Selecting its name anyway would light nothing and
1181                // leave a phantom selection behind, so say so instead.
1182                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        // A workbench that ALREADY draws what was asked for is left alone: a
1192        // user in Modeling who asks to see the point in 3D wants the selection,
1193        // not to be moved to another workbench.
1194        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            // The SAME seam the workbench dropdown writes through, but NOT
1200            // persisted to the settings blob: a jump is navigation within a
1201            // document, like the assembly auto-switch, and the blob stays the
1202            // user's boot preference.
1203            let _ = engine
1204                .apply_settings_json(&serde_json::json!({ "workbench": workbench }).to_string());
1205        }
1206    }
1207
1208    /// Adopt the eCAD editor's own selection when it names a connection point:
1209    /// picking pin `VCC` in the symbol selects `J1.VCC` here, which is the half
1210    /// of "select it there, look at it here" the jump buttons do not cover.
1211    fn adopt_editor_selection(&mut self, engine: &EngineState, ecad: &Editors, target: Option<Target>) {
1212        // The 3D surface has a selection of its own, and it already names the
1213        // point: a declared point draws as a sheet keyed by its address. This
1214        // is the direction the panel could not reach before — clicking a point
1215        // in the viewport now opens it here.
1216        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            // A schematic sheet or a board: neither selects a pin or a pad, so
1222            // there is nothing of this part's to adopt.
1223            Some(_) => return,
1224        };
1225        let Some(label) = label else {
1226            // Nothing selected over there clears what was adopted FROM there,
1227            // so re-picking the same pin is a new pick.
1228            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        // The 3D surface's selection IS the address — the join the two eCAD
1238        // surfaces need is already made there.
1239        if surface == MODEL_SURFACE {
1240            self.selected = Some(label);
1241            return;
1242        }
1243        // A pin's group is its UNIT's group: a pad matches its pin by number
1244        // symbol-wide, so both surfaces route through the same join.
1245        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
1259/// Whether the LAST RUN resolved `address` — whether, in other words, there is
1260/// anything in the scene under that name to select. A part's own points are
1261/// resolved at the tail of the run, so a point just typed in has none until the
1262/// next one finishes.
1263fn 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
1269/// What `target`'s editor currently has selected, by NUMBER — the one reading
1270/// of it, so a pick and the adopt that follows it cannot disagree about what
1271/// the editor holds. `None` for a surface that selects no pin or pad.
1272fn 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
1280/// The key an adopted editor selection is remembered under. A `&'static str`
1281/// rather than the `Target` itself, because what is remembered is "the last
1282/// thing I saw selected over there" and the two eCAD editors are the only
1283/// surfaces that have one.
1284fn surface_of(target: Target) -> &'static str {
1285    match target {
1286        Target::Symbol => "symbol",
1287        Target::Pads => "pads",
1288        Target::Pcb => "pcb",
1289    }
1290}
1291
1292// ---------------------------------------------------------------------------
1293// Raw-block helpers: every edit touches ONE key, so a field this panel does not
1294// know about survives an edit to the field beside it.
1295// ---------------------------------------------------------------------------
1296
1297fn 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
1330/// Write one component of `transform.position` / `transform.rotationEuler`,
1331/// filling in the array (and the transform) when the point has none.
1332fn 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
1366/// A typed field's value: a NUMBER when it parses as one, else the string,
1367/// which the transform lane reads as an expression. An empty field is `0`
1368/// rather than an empty expression, because a blank component is not a
1369/// placement.
1370fn 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
1381/// One component of a point's transform as the field shows it: a number
1382/// formatted plainly, an expression verbatim, and `0` for a point with no
1383/// transform at all.
1384fn 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        // COMPACT, not `to_string`: the block carries a component the panel
1387        // wrote as a JSON float, so an untouched zero read back as `0.0` and a
1388        // whole millimetre as `2.0`. Six places is past anything a placement
1389        // field is typed to and short of f64 noise.
1390        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
1399/// One of the point's optional scalar fields as its field shows it — empty
1400/// where the point does not carry it.
1401fn 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
1413/// One status lamp: catalogued artwork where the glyph has some, a coloured
1414/// character where it does not.
1415fn 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
1422/// A vector as the seat readout prints it: three numbers, short.
1423fn triple(values: [f64; 3]) -> String {
1424    values
1425        .iter()
1426        .map(|value| {
1427            let rounded = (value * 1000.0).round() / 1000.0;
1428            // `-0` is the same place as `0` and reads as a mistake.
1429            if rounded == 0.0 { "0".to_string() } else { format!("{rounded}") }
1430        })
1431        .collect::<Vec<_>>()
1432        .join(", ")
1433}
1434
1435/// The footprint's pad numbers. A pad matches a pin by number symbol-wide, and
1436/// a pin carries its point's name, so a pad is this point's when its number is
1437/// the point's name — which is exactly the join `part_pins` makes.
1438fn 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
1453/// `J1`, `J2`, … — the first that no group in the block has taken.
1454fn 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
1462/// `1`, `2`, … — the first that no point in the group has taken. A number, not
1463/// a word, because a pin's label is what this becomes and pins are numbered.
1464fn 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