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