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, MountPick, 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/// What the mount section asked for.
119#[derive(Clone, Debug, PartialEq)]
120enum MountEdit {
121    /// A whole pose, `[translate, rotateEulerDeg]`, from one field's change;
122    /// the field names the undo step a drag coalesces into.
123    Pose([f64; 3], [f64; 3], String),
124    /// +90° about x composed onto the current mount.
125    YUpToZUp,
126    Reset,
127    /// Enter the picker for a helper: origin to a picked point, or seat on a
128    /// picked face. The pick itself is written when the picker finishes.
129    Pick(MountPick),
130    /// Align to footprint: refit the mount from the seated pins onto their
131    /// pads (`brep_kernel::mount_aligned_to_footprint`), with the leftover.
132    Align,
133}
134
135/// What the last Align to footprint did, for the line under its button and
136/// the verifier global. It is shown while the mount is still the one it wrote.
137#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
138struct AlignOutcome {
139    /// The mount block as Align left it.
140    written: Option<Value>,
141    /// The largest and the RMS pin-to-pad distance (mm) and the pin with the
142    /// largest, when the fit ran.
143    largest: Option<f64>,
144    rms: Option<f64>,
145    worst: Option<String>,
146    pins: usize,
147    notes: Vec<String>,
148    /// Why Align refused, when it did. Nothing was written then.
149    error: Option<String>,
150}
151
152/// Write a mount edit as one undoable step. An identity result removes the
153/// block (`brep_kernel::mount_block_of`), so a part brought back to identity
154/// re-serializes as it was before it had a mount.
155fn apply_mount(engine: &mut EngineState, edit: MountEdit) {
156    if let MountEdit::Pick(pick) = edit {
157        engine.begin_ref_select_for_mount(pick);
158        return;
159    }
160    let current = engine
161        .history
162        .mount_block()
163        .and_then(|block| brep_kernel::mount_from_block(block).ok());
164    let (mount, coalesce) = match edit {
165        MountEdit::Reset | MountEdit::Pick(_) | MountEdit::Align => (None, None),
166        MountEdit::Pose(translate, rotate, field) => {
167            let pose = serde_json::json!({ "translate": translate, "rotateEulerDeg": rotate });
168            (brep_kernel::mount_from_block(&pose).ok(), Some(format!("field:{field}")))
169        }
170        MountEdit::YUpToZUp => {
171            let turn = brep_kernel::mount_from_block(&serde_json::json!({ "rotateEulerDeg": [90.0, 0.0, 0.0] }));
172            let composed = turn.and_then(|turn| match current {
173                Some(current) => turn.compose(&current),
174                None => Ok(turn),
175            });
176            (composed.ok(), None)
177        }
178    };
179    let block = mount.as_ref().and_then(brep_kernel::mount_block_of);
180    if block.as_ref() == engine.history.mount_block() {
181        return;
182    }
183    engine.history.set_mount_block(block, coalesce.as_deref());
184}
185
186/// Where a jump goes.
187#[derive(Clone, Copy, PartialEq, Eq)]
188enum Jump {
189    Symbol,
190    Pads,
191    Model,
192}
193
194/// The panel's transient UI state. Everything it draws comes from the engine.
195pub struct QualifyPanel {
196    hits: HashMap<String, egui::Rect>,
197    /// The selected connection point, by part-local ADDRESS (`J1.VCC`). Held
198    /// by address rather than by index so an edit that reorders the block does
199    /// not move the selection to another point.
200    selected: Option<String>,
201    /// The editor selection last adopted, so an eCAD pick is adopted ONCE: a
202    /// user who picks a point here and then a different pin there gets the pin,
203    /// and one who picks here and leaves the editor alone keeps their pick.
204    /// The 3D surface goes through the same field under [`MODEL_SURFACE`].
205    adopted: Option<(&'static str, String)>,
206    /// The selection this panel last acted on for the GIZMO. The gizmo is
207    /// shared — the History panel arms it on a feature — so this panel acts on
208    /// a CHANGE of selection and not every frame: otherwise it would take the
209    /// handles back off a feature dialog on the frame after it armed them, and
210    /// it would re-ask (and re-notice) a refusal once a frame.
211    gizmo_armed_for: Option<String>,
212    /// The pin seat check of the open part (`pin_seats`), with the run and
213    /// history revision it was read at: it cuts meshes, so not once a frame.
214    pin_seats: Vec<super::pin_seats::PinSeat>,
215    pin_seats_at: Option<(u64, u64)>,
216    /// The part's `mount` block as of the same run, for the verifier global.
217    mount: Option<Value>,
218    /// The last Align to footprint.
219    align: Option<AlignOutcome>,
220}
221
222impl Default for QualifyPanel {
223    fn default() -> Self {
224        Self::new()
225    }
226}
227
228impl QualifyPanel {
229    pub fn new() -> Self {
230        Self { hits: HashMap::new(), selected: None, adopted: None, gizmo_armed_for: None, pin_seats: Vec::new(), pin_seats_at: None, mount: None, align: None }
231    }
232
233    pub fn hits_json(&self) -> String {
234        crate::automation::hit_rects::hits_json(&self.hits)
235    }
236
237    /// Drop the published rects: the dock calls this for a pane it did not
238    /// draw this frame (`DockState::ui`), whose widgets are not on screen.
239    pub fn clear_hits(&mut self) {
240        self.hits.clear();
241    }
242
243    /// The panel's verifier global: the selected address and the surface it is
244    /// drawn on, beside the block and report the engine publishes.
245    pub fn state_json(&self) -> String {
246        serde_json::json!({
247            "selected": self.selected,
248            "gizmoArmedFor": self.gizmo_armed_for,
249            "pinSeats": self.pin_seats,
250            "mount": self.mount,
251            "align": self.align,
252        })
253        .to_string()
254    }
255
256    /// Draw the panel. `target` is the eCAD editor on screen, or `None` where
257    /// the central tile draws the 3D model.
258    pub fn show(
259        &mut self,
260        ui: &mut egui::Ui,
261        engine: &mut EngineState,
262        ecad: &mut Editors,
263        target: Option<Target>,
264    ) {
265        self.hits.clear();
266        self.hits.insert("qualify:panel:clip".into(), ui.clip_rect());
267
268        let groups: Vec<PortDeclaration> = engine
269            .history
270            .ports_block()
271            .cloned()
272            .and_then(|block| serde_json::from_value(block).ok())
273            .unwrap_or_default();
274
275        let at = (engine.applied_generation(), engine.history.revision());
276        if self.pin_seats_at != Some(at) {
277            self.pin_seats = super::pin_seats::pin_seats(engine);
278            self.mount = engine.history.mount_block().cloned();
279            self.pin_seats_at = Some(at);
280        }
281
282        // An eCAD pick is a pick of the same thing: adopt it, once.
283        self.adopt_editor_selection(engine, ecad, target);
284        // A selection whose point is gone (removed, or renamed out from under
285        // it) is dropped rather than kept as a stale address.
286        if let Some(address) = &self.selected {
287            if !groups.iter().any(|group| {
288                group.points.iter().any(|point| &brep_kernel::port_address(&group.name, &point.name) == address)
289            }) {
290                self.selected = None;
291            }
292        }
293
294        let mut edit: Option<(Edit, Option<String>)> = None;
295        let mut jump: Option<Jump> = None;
296        let mut pick: Option<Option<String>> = None;
297        // `(address, field, enter the picker)` — clearing a reference is the
298        // same act said with `false`, so both go through one commit.
299        let mut refs: Option<(String, PortRefField, bool)> = None;
300
301        // --- header -----------------------------------------------------------
302        let points: usize = groups.iter().map(|group| group.points.len()).sum();
303        ui.horizontal(|ui| {
304            let add = ui
305                .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add group")).small())
306                .on_hover_text("Declare another port group on this part — a second connector, or a port with a different purpose");
307            self.hits.insert("qualify:add_group".into(), add.rect);
308            if add.clicked() {
309                edit = Some((Edit::AddGroup, None));
310            }
311            ui.label(
312                egui::RichText::new(format!(
313                    "{} group{} | {points} point{}",
314                    groups.len(),
315                    if groups.len() == 1 { "" } else { "s" },
316                    if points == 1 { "" } else { "s" },
317                ))
318                .weak(),
319            );
320        });
321        if self.selected.is_none() {
322            // A pane whose whole lower half is blank until something is
323            // selected should say what to select and what it will get.
324            let hint = ui.label(
325                egui::RichText::new(
326                    "Select a point to place it, seat it on geometry and cross to its pin and pad",
327                )
328                .weak()
329                .small(),
330            );
331            self.hits.insert("qualify:hint".into(), hint.rect);
332        }
333        ui.add_space(2.0);
334
335        // --- the groups -------------------------------------------------------
336        for (gi, group) in groups.iter().enumerate() {
337            egui::Frame::group(ui.style())
338                .inner_margin(egui::Margin::same(4))
339                .show(ui, |ui| {
340                    // The frame must not lay out wider than what is on screen,
341                    // or its right-aligned ✕ is published past the pane's edge
342                    // and a click aims into the viewport (the same clamp the
343                    // spline-anchor rows carry, for the same reason).
344                    let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
345                    ui.set_width(ui.available_width().min(room));
346                    if let Some(asked) = self.group_header(ui, gi, group) {
347                        edit = Some(asked);
348                    }
349                    for (pi, point) in group.points.iter().enumerate() {
350                        let address = brep_kernel::port_address(&group.name, &point.name);
351                        let selected = self.selected.as_deref() == Some(address.as_str());
352                        if let Some(asked) = self
353                            .point_row(ui, engine, gi, pi, point, &address, selected, &mut pick)
354                        {
355                            edit = Some(asked);
356                        }
357                        if let Some(seat) = self.pin_seats.iter().find(|seat| seat.address == address).cloned() {
358                            self.pin_seat_line(ui, &seat);
359                        }
360                        if selected {
361                            if let Some(asked) = self
362                                .point_fields(ui, engine, gi, pi, point, &address, target, &mut refs)
363                            {
364                                edit = Some(asked);
365                            }
366                            if let Some(asked) = self.jump_row(ui, &address, target) {
367                                jump = Some(asked);
368                            }
369                        }
370                    }
371                    let add = ui
372                        .add(crate::icon_text::icon_button(ui, &format!("{GLYPH_ADD} Add point")).small())
373                        .on_hover_text("Add a connection point to this group. It arrives at the part origin, facing +X; place it below.");
374                    self.hits.insert(format!("qualify:group:{gi}:add_point"), add.rect);
375                    if add.clicked() {
376                        edit = Some((Edit::AddPoint(gi), None));
377                    }
378                });
379        }
380
381        // --- the mount frame --------------------------------------------------
382        let mount_edit = self.mount_section(ui, engine, target.is_none());
383
384        // --- the reports ------------------------------------------------------
385        ui.add_space(4.0);
386        self.reports(ui, engine);
387
388        // --- act on what the draw asked for (at most one of each) --------------
389        if let Some(pick) = pick {
390            self.pick(engine, ecad, target, pick);
391        }
392        if let Some((address, field, enter)) = refs {
393            match enter {
394                true => engine.begin_ref_select_for_port_point(&address, field),
395                false => engine.clear_port_point_ref(&address, field),
396            }
397        }
398        if let Some((edit, coalesce)) = edit {
399            self.apply(engine, edit, coalesce.as_deref());
400        }
401        if let Some(jump) = jump {
402            self.jump(engine, ecad, jump);
403        }
404        match mount_edit {
405            Some(MountEdit::Align) => self.align_mount(engine),
406            Some(mount_edit) => apply_mount(engine, mount_edit),
407            None => {}
408        }
409        // Last, so it follows whatever the frame just did to the selection.
410        self.follow_gizmo(engine, target);
411    }
412
413    /// Put the move/rotate handles on the selected point, or take them off.
414    ///
415    /// Selecting a row IS arming the gizmo, which is the convention the spline
416    /// anchors panel already set: one affordance, not a select and then a
417    /// separate arm. Only on the 3D surface, because an eCAD editor has no
418    /// viewport to drag handles in, and never while the reference picker is
419    /// up, because that picker owns the clicks.
420    fn follow_gizmo(&mut self, engine: &mut EngineState, target: Option<Target>) {
421        let wanted = match target.is_none() && !engine.ref_select_active() {
422            true => self.selected.clone(),
423            false => None,
424        };
425        // The gizmo is ONE shared widget, so this is deliberately not "arm what
426        // is selected, every frame". It is SETTLED — and left alone — when the
427        // selection has not changed AND one of three things is true:
428        //
429        // * nothing is wanted (and the disarm below has already run);
430        // * SOMETHING is armed. Whose it is does not matter: if a feature
431        //   dialog has taken the handles, re-arming would take them straight
432        //   back on the next frame, and this pane is drawn beside every
433        //   feature dialog in the product;
434        // * the point REFUSES the handles, which would otherwise re-ask —
435        //   and re-push its notice — sixty times a second.
436        //
437        // What that leaves is the case the plain change check got wrong: the
438        // reference picker takes the handles off at its entry, and the pane is
439        // not drawn while it is up, so on the frame it closes the selection has
440        // NOT changed and nothing is armed. That is exactly when they go back.
441        let refusal = wanted
442            .as_deref()
443            .and_then(|address| engine.port_point_gizmo_refusal(address));
444        let settled = wanted == self.gizmo_armed_for
445            && (wanted.is_none() || engine.transform_armed() || refusal.is_some());
446        if settled {
447            return;
448        }
449        self.gizmo_armed_for = wanted.clone();
450        match wanted {
451            // A refusal is asked ONCE — the arm pushes the notice — and the
452            // reason the gizmo line shows is read from the engine, not from
453            // anything kept here.
454            Some(address) => {
455                engine.arm_transform_for_port_point(&address);
456            }
457            // Take away only what THIS panel put there. A feature's gizmo,
458            // armed from the History panel, is not ours — and neither is one
459            // on another connection point that something else armed.
460            None => {
461                if engine.transform_armed_port_point().is_some() {
462                    engine.disarm_transform();
463                }
464            }
465        }
466    }
467
468    /// Take a pick made in the panel: select `address` (or nothing) and LIGHT
469    /// IT UP on the surface the user is on.
470    ///
471    /// Lighting it up is not decoration — it is the other half of the same
472    /// sentence the jump buttons speak, and without it a pick here means
473    /// nothing until the user leaves. It also has to drive the editor through
474    /// the SAME deferred path a jump uses: the editor's own selection is what
475    /// [`Self::adopt_editor_selection`] reads back, so a panel pick that left
476    /// the editor sitting on another pin would be overwritten by that pin on
477    /// the very next frame.
478    fn pick(
479        &mut self,
480        engine: &mut EngineState,
481        ecad: &mut Editors,
482        target: Option<Target>,
483        address: Option<String>,
484    ) {
485        self.selected = address.clone();
486        match target {
487            Some(target) => {
488                // Agreeing with the editor NOW as well as after its next draw:
489                // `apply_focus` is what survives a pull, and this is what makes
490                // the pin light up on the frame of the click.
491                if let Some((_, name)) =
492                    address.as_deref().and_then(brep_kernel::split_address)
493                {
494                    ecad.focus(target, name.to_string());
495                    ecad.apply_focus(target);
496                }
497                // What is remembered is what the editor ACTUALLY holds now, not
498                // what was asked of it. They differ for a point with no pin —
499                // the focus finds nothing and the editor stays where it was —
500                // and remembering the ask would make the next frame read that
501                // stale pin as a NEW editor pick and overwrite the user's.
502                self.adopted = editor_selection(ecad, target)
503                    .map(|held| (surface_of(target), held));
504            }
505            // The 3D surface: the point's own scene entities are published
506            // under its address, so this is the selection a click in the
507            // viewport makes — the Scene tree's row click, by name.
508            None => {
509                if let Some(address) = address.as_deref() {
510                    if resolved(engine, address) {
511                        engine.select_by_name("solid", address);
512                    }
513                }
514                // The same rule, on this surface: what is remembered is what
515                // the VIEWPORT holds afterwards. Deselecting here leaves the
516                // geometry lit, and remembering the ask instead would make the
517                // next frame read that as a fresh viewport pick and undo the
518                // deselection.
519                self.adopted = engine
520                    .selected_port_point()
521                    .map(|held| (MODEL_SURFACE, held));
522            }
523        }
524    }
525
526    /// One group's header row: name, purpose, symbol unit, remove.
527    fn group_header(
528        &mut self,
529        ui: &mut egui::Ui,
530        gi: usize,
531        group: &PortDeclaration,
532    ) -> Option<(Edit, Option<String>)> {
533        let mut asked = None;
534        ui.horizontal(|ui| {
535            let mut name = group.name.clone();
536            let field = ui
537                .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
538                .on_hover_text("The group's name — the first half of every address in it (`J1` in `J1.VCC`). `:`, `.` and `/` are refused.");
539            self.hits.insert(format!("qualify:group:{gi}:name"), field.rect);
540            if field.changed() {
541                asked = Some((Edit::GroupName(gi, name), Some(format!("group:{gi}:name"))));
542            }
543
544            let mut purpose = group.purpose.clone();
545            let combo = egui::ComboBox::from_id_salt(("qualify-purpose", gi))
546                .selected_text(if purpose.is_empty() { "purpose" } else { purpose.as_str() })
547                .width(76.0)
548                .show_ui(ui, |ui| {
549                    // The document's own value is offered beside the three when
550                    // it is none of them: the kernel carries `purpose` as a
551                    // string and never enumerates it, so a purpose a later
552                    // slice invents must not vanish because this list has not
553                    // heard of it.
554                    let mut offered: Vec<String> =
555                        PURPOSES.iter().map(|p| (*p).to_string()).collect();
556                    if !group.purpose.is_empty() && !PURPOSES.contains(&group.purpose.as_str()) {
557                        offered.push(group.purpose.clone());
558                    }
559                    for candidate in offered {
560                        let item = ui.selectable_label(purpose == candidate, &candidate);
561                        self.hits
562                            .insert(format!("qualify:group:{gi}:purpose:{candidate}"), item.rect);
563                        if item.clicked() {
564                            purpose = candidate;
565                        }
566                    }
567                });
568            self.hits.insert(format!("qualify:group:{gi}:purpose"), combo.response.rect);
569            if purpose != group.purpose {
570                asked = Some((Edit::GroupPurpose(gi, purpose), None));
571            }
572
573            ui.label(egui::RichText::new("unit").weak());
574            let mut unit = group.symbol_unit.map(|unit| unit.to_string()).unwrap_or_default();
575            let field = ui
576                .add(egui::TextEdit::singleline(&mut unit).desired_width(24.0))
577                .on_hover_text("The SYMBOL UNIT whose pins bind into this group, 1-based. Empty binds no pins — which is right for a piping port — unless this is the part's only group, when it takes unit 1.");
578            self.hits.insert(format!("qualify:group:{gi}:unit"), field.rect);
579            if field.changed() {
580                let parsed = unit.trim().parse::<u32>().ok();
581                // A field being cleared reads as "no unit"; a field holding
582                // something that is not a number keeps what was there, so a
583                // half-typed value never silently unbinds a group.
584                if parsed.is_some() || unit.trim().is_empty() {
585                    asked = Some((Edit::GroupUnit(gi, parsed), Some(format!("group:{gi}:unit"))));
586                }
587            }
588
589            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
590                let remove = ui
591                    .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
592                    .on_hover_text("Remove this group and every point in it — and the pins bound to them");
593                self.hits.insert(format!("qualify:group:{gi}:remove"), remove.rect);
594                if remove.clicked() {
595                    asked = Some((Edit::RemoveGroup(gi), None));
596                }
597            });
598        });
599        asked
600    }
601
602    /// One point's row: select, name, remove. A click on ◎ is reported as a
603    /// PICK rather than applied here, because a pick is not only a selection:
604    /// it lights the point on whatever surface is on screen, which needs the
605    /// editors and the engine.
606    #[allow(clippy::too_many_arguments)]
607    fn point_row(
608        &mut self,
609        ui: &mut egui::Ui,
610        engine: &EngineState,
611        gi: usize,
612        pi: usize,
613        point: &brep_kernel::PortPoint,
614        address: &str,
615        selected: bool,
616        pick: &mut Option<Option<String>>,
617    ) -> Option<(Edit, Option<String>)> {
618        let mut asked = None;
619        ui.horizontal(|ui| {
620            let label = crate::icon_text::selectable_icon_label(ui, selected, GLYPH_SELECT)
621                .on_hover_text(format!("Select {address} — it lights up on the surface you are on, its fields open below, and the jump buttons carry it to the others"));
622            self.hits.insert(format!("qualify:point:{gi}:{pi}:select"), label.rect);
623            if label.clicked() {
624                *pick = Some((!selected).then(|| address.to_string()));
625            }
626            let mut name = point.name.clone();
627            let field = ui
628                .add(egui::TextEdit::singleline(&mut name).desired_width(70.0))
629                .on_hover_text("The point's name, which is its identity: the symbol pin of this name in this group's unit binds to it, and the pad of that number follows.");
630            self.hits.insert(format!("qualify:point:{gi}:{pi}:name"), field.rect);
631            if field.changed() {
632                asked = Some((Edit::PointName(gi, pi, name), Some(format!("point:{gi}:{pi}:name"))));
633            }
634            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
635                let remove = ui
636                    .add(crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small())
637                    .on_hover_text("Remove this connection point — and the pin bound to it");
638                self.hits.insert(format!("qualify:point:{gi}:{pi}:remove"), remove.rect);
639                if remove.clicked() {
640                    asked = Some((Edit::RemovePoint(gi, pi), None));
641                }
642                ui.add_space(4.0);
643                self.presence(ui, engine, gi, pi, address, &point.name);
644            });
645        });
646        asked
647    }
648
649    /// The selected point's fields, indented under its row, in four sections:
650    /// where it is SEATED, the PLACEMENT read in that seat, what a WIRE leaving
651    /// it does, and — for an assembly — the descendant it maps to.
652    ///
653    /// The sections are the point's own sentence in order: seat it, nudge it,
654    /// say how the wire leaves, and (an assembly only) say whose point it
655    /// really is. Before this they were one flat list of eight fields in which
656    /// `pointRef` and `extension` looked like the same kind of thing.
657    fn point_fields(
658        &mut self,
659        ui: &mut egui::Ui,
660        engine: &EngineState,
661        gi: usize,
662        pi: usize,
663        point: &brep_kernel::PortPoint,
664        address: &str,
665        target: Option<Target>,
666        refs: &mut Option<(String, PortRefField, bool)>,
667    ) -> Option<(Edit, Option<String>)> {
668        let mut asked = None;
669        // A MAPPED point has no placement of its own: the kernel's
670        // `resolve_point` returns on `mapsTo` before it reads the transform or
671        // either reference. Offering a seat and an offset it will ignore is
672        // three sections of lie, so a mapped point shows only the one field
673        // that decides where it is.
674        let mapped = point
675            .maps_to
676            .as_deref()
677            .map(str::trim)
678            .is_some_and(|target| !target.is_empty());
679        ui.indent(("qualify-point", gi, pi), |ui| {
680            if mapped {
681                if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
682                    asked = Some(mapped_asked);
683                }
684                self.seat_line(ui, engine, address, point);
685                return;
686            }
687            // --- seat ---------------------------------------------------------
688            // Every purpose offers it. On a `pcb` group the seat is checked
689            // against the pin's pad (`pin_seats`, the line under the point).
690            let seat_fields: &[(PortRefField, &str, &str)] = &[
691                (PortRefField::Point, "Point", "The geometry this point SITS on: a face, an edge, a circle's centre, a vertex, a datum frame. Pick it in the 3D view with \u{2316}. Empty places the point by the offset below alone."),
692                (PortRefField::Direction, "Direction", "The geometry it FACES along: a face's normal, a bore's axis, an edge, a datum frame. Empty takes the direction the point reference implies, or +X. Seat the POINT first where you can: a direction on its own still re-reads the offset in its own axes, so a placement you typed is zeroed rather than turned."),
693                (PortRefField::Body, "Body", "The SOLID that is this point's contact, when a pin is a whole body (an XLR pin, a jack sleeve, a crimp). It seats what Point and Direction leave empty: the point at the body's wire end, facing out along its axis. Pick it in the 3D view with \u{2316}."),
694            ];
695            self.section(ui, "Seated on");
696            for &(field, caption, hover) in seat_fields {
697                ui.horizontal(|ui| {
698                    ui.label(egui::RichText::new(caption).weak());
699                    let key = field.key();
700                    let mut text = optional_text(point, key);
701                    let field_ui = ui
702                        .add(egui::TextEdit::singleline(&mut text).desired_width(120.0))
703                        .on_hover_text(hover);
704                    self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field_ui.rect);
705                    if field_ui.changed() {
706                        asked = Some((
707                            Edit::PointText(gi, pi, key, text),
708                            Some(format!("point:{gi}:{pi}:{key}")),
709                        ));
710                    }
711                    // Picking is offered only where there is a model to pick
712                    // IN. From an eCAD editor the button would open a picker
713                    // over a schematic, which has no faces.
714                    let pickable = target.is_none();
715                    let pick = ui
716                        .add_enabled(
717                            pickable,
718                            crate::icon_text::icon_button(ui, GLYPH_PICK).small(),
719                        )
720                        .on_hover_text("Pick it in the 3D view")
721                        .on_disabled_hover_text("Go to the 3D model to pick geometry");
722                    self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:pick"), pick.rect);
723                    if pick.clicked() {
724                        *refs = Some((address.to_string(), field, true));
725                    }
726                    let has = !optional_text(point, key).trim().is_empty();
727                    let clear = ui
728                        .add_enabled(
729                            has,
730                            crate::icon_text::icon_button_colored(ui, GLYPH_REMOVE, Some(REMOVE_RED)).small(),
731                        )
732                        .on_hover_text("Unseat it — the offset below stays as it is, read from the part origin");
733                    self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}:clear"), clear.rect);
734                    if clear.clicked() {
735                        *refs = Some((address.to_string(), field, false));
736                    }
737                });
738            }
739            self.seat_line(ui, engine, address, point);
740            if let Some(flip) = self.contact_line(ui, engine, gi, pi, address, point) {
741                asked = Some(flip);
742            }
743
744            // --- placement ----------------------------------------------------
745            self.section(ui, "Placement");
746            let seated = point.point_ref.is_some()
747                || point.direction_ref.is_some()
748                || point.contact_body.is_some();
749            for (key, caption, hover) in [
750                ("position", "Offset", if seated {
751                    "Where the point sits RELATIVE TO ITS SEAT, in millimetres: x runs along the direction the reference gives, y and z across it. A component that is not a number is kept as an EXPRESSION."
752                } else {
753                    "Where the point sits, in millimetres from the part origin. Seat it on geometry above and these become an offset from that. A component that is not a number is kept as an EXPRESSION."
754                }),
755                ("rotationEuler", "Angle", if seated {
756                    "The rotation applied to the seat's own axes to get the direction a wire leaves along, in degrees. All zero means \"straight out along the reference\"."
757                } else {
758                    "The rotation applied to +X to get the direction a wire leaves along, in degrees."
759                }),
760            ] {
761                ui.horizontal(|ui| {
762                    ui.label(egui::RichText::new(caption).weak());
763                    for axis in 0..3 {
764                        let mut text = transform_component(point, key, axis);
765                        let field = ui
766                            .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
767                            .on_hover_text(hover);
768                        self.hits
769                            .insert(format!("qualify:point:{gi}:{pi}:{key}{axis}"), field.rect);
770                        if field.changed() {
771                            asked = Some((
772                                Edit::PointTransform(gi, pi, key, axis, text),
773                                Some(format!("point:{gi}:{pi}:{key}{axis}")),
774                            ));
775                        }
776                    }
777                });
778            }
779            self.gizmo_line(ui, engine, address, target);
780
781            // --- the wire -----------------------------------------------------
782            self.section(ui, "Wire");
783            ui.horizontal(|ui| {
784                for (key, caption, hover) in [
785                    ("extension", "Extension", "The straight run a wire keeps before it may bend. Empty takes the default."),
786                    ("displayLength", "Drawn", "How long the point's line is drawn. Empty takes the default."),
787                ] {
788                    ui.label(egui::RichText::new(caption).weak());
789                    let mut text = optional_text(point, key);
790                    let field = ui
791                        .add(egui::TextEdit::singleline(&mut text).desired_width(46.0))
792                        .on_hover_text(hover);
793                    self.hits.insert(format!("qualify:point:{gi}:{pi}:{key}"), field.rect);
794                    if field.changed() {
795                        asked = Some((
796                            Edit::PointText(gi, pi, key, text),
797                            Some(format!("point:{gi}:{pi}:{key}")),
798                        ));
799                    }
800                }
801            });
802            let mut reverse = point.reverse_direction;
803            let toggle = ui
804                .checkbox(&mut reverse, "Leaves the other way")
805                .on_hover_text("Flip the direction a wire leaves along, without disturbing the seat");
806            self.hits.insert(format!("qualify:point:{gi}:{pi}:reverse"), toggle.rect);
807            if toggle.changed() {
808                asked = Some((Edit::PointReverse(gi, pi, reverse), None));
809            }
810
811            // --- the assembly declaration -------------------------------------
812            // Shown only where it can mean something: `mapsTo` says "this point
813            // IS a descendant's point", so on a part with no components it is a
814            // field that can only ever be wrong.
815            if !engine.assembly_components().is_empty() {
816                if let Some(mapped_asked) = self.maps_to_field(ui, gi, pi, point) {
817                    asked = Some(mapped_asked);
818                }
819            }
820        });
821        asked
822    }
823
824    /// The `mapsTo` field and its heading — the only field a MAPPED point has,
825    /// and the last section of an unmapped one in a document with components.
826    fn maps_to_field(
827        &mut self,
828        ui: &mut egui::Ui,
829        gi: usize,
830        pi: usize,
831        point: &brep_kernel::PortPoint,
832    ) -> Option<(Edit, Option<String>)> {
833        let mut asked = None;
834        self.section(ui, "Assembly");
835        ui.horizontal(|ui| {
836            ui.label(egui::RichText::new("Maps to").weak());
837            let mut text = optional_text(point, "mapsTo");
838            let field = ui
839                .add(egui::TextEdit::singleline(&mut text).desired_width(130.0))
840                .on_hover_text("The descendant point this one IS, by address (`ACOMP2:J5.VCC`). It takes the target's resolved placement, so the interface follows the child — and this point has no seat, no offset and no handles of its own. Clear it to place this point here instead.");
841            self.hits.insert(format!("qualify:point:{gi}:{pi}:mapsTo"), field.rect);
842            if field.changed() {
843                asked = Some((
844                    Edit::PointText(gi, pi, "mapsTo", text),
845                    Some(format!("point:{gi}:{pi}:mapsTo")),
846                ));
847            }
848        });
849        asked
850    }
851
852    /// A section heading inside the selected point's fields.
853    /// The part's MOUNT FRAME on the board (`brep_kernel::part_mount`): how
854    /// the whole part, every solid with its seats, is moved into its
855    /// footprint's frame wherever it is placed. Its own features are not
856    /// touched, so this editor still shows the model as built. Offered on a
857    /// part with pads, where there is a footprint to sit on.
858    fn mount_section(&mut self, ui: &mut egui::Ui, engine: &EngineState, pickable: bool) -> Option<MountEdit> {
859        if engine.history.pads_block().is_none() {
860            return None;
861        }
862        let mut asked = None;
863        ui.add_space(4.0);
864        egui::Frame::group(ui.style()).inner_margin(egui::Margin::same(4)).show(ui, |ui| {
865            let room = (ui.clip_rect().right() - ui.max_rect().left()).max(0.0);
866            ui.set_width(ui.available_width().min(room));
867            self.section(ui, "Mount on board");
868            let block = engine.history.mount_block();
869            let pose = match block.map(brep_kernel::mount_from_block).transpose() {
870                Ok(mount) => mount.map(|mount| brep_kernel::transform_to_pose_params(&mount)),
871                Err(error) => {
872                    let line = ui.label(
873                        egui::RichText::new(format!("The mount block does not read as a pose ({error}), so no pin is checked. Reset it.")).color(WARN_COLOR).small(),
874                    );
875                    self.hits.insert("qualify:mount:status".into(), line.rect);
876                    None
877                }
878            };
879            let triple = |key: &str| -> [f64; 3] {
880                let values = pose.as_ref().and_then(|pose| pose[key].as_array().cloned()).unwrap_or_default();
881                [0, 1, 2].map(|k| values.get(k).and_then(Value::as_f64).unwrap_or(0.0))
882            };
883            let status = if block.is_none() {
884                "The model is in its footprint's frame: top copper at z = 0, the footprint origin at 0, 0."
885            } else {
886                "Every solid of the part, with its seats, is moved by this onto its footprint wherever the part is placed. The features are not changed."
887            };
888            if block.is_none() || pose.is_some() {
889                let line = ui.label(egui::RichText::new(status).weak().small());
890                self.hits.insert("qualify:mount:status".into(), line.rect);
891            }
892            for (key, caption, speed, hover) in [
893                ("translate", "Move", 0.05, "Where the model's origin goes on the footprint, in millimetres (y up, top copper at z = 0)."),
894                ("rotateEulerDeg", "Turn", 1.0, "How the model is turned onto the footprint, in degrees about x, then y, then z."),
895            ] {
896                let values = triple(key);
897                ui.horizontal(|ui| {
898                    ui.label(egui::RichText::new(caption).weak());
899                    for (axis, value) in values.iter().enumerate() {
900                        let mut edited = *value;
901                        let field = ui.add(egui::DragValue::new(&mut edited).speed(speed).max_decimals(4)).on_hover_text(hover);
902                        self.hits.insert(format!("qualify:mount:{key}{axis}"), field.rect);
903                        if field.changed() && edited.is_finite() {
904                            let mut translate = triple("translate");
905                            let mut rotate = triple("rotateEulerDeg");
906                            match key {
907                                "translate" => translate[axis] = edited,
908                                _ => rotate[axis] = edited,
909                            }
910                            asked = Some(MountEdit::Pose(translate, rotate, format!("{key}{axis}")));
911                        }
912                    }
913                });
914            }
915            ui.horizontal(|ui| {
916                let up = ui
917                    .add(crate::icon_text::icon_button(ui, "Y up \u{2192} Z up").small())
918                    .on_hover_text("Turn the model +90° about x: for a model built with y up, where a board's up is z");
919                self.hits.insert("qualify:mount:y_up".into(), up.rect);
920                if up.clicked() {
921                    asked = Some(MountEdit::YUpToZUp);
922                }
923                let reset = ui
924                    .add_enabled(block.is_some(), crate::icon_text::icon_button(ui, "Reset").small())
925                    .on_hover_text("Clear the mount: the model is placed as it is built");
926                self.hits.insert("qualify:mount:reset".into(), reset.rect);
927                if reset.clicked() {
928                    asked = Some(MountEdit::Reset);
929                }
930            });
931            // The picks are offered only where there is a model to pick IN.
932            ui.horizontal(|ui| {
933                for (key, caption, hover, pick) in [
934                    ("seat", "Seat on face", "Pick the face the part sits on (lead undersides, a standoff, the body's underside): it is turned to face down and moved to the board's top, z = 0", MountPick::Seat),
935                    ("origin", "Origin to point", "Pick the point that goes on the footprint origin (a pin's centre, a corner): the part moves in the board's plane, and its height stays", MountPick::Origin),
936                ] {
937                    let button = ui
938                        .add_enabled(pickable, crate::icon_text::icon_button(ui, &format!("{GLYPH_PICK} {caption}")).small())
939                        .on_hover_text(hover)
940                        .on_disabled_hover_text("Go to the 3D model to pick geometry");
941                    self.hits.insert(format!("qualify:mount:{key}"), button.rect);
942                    if button.clicked() {
943                        asked = Some(MountEdit::Pick(pick));
944                    }
945                }
946            });
947            let align = ui
948                .add(crate::icon_text::icon_button(ui, "Align to footprint").small())
949                .on_hover_text("Fit the part onto its pads as one rigid move: the seating plane from the pins' wires (or the plane already set), then the pins matched to their pads by number. The leftover is shown below");
950            self.hits.insert("qualify:mount:align".into(), align.rect);
951            if align.clicked() {
952                asked = Some(MountEdit::Align);
953            }
954            if let Some(outcome) = self.align.clone().filter(|outcome| outcome.written.as_ref() == block) {
955                let mut lines = Vec::new();
956                match (&outcome.error, outcome.largest, outcome.rms) {
957                    (Some(error), _, _) => lines.push((format!("Align refused: {error}."), true)),
958                    (None, Some(largest), Some(rms)) => lines.push((
959                        format!(
960                            "Aligned {} pins: largest {largest:.3} mm (pin {}), RMS {rms:.3} mm.",
961                            outcome.pins,
962                            outcome.worst.as_deref().unwrap_or("?")
963                        ),
964                        false,
965                    )),
966                    _ => {}
967                }
968                lines.extend(outcome.notes.iter().map(|note| (format!("Note: {note}."), true)));
969                for (i, (text, warn)) in lines.into_iter().enumerate() {
970                    let text = egui::RichText::new(text).small();
971                    let line = ui.label(if warn { text.color(WARN_COLOR) } else { text.weak() });
972                    self.hits.insert(format!("qualify:mount:align_report:{i}"), line.rect);
973                }
974            }
975        });
976        asked
977    }
978
979    /// Align to footprint, written as one undo step; the outcome is kept for
980    /// the line under the button. A refusal writes nothing.
981    fn align_mount(&mut self, engine: &mut EngineState) {
982        let outcome = match super::pin_seats::align_to_footprint(engine) {
983            Ok(report) => {
984                let block = brep_kernel::mount_block_of(&report.mount);
985                if block.as_ref() != engine.history.mount_block() {
986                    engine.history.set_mount_block(block.clone(), None);
987                }
988                AlignOutcome {
989                    written: block,
990                    largest: Some(report.largest),
991                    rms: Some(report.rms),
992                    worst: Some(report.worst),
993                    pins: report.pins,
994                    notes: report.notes,
995                    error: None,
996                }
997            }
998            Err(error) => AlignOutcome { written: engine.history.mount_block().cloned(), error: Some(error), ..AlignOutcome::default() },
999        };
1000        self.align = Some(outcome);
1001    }
1002
1003    fn section(&mut self, ui: &mut egui::Ui, caption: &str) {
1004        ui.add_space(3.0);
1005        ui.label(egui::RichText::new(caption).small().strong());
1006    }
1007
1008    /// What the last run made of the point's seat, in words: where it sits and
1009    /// which way it faces. This is the answer to "did my pick take?", and
1010    /// without it a reference field is a string the user must trust.
1011    /// Whether the point's 3D seat lands on its pin's pad (`pin_seats`): the
1012    /// finding in amber, or a quiet line when it does.
1013    fn pin_seat_line(&mut self, ui: &mut egui::Ui, seat: &super::pin_seats::PinSeat) {
1014        let text = match &seat.message {
1015            Some(message) => egui::RichText::new(message).color(WARN_COLOR).small(),
1016            None => egui::RichText::new(format!("Pin {} is on pad {}", seat.pin, seat.pin)).color(OK_COLOR).small(),
1017        };
1018        let label = ui.label(text);
1019        self.hits.insert(format!("qualify:pinseat:{}", seat.address), label.rect);
1020    }
1021
1022    fn seat_line(
1023        &mut self,
1024        ui: &mut egui::Ui,
1025        engine: &EngineState,
1026        address: &str,
1027        point: &brep_kernel::PortPoint,
1028    ) {
1029        let seated = !optional_text(point, "pointRef").trim().is_empty()
1030            || !optional_text(point, "directionRef").trim().is_empty()
1031            || !optional_text(point, "contactBody").trim().is_empty();
1032        let text = match engine.port_point_row(address) {
1033            Some(row) if seated => format!(
1034                "seated at ({}), facing ({})",
1035                triple(row.seat.origin),
1036                triple(row.seat.x),
1037            ),
1038            Some(row) => format!("at ({}), facing ({})", triple(row.position), triple(row.direction)),
1039            // The tail resolves at the END of the run, so a point just added
1040            // has nothing yet — which is a state, not a fault.
1041            None => "not resolved by the last run".to_string(),
1042        };
1043        let label = ui.label(egui::RichText::new(text).weak().small());
1044        self.hits.insert("qualify:seat".into(), label.rect);
1045    }
1046
1047    /// Which end of its contact body the point took, with the one-click flip
1048    /// beside it: the default wire end is a geometric rule (the end farther
1049    /// from the rest of the part), and on a connector whose pins protrude
1050    /// forward it picks the mating end, so the choice is shown, not hidden.
1051    /// Drawn only when the last run derived the body's axis.
1052    fn contact_line(
1053        &mut self,
1054        ui: &mut egui::Ui,
1055        engine: &EngineState,
1056        gi: usize,
1057        pi: usize,
1058        address: &str,
1059        point: &brep_kernel::PortPoint,
1060    ) -> Option<(Edit, Option<String>)> {
1061        let contact = engine.port_point_row(address)?.contact.clone()?;
1062        let mut asked = None;
1063        ui.horizontal(|ui| {
1064            let text = if contact.seats_origin {
1065                format!(
1066                    "wire end: the {} end of {} at ({})",
1067                    contact.end,
1068                    contact.body,
1069                    triple(contact.wire_end)
1070                )
1071            } else {
1072                format!("axis of {} ({}); the point is seated above", contact.body, triple(contact.axis))
1073            };
1074            let label = ui.label(egui::RichText::new(text).weak().small());
1075            self.hits.insert("qualify:contact".into(), label.rect);
1076            if contact.seats_origin {
1077                let flip = ui
1078                    .small_button("Other end")
1079                    .on_hover_text("Attach the wire at the body's other end (Leaves the other way)");
1080                self.hits.insert(format!("qualify:point:{gi}:{pi}:contact:flip"), flip.rect);
1081                if flip.clicked() {
1082                    asked = Some((Edit::PointReverse(gi, pi, !point.reverse_direction), None));
1083                }
1084            }
1085        });
1086        asked
1087    }
1088
1089    /// Whether the handles are on this point, and why not when they are not.
1090    fn gizmo_line(
1091        &mut self,
1092        ui: &mut egui::Ui,
1093        engine: &EngineState,
1094        address: &str,
1095        target: Option<Target>,
1096    ) {
1097        // Asked of the ENGINE rather than inferred from the gizmo not being
1098        // armed: this line is drawn a moment before `follow_gizmo` runs, so on
1099        // the frame a point is selected an inference would show the refusal
1100        // reason for a point that is about to arm perfectly well.
1101        let text = match (target, engine.port_point_gizmo_refusal(address)) {
1102            (Some(_), _) => "the move/rotate handles arm on the 3D surface".to_string(),
1103            (None, Some(expression)) => format!(
1104                "no handles: '{expression}' places this point, and a drag writes numbers"
1105            ),
1106            (None, None) => {
1107                "the move/rotate handles are on it — a drag writes the offset above".to_string()
1108            }
1109        };
1110        let label = ui.label(egui::RichText::new(text).weak().small());
1111        self.hits.insert("qualify:gizmo".into(), label.rect);
1112    }
1113
1114    /// Three lamps per point: does a symbol PIN carry this name, does a PAD,
1115    /// and did the last run resolve it in 3D. A connection point is ONE thing
1116    /// on three surfaces, and this row is where that claim is either true in
1117    /// front of the user or visibly not.
1118    fn presence(
1119        &mut self,
1120        ui: &mut egui::Ui,
1121        engine: &EngineState,
1122        gi: usize,
1123        pi: usize,
1124        address: &str,
1125        name: &str,
1126    ) {
1127        let pinned = engine
1128            .history
1129            .pin_point_report()
1130            .map(|report| report.pairs.iter().any(|pair| pair.point == address));
1131        let padded = pad_numbers(engine).iter().any(|number| number == name);
1132        for (key, state, present, absent) in [
1133            (
1134                "symbol",
1135                pinned,
1136                "a symbol pin carries this name",
1137                "no symbol pin carries this name, so nothing on the schematic is this point",
1138            ),
1139            (
1140                "pads",
1141                Some(padded),
1142                "a pad carries this number",
1143                "no pad carries this number",
1144            ),
1145            (
1146                "model",
1147                Some(resolved(engine, address)),
1148                "the last run resolved it in 3D",
1149                "the last run did not resolve it, so there is no geometry to show",
1150            ),
1151        ] {
1152            let (glyph, color, hover) = match state {
1153                Some(true) => (GLYPH_PRESENT, OK_COLOR, present),
1154                Some(false) => (GLYPH_ABSENT, WARN_COLOR, absent),
1155                // No symbol at all: the question does not arise, and an amber
1156                // lamp on a 3D-only part would be a fault where there is none.
1157                None => (
1158                    GLYPH_ABSENT,
1159                    ui.visuals().weak_text_color(),
1160                    "this part has no symbol",
1161                ),
1162            };
1163            let lamp = lamp(ui, glyph, color).on_hover_text(format!("{key}: {hover}"));
1164            self.hits
1165                .insert(format!("qualify:point:{gi}:{pi}:lamp:{key}"), lamp.rect);
1166        }
1167    }
1168
1169    /// The three JUMP buttons for the selected point. The one for the surface
1170    /// already on screen is drawn pressed and does nothing.
1171    fn jump_row(&mut self, ui: &mut egui::Ui, address: &str, target: Option<Target>) -> Option<Jump> {
1172        let mut asked = None;
1173        ui.horizontal(|ui| {
1174            ui.label(egui::RichText::new("Look at it in").weak());
1175            for (jump, key, label, hover) in [
1176                (Jump::Symbol, "symbol", "Symbol", "Open the schematic symbol with this point's PIN selected"),
1177                (Jump::Pads, "pads", "Pads", "Open the footprint with this point's PAD selected"),
1178                (Jump::Model, "model", "3D", "Show the model with this point's geometry selected"),
1179            ] {
1180                let here = match jump {
1181                    Jump::Symbol => target == Some(Target::Symbol),
1182                    Jump::Pads => target == Some(Target::Pads),
1183                    Jump::Model => target.is_none(),
1184                };
1185                let button = ui
1186                    .add_enabled(!here, egui::Button::new(label).small())
1187                    .on_hover_text(format!("{hover} ({address})"))
1188                    .on_disabled_hover_text("You are looking at it");
1189                self.hits.insert(format!("qualify:jump:{key}"), button.rect);
1190                if button.clicked() {
1191                    asked = Some(jump);
1192                }
1193            }
1194        });
1195        asked
1196    }
1197
1198    /// The two consistency reports, which exist to be shown and were shown
1199    /// nowhere: the pin/point pairing and the ports tail's own resolution.
1200    fn reports(&mut self, ui: &mut egui::Ui, engine: &EngineState) {
1201        let mut problem = 0usize;
1202        let mut line = |ui: &mut egui::Ui,
1203                        hits: &mut HashMap<String, egui::Rect>,
1204                        text: String,
1205                        color: egui::Color32| {
1206            let label = ui.label(egui::RichText::new(text).weak().color(color));
1207            hits.insert(format!("qualify:problem:{problem}"), label.rect);
1208            problem += 1;
1209        };
1210
1211        ui.label(egui::RichText::new("Pins and points").strong());
1212        match engine.history.pin_point_report() {
1213            None => {
1214                ui.label(
1215                    egui::RichText::new("this part has no symbol, so its points bind to no pins")
1216                        .weak(),
1217                );
1218            }
1219            Some(PinPointReport { pairs, problems }) => {
1220                ui.label(
1221                    egui::RichText::new(format!(
1222                        "{} pin{} paired",
1223                        pairs.len(),
1224                        if pairs.len() == 1 { "" } else { "s" }
1225                    ))
1226                    .weak()
1227                    .color(if problems.is_empty() { OK_COLOR } else { WARN_COLOR }),
1228                );
1229                for entry in &problems {
1230                    line(ui, &mut self.hits, entry.message(), WARN_COLOR);
1231                }
1232            }
1233        }
1234        // A HOLD is the live state of the edit in flight, not a property of the
1235        // document: the last keystroke could not be carried to the other side,
1236        // and the next one will be diffed from the same base again.
1237        if let Some(hold) = engine.history.pin_port_hold() {
1238            line(ui, &mut self.hits, format!("not carried to the pins: {hold}"), WARN_COLOR);
1239        }
1240
1241        ui.add_space(2.0);
1242        ui.label(egui::RichText::new("Ports").strong());
1243        match engine.ports_report() {
1244            None => {
1245                ui.label(egui::RichText::new("the model has not run yet").weak());
1246            }
1247            Some(report) => {
1248                ui.label(
1249                    egui::RichText::new(format!(
1250                        "{} point{} resolved | {}",
1251                        report.points.len(),
1252                        if report.points.len() == 1 { "" } else { "s" },
1253                        if report.boundary {
1254                            "a boundary: a parent sees only what this document declares"
1255                        } else {
1256                            "transparent: a parent sees this document's children too"
1257                        },
1258                    ))
1259                    .weak()
1260                    .color(if report.problems.is_empty() { OK_COLOR } else { ERROR_COLOR }),
1261                )
1262                .on_hover_text(if report.boundary {
1263                    "A board hides its components behind the ports it declares itself (`portBoundary`, or a `pcb` block)."
1264                } else {
1265                    "An enclosure does not hide the parts in it: their points are exported namespaced."
1266                });
1267                for entry in &report.problems {
1268                    line(ui, &mut self.hits, entry.clone(), ERROR_COLOR);
1269                }
1270            }
1271        }
1272        // A point that maps DOWN says where to, since `mapsTo` is the one field
1273        // whose meaning is another document's.
1274        if let Some(report) = engine.ports_report() {
1275            for row in report.points.iter().filter(|row| row.maps_to.is_some()) {
1276                let target = row.maps_to.clone().unwrap_or_default();
1277                line(
1278                    ui,
1279                    &mut self.hits,
1280                    format!("{} \u{2192} {target}", row.address),
1281                    ui.visuals().weak_text_color(),
1282                );
1283            }
1284        }
1285    }
1286
1287    // --- acting -------------------------------------------------------------
1288
1289    /// Apply one edit to the raw block and write it back. The write carries the
1290    /// pin/point follow, and sets the flag that re-runs the history next frame.
1291    fn apply(&mut self, engine: &mut EngineState, edit: Edit, coalesce: Option<&str>) {
1292        let mut block = engine
1293            .history
1294            .ports_block()
1295            .and_then(Value::as_array)
1296            .cloned()
1297            .unwrap_or_default();
1298        match edit {
1299            Edit::AddGroup => {
1300                block.push(serde_json::json!({
1301                    "name": unique_group_name(&block),
1302                    "purpose": PURPOSES[0],
1303                    "points": [],
1304                }));
1305            }
1306            Edit::RemoveGroup(gi) => {
1307                if gi < block.len() {
1308                    block.remove(gi);
1309                }
1310            }
1311            Edit::GroupName(gi, name) => {
1312                // Renaming a group moves EVERY address in it, and the selection
1313                // is held by address — so carry it, exactly as a point rename
1314                // does, or the point being edited deselects itself the moment
1315                // its group's name is touched.
1316                let was = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str);
1317                if let (Some(was), Some(address)) = (was, self.selected.clone()) {
1318                    if let Some((port, point)) = brep_kernel::split_address(&address) {
1319                        if port == was {
1320                            self.selected = Some(brep_kernel::port_address(&name, point));
1321                        }
1322                    }
1323                }
1324                set_group(&mut block, gi, "name", Value::String(name));
1325            }
1326            Edit::GroupPurpose(gi, purpose) => {
1327                set_group(&mut block, gi, "purpose", Value::String(purpose));
1328            }
1329            Edit::GroupUnit(gi, unit) => match unit {
1330                Some(unit) => set_group(&mut block, gi, "symbolUnit", Value::from(unit)),
1331                None => remove_group_key(&mut block, gi, "symbolUnit"),
1332            },
1333            Edit::AddPoint(gi) => {
1334                if let Some(points) = points_mut(&mut block, gi) {
1335                    let name = unique_point_name(points);
1336                    points.push(serde_json::json!({
1337                        "name": name,
1338                        "transform": { "position": [0.0, 0.0, 0.0], "rotationEuler": [0.0, 0.0, 0.0] },
1339                    }));
1340                }
1341            }
1342            Edit::RemovePoint(gi, pi) => {
1343                if let Some(points) = points_mut(&mut block, gi) {
1344                    if pi < points.len() {
1345                        points.remove(pi);
1346                    }
1347                }
1348            }
1349            Edit::PointName(gi, pi, name) => {
1350                // The selection is held by ADDRESS, so a rename has to move it
1351                // or the point the user is editing deselects itself mid-word.
1352                if let Some(group) = block.get(gi).and_then(|group| group.get("name")).and_then(Value::as_str) {
1353                    self.selected = Some(brep_kernel::port_address(group, &name));
1354                }
1355                set_point(&mut block, gi, pi, "name", Value::String(name));
1356            }
1357            Edit::PointText(gi, pi, key, text) => match text.trim().is_empty() {
1358                true => remove_point_key(&mut block, gi, pi, key),
1359                // A reference names geometry or a point: it is TEXT even when
1360                // it reads as a number. `scalar` stored `0` as `0.0`, which the
1361                // kernel's block read refused whole (a reported bug).
1362                false => set_point(&mut block, gi, pi, key, match key {
1363                    "pointRef" | "directionRef" | "contactBody" | "mapsTo" => {
1364                        Value::String(text.trim().to_string())
1365                    }
1366                    _ => scalar(&text),
1367                }),
1368            },
1369            Edit::PointTransform(gi, pi, key, axis, text) => {
1370                set_transform_component(&mut block, gi, pi, key, axis, scalar(&text));
1371            }
1372            Edit::PointReverse(gi, pi, reverse) => match reverse {
1373                true => set_point(&mut block, gi, pi, "reverseDirection", Value::Bool(true)),
1374                false => remove_point_key(&mut block, gi, pi, "reverseDirection"),
1375            },
1376        }
1377        // An EMPTY block is not a block: the kernel omits it on re-serialize,
1378        // and leaving `[]` behind would keep this pane up over a part with
1379        // nothing to qualify. Removing the last group therefore closes the pane,
1380        // which is worth saying out loud.
1381        if block.is_empty() {
1382            engine.history.set_ports_block(None, None);
1383            engine.push_notice("the last connection-point group is gone; the Qualify pane closes with it");
1384            return;
1385        }
1386        engine.history.set_ports_block(Some(Value::Array(block)), coalesce);
1387    }
1388
1389    /// Carry the selected point to another surface: switch the workbench and
1390    /// hand the editor the selection to make when it next draws.
1391    ///
1392    /// The editor selection is DEFERRED rather than set here: the editor is
1393    /// re-handed its block on the frame it is drawn (`viewport::ecad`'s pull),
1394    /// which clears whatever it had selected, so a selection set now would be
1395    /// wiped by the switch itself.
1396    fn jump(&mut self, engine: &mut EngineState, ecad: &mut Editors, jump: Jump) {
1397        let Some(address) = self.selected.clone() else {
1398            return;
1399        };
1400        let Some((_, name)) = brep_kernel::split_address(&address) else {
1401            return;
1402        };
1403        let (target, workbench) = match jump {
1404            Jump::Symbol => (Some(Target::Symbol), "symbol"),
1405            Jump::Pads => (Some(Target::Pads), "pads"),
1406            Jump::Model => (None, MODEL_WORKBENCH),
1407        };
1408        match target {
1409            Some(target) => ecad.focus(target, name.to_string()),
1410            None => {
1411                // The part's OWN points resolve at the TAIL of the run, so one
1412                // the last run did not resolve has nothing in the scene to
1413                // select. Selecting its name anyway would light nothing and
1414                // leave a phantom selection behind, so say so instead.
1415                if resolved(engine, &address) {
1416                    engine.select_by_name("solid", &address);
1417                } else {
1418                    engine.push_notice(format!(
1419                        "{address} has no geometry yet \u{2014} the last run did not resolve it"
1420                    ));
1421                }
1422            }
1423        }
1424        // A workbench that ALREADY draws what was asked for is left alone: a
1425        // user in Modeling who asks to see the point in 3D wants the selection,
1426        // not to be moved to another workbench.
1427        let already = match jump {
1428            Jump::Model => Target::of_workbench(&engine.settings.workbench).is_none(),
1429            _ => false,
1430        };
1431        if !already && engine.settings.workbench != workbench {
1432            // The SAME seam the workbench dropdown writes through, but NOT
1433            // persisted to the settings blob: a jump is navigation within a
1434            // document, like the assembly auto-switch, and the blob stays the
1435            // user's boot preference.
1436            let _ = engine
1437                .apply_settings_json(&serde_json::json!({ "workbench": workbench }).to_string());
1438        }
1439    }
1440
1441    /// Adopt the eCAD editor's own selection when it names a connection point:
1442    /// picking pin `VCC` in the symbol selects `J1.VCC` here, which is the half
1443    /// of "select it there, look at it here" the jump buttons do not cover.
1444    fn adopt_editor_selection(&mut self, engine: &EngineState, ecad: &Editors, target: Option<Target>) {
1445        // The 3D surface has a selection of its own, and it already names the
1446        // point: a declared point draws as a sheet keyed by its address. This
1447        // is the direction the panel could not reach before — clicking a point
1448        // in the viewport now opens it here.
1449        let (surface, label) = match target {
1450            None => (MODEL_SURFACE, engine.selected_port_point()),
1451            Some(target @ (Target::Symbol | Target::Pads)) => {
1452                (surface_of(target), editor_selection(ecad, target))
1453            }
1454            // A schematic sheet or a board: neither selects a pin or a pad, so
1455            // there is nothing of this part's to adopt.
1456            Some(_) => return,
1457        };
1458        let Some(label) = label else {
1459            // Nothing selected over there clears what was adopted FROM there,
1460            // so re-picking the same pin is a new pick.
1461            if self.adopted.as_ref().is_some_and(|(from, _)| *from == surface) {
1462                self.adopted = None;
1463            }
1464            return;
1465        };
1466        if self.adopted.as_ref().is_some_and(|(from, what)| *from == surface && *what == label) {
1467            return;
1468        }
1469        self.adopted = Some((surface, label.clone()));
1470        // The 3D surface's selection IS the address — the join the two eCAD
1471        // surfaces need is already made there.
1472        if surface == MODEL_SURFACE {
1473            self.selected = Some(label);
1474            return;
1475        }
1476        // A pin's group is its UNIT's group: a pad matches its pin by number
1477        // symbol-wide, so both surfaces route through the same join.
1478        let unit = engine
1479            .history
1480            .pins()
1481            .unwrap_or_default()
1482            .into_iter()
1483            .find(|pin| pin.label == label)
1484            .map(|pin| pin.unit)
1485            .unwrap_or(1);
1486        if let Some(group) = engine.history.port_group_for_unit(unit) {
1487            self.selected = Some(brep_kernel::port_address(&group, &label));
1488        }
1489    }
1490}
1491
1492/// Whether the LAST RUN resolved `address` — whether, in other words, there is
1493/// anything in the scene under that name to select. A part's own points are
1494/// resolved at the tail of the run, so a point just typed in has none until the
1495/// next one finishes.
1496fn resolved(engine: &EngineState, address: &str) -> bool {
1497    engine
1498        .ports_report()
1499        .is_some_and(|report| report.points.iter().any(|row| row.address == address))
1500}
1501
1502/// What `target`'s editor currently has selected, by NUMBER — the one reading
1503/// of it, so a pick and the adopt that follows it cannot disagree about what
1504/// the editor holds. `None` for a surface that selects no pin or pad.
1505fn editor_selection(ecad: &Editors, target: Target) -> Option<String> {
1506    match target {
1507        Target::Symbol => ecad.symbol.selected_pin().map(str::to_string),
1508        Target::Pads => ecad.pads.selected_pad().map(str::to_string),
1509        Target::Pcb => None,
1510    }
1511}
1512
1513/// The key an adopted editor selection is remembered under. A `&'static str`
1514/// rather than the `Target` itself, because what is remembered is "the last
1515/// thing I saw selected over there" and the two eCAD editors are the only
1516/// surfaces that have one.
1517fn surface_of(target: Target) -> &'static str {
1518    match target {
1519        Target::Symbol => "symbol",
1520        Target::Pads => "pads",
1521        Target::Pcb => "pcb",
1522    }
1523}
1524
1525// ---------------------------------------------------------------------------
1526// Raw-block helpers: every edit touches ONE key, so a field this panel does not
1527// know about survives an edit to the field beside it.
1528// ---------------------------------------------------------------------------
1529
1530fn set_group(block: &mut [Value], gi: usize, key: &str, value: Value) {
1531    if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1532        object.insert(key.into(), value);
1533    }
1534}
1535
1536fn remove_group_key(block: &mut [Value], gi: usize, key: &str) {
1537    if let Some(object) = block.get_mut(gi).and_then(Value::as_object_mut) {
1538        object.remove(key);
1539    }
1540}
1541
1542fn points_mut(block: &mut [Value], gi: usize) -> Option<&mut Vec<Value>> {
1543    let group = block.get_mut(gi)?.as_object_mut()?;
1544    group.entry("points").or_insert_with(|| Value::Array(Vec::new())).as_array_mut()
1545}
1546
1547fn point_mut<'a>(block: &'a mut [Value], gi: usize, pi: usize) -> Option<&'a mut serde_json::Map<String, Value>> {
1548    points_mut(block, gi)?.get_mut(pi)?.as_object_mut()
1549}
1550
1551fn set_point(block: &mut [Value], gi: usize, pi: usize, key: &str, value: Value) {
1552    if let Some(point) = point_mut(block, gi, pi) {
1553        point.insert(key.into(), value);
1554    }
1555}
1556
1557fn remove_point_key(block: &mut [Value], gi: usize, pi: usize, key: &str) {
1558    if let Some(point) = point_mut(block, gi, pi) {
1559        point.remove(key);
1560    }
1561}
1562
1563/// Write one component of `transform.position` / `transform.rotationEuler`,
1564/// filling in the array (and the transform) when the point has none.
1565fn set_transform_component(
1566    block: &mut [Value],
1567    gi: usize,
1568    pi: usize,
1569    key: &str,
1570    axis: usize,
1571    value: Value,
1572) {
1573    let Some(point) = point_mut(block, gi, pi) else {
1574        return;
1575    };
1576    let transform = point
1577        .entry("transform")
1578        .or_insert_with(|| Value::Object(Default::default()));
1579    if !transform.is_object() {
1580        *transform = Value::Object(Default::default());
1581    }
1582    let Some(transform) = transform.as_object_mut() else {
1583        return;
1584    };
1585    let axes = transform
1586        .entry(key.to_string())
1587        .or_insert_with(|| Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]));
1588    if !axes.is_array() {
1589        *axes = Value::Array(vec![Value::from(0.0), Value::from(0.0), Value::from(0.0)]);
1590    }
1591    if let Some(axes) = axes.as_array_mut() {
1592        while axes.len() < 3 {
1593            axes.push(Value::from(0.0));
1594        }
1595        axes[axis] = value;
1596    }
1597}
1598
1599/// A typed field's value: a NUMBER when it parses as one, else the string,
1600/// which the transform lane reads as an expression. An empty field is `0`
1601/// rather than an empty expression, because a blank component is not a
1602/// placement.
1603fn scalar(text: &str) -> Value {
1604    let text = text.trim();
1605    if text.is_empty() {
1606        return Value::from(0.0);
1607    }
1608    match text.parse::<f64>() {
1609        Ok(number) => Value::from(number),
1610        Err(_) => Value::String(text.to_string()),
1611    }
1612}
1613
1614/// One component of a point's transform as the field shows it: a number
1615/// formatted plainly, an expression verbatim, and `0` for a point with no
1616/// transform at all.
1617fn transform_component(point: &brep_kernel::PortPoint, key: &str, axis: usize) -> String {
1618    match point.transform.get(key).and_then(Value::as_array).and_then(|axes| axes.get(axis)) {
1619        // COMPACT, not `to_string`: the block carries a component the panel
1620        // wrote as a JSON float, so an untouched zero read back as `0.0` and a
1621        // whole millimetre as `2.0`. Six places is past anything a placement
1622        // field is typed to and short of f64 noise.
1623        Some(Value::Number(number)) => match number.as_f64() {
1624            Some(value) => brep_render::formatting::compact_decimal(value, 6),
1625            None => number.to_string(),
1626        },
1627        Some(Value::String(expression)) => expression.clone(),
1628        _ => "0".to_string(),
1629    }
1630}
1631
1632/// One of the point's optional scalar fields as its field shows it — empty
1633/// where the point does not carry it.
1634fn optional_text(point: &brep_kernel::PortPoint, key: &str) -> String {
1635    match key {
1636        "pointRef" => point.point_ref.clone().unwrap_or_default(),
1637        "directionRef" => point.direction_ref.clone().unwrap_or_default(),
1638        "contactBody" => point.contact_body.clone().unwrap_or_default(),
1639        "mapsTo" => point.maps_to.clone().unwrap_or_default(),
1640        "extension" => point.extension.map(|v| v.to_string()).unwrap_or_default(),
1641        "displayLength" => point.display_length.map(|v| v.to_string()).unwrap_or_default(),
1642        _ => String::new(),
1643    }
1644}
1645
1646/// One status lamp: catalogued artwork where the glyph has some, a coloured
1647/// character where it does not.
1648fn lamp(ui: &mut egui::Ui, glyph: &str, color: egui::Color32) -> egui::Response {
1649    match crate::icon_text::glyph(ui, glyph, color) {
1650        Some(art) => ui.add(art),
1651        None => ui.label(egui::RichText::new(glyph).color(color)),
1652    }
1653}
1654
1655/// A vector as the seat readout prints it: three numbers, short.
1656fn triple(values: [f64; 3]) -> String {
1657    values
1658        .iter()
1659        .map(|value| {
1660            let rounded = (value * 1000.0).round() / 1000.0;
1661            // `-0` is the same place as `0` and reads as a mistake.
1662            if rounded == 0.0 { "0".to_string() } else { format!("{rounded}") }
1663        })
1664        .collect::<Vec<_>>()
1665        .join(", ")
1666}
1667
1668/// The footprint's pad numbers. A pad matches a pin by number symbol-wide, and
1669/// a pin carries its point's name, so a pad is this point's when its number is
1670/// the point's name — which is exactly the join `part_pins` makes.
1671fn pad_numbers(engine: &EngineState) -> Vec<String> {
1672    engine
1673        .history
1674        .pads_block()
1675        .and_then(|block| block.get("pads"))
1676        .and_then(Value::as_array)
1677        .map(|pads| {
1678            pads.iter()
1679                .filter_map(|pad| pad.get("number").and_then(Value::as_str))
1680                .map(str::to_string)
1681                .collect()
1682        })
1683        .unwrap_or_default()
1684}
1685
1686/// `J1`, `J2`, … — the first that no group in the block has taken.
1687fn unique_group_name(block: &[Value]) -> String {
1688    let taken: Vec<&str> = block
1689        .iter()
1690        .filter_map(|group| group.get("name").and_then(Value::as_str))
1691        .collect();
1692    (1..).map(|n| format!("J{n}")).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1693}
1694
1695/// `1`, `2`, … — the first that no point in the group has taken. A number, not
1696/// a word, because a pin's label is what this becomes and pins are numbered.
1697fn unique_point_name(points: &[Value]) -> String {
1698    let taken: Vec<&str> = points
1699        .iter()
1700        .filter_map(|point| point.get("name").and_then(Value::as_str))
1701        .collect();
1702    (1..).map(|n| n.to_string()).find(|name| !taken.contains(&name.as_str())).unwrap_or_default()
1703}
1704
1705pub static HIT_KEYS: &[HitKeyDoc] = &[
1706    HitKeyDoc { panel: "qualify", prefix: "qualify:panel:clip", meaning: "the visible region of the pane", command: None },
1707    HitKeyDoc { panel: "qualify", prefix: "qualify:add_group", meaning: "declare another port group", command: None },
1708    HitKeyDoc { panel: "qualify", prefix: "qualify:group:", meaning: "a port group's name, purpose, symbol unit, add-point or remove", command: None },
1709    HitKeyDoc { panel: "qualify", prefix: "qualify:point:", meaning: "a connection point's select, name, remove, or one of the selected point's fields", command: None },
1710    HitKeyDoc { panel: "qualify", prefix: "qualify:jump:", meaning: "carry the selected point to the symbol, the pads or the 3D model", command: None },
1711    HitKeyDoc { panel: "qualify", prefix: "qualify:hint", meaning: "what selecting a point is for, shown while none is", command: None },
1712    HitKeyDoc { panel: "qualify", prefix: "qualify:seat", meaning: "what the last run made of the selected point's seat", command: None },
1713    HitKeyDoc { panel: "qualify", prefix: "qualify:pinseat:", meaning: "a pcb point's pin seat check, by address: whether its 3D seat lands on its pin's pad", command: None },
1714    HitKeyDoc { panel: "qualify", prefix: "qualify:gizmo", meaning: "whether the move/rotate handles are on the selected point", command: None },
1715    HitKeyDoc { panel: "qualify", prefix: "qualify:problem:", meaning: "one line of the pin/point or ports report", command: None },
1716    HitKeyDoc { panel: "qualify", prefix: "qualify:mount:", meaning: "the part's mount frame on the board: its status, a move or turn field (translate0..2, rotateEulerDeg0..2), Y up to Z up, reset, a pick (seat on a face, origin to a point), Align to footprint (align) and its report lines (align_report:N)", command: None },
1717];
1718