Skip to main content

brep_ecad_egui/
lib.rs

1//! Embeddable egui editors for BREP_ecad_core documents: schematic and
2//! wiring-diagram sheets, the board, symbols and pads (footprints).
3//!
4//! The host owns file I/O and application chrome. [`Editor`] edits the
5//! [`Document`] it holds; call [`Editor::toolbar`] and [`Editor::show`] each
6//! frame and take [`Editor::take_change`] to learn that something changed.
7//! [`actions()`] lists every command, named and grouped, for a host's toolbar,
8//! menus and automation. [`SymbolEditor`] and [`FootprintEditor`] edit one
9//! symbol or one footprint. See the README for an example.
10use std::collections::BTreeMap;
11use brep_ecad_core::{
12    Component, ConnectionTarget, Document, DocumentKind, Graphic, History, Label, PartSource,
13    Point, Symbol, Terminal, Uuid,
14};
15use egui::{Align2, Color32, FontId, Key, PointerButton, Pos2, Rect, Sense, Stroke, Vec2};
16
17mod actions;
18pub mod widgets;
19mod editor_core;
20
21/// `n` and its noun, singular for exactly one: "1 pad", "2 pads", "0 pads".
22/// The panels' counts read "1 pads" and "1 graphics" (lane U audit item 8).
23pub(crate) fn count(n: usize, one: &str, many: &str) -> String {
24    format!("{n} {}", if n == 1 { one } else { many })
25}
26mod board_view;
27mod erc_panel;
28mod footprint_editor;
29mod grips;
30mod pin_functions;
31mod symbol_editor;
32pub use actions::{Action, ActionGroup, actions};
33pub use board_view::{BoardSelection, BoardTool, View};
34pub use footprint_editor::{FootprintEditor, pad_actions};
35pub use symbol_editor::{PinPoints, SymbolEditor, symbol_actions};
36
37/// Keep zoom free of product limits, rejecting only scales that cannot be
38/// represented by the canvas math (including projected integer coordinates).
39fn valid_zoom(candidate: f32, previous: f32) -> f32 {
40    if candidate > 0.0
41        && candidate.recip().is_finite()
42        && (candidate * i32::MAX as f32).is_finite()
43    {
44        candidate
45    } else {
46        previous
47    }
48}
49
50fn scaled_zoom(current: f32, factor: f32) -> f32 {
51    valid_zoom(current * factor, current)
52}
53
54/// Preserve the world point under an anchor while scaling. Commit both pieces
55/// together, so a numeric overflow cannot leave a broken pan behind.
56fn zoom_at(zoom: &mut f32, pan: &mut Vec2, factor: f32, anchor: Vec2) {
57    let next = scaled_zoom(*zoom, factor);
58    let next_pan = anchor - (anchor - *pan) * (next / *zoom);
59    if next_pan.x.is_finite() && next_pan.y.is_finite() {
60        *zoom = next;
61        *pan = next_pan;
62    }
63}
64
65/// The zoom the wheel and a pinch ask of a 2D canvas this frame, with the
66/// screen point to hold still while it is applied: the pointer, or a touch
67/// pinch's centre. The plain wheel, a ctrl-wheel (which egui turns into
68/// `zoom_delta` and takes OUT of the scroll delta, so the two never add up) and
69/// a trackpad or touch pinch all zoom the same way, about the same point.
70/// `None` when nothing asks for a zoom.
71pub(crate) fn pointer_zoom(ui: &egui::Ui) -> Option<(f32, Pos2)> {
72    ui.input(|i| {
73        let factor = (i.smooth_scroll_delta.y * 0.002).exp() * i.zoom_delta();
74        let at = i.multi_touch().map(|t| t.center_pos).or(i.pointer.hover_pos())?;
75        (factor.is_finite() && factor > 0. && factor != 1.).then_some((factor, at))
76    })
77}
78
79/// Whether two or more fingers are on a touch screen: a pinch. The first
80/// finger of a pinch is also the primary pointer, so while one is on, an
81/// editor drags nothing: a drag already running is taken back and none starts,
82/// so zooming never moves what the first finger landed on.
83pub(crate) fn pinching(ui: &egui::Ui) -> bool {
84    ui.input(|i| i.multi_touch().is_some())
85}
86
87/// Coarsen the displayed grid by whole multiples of its snapping grid. Iteration
88/// is in screen space, so zooming out cannot enumerate millions of world points.
89fn grid_spacing(zoom: f32) -> f32 {
90    let mut spacing = 1270.0 * zoom;
91    while spacing > 0.0 && spacing < 8.0 {
92        spacing *= 5.0;
93    }
94    spacing
95}
96
97/// Large zoomed labels must scale their drawing, not allocate enormous glyphs
98/// in the font atlas. Keep ordinary sizes unchanged and scale the cached mesh
99/// above that size; this is a rasterization budget, not a view zoom limit.
100fn zoomed_text(ctx: &egui::Context, text: String, mut font: FontId, color: Color32) -> std::sync::Arc<egui::Galley> {
101    let scale = (font.size / 96.0).max(1.0);
102    font.size /= scale;
103    let galley = ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text, font, color));
104    if scale == 1.0 {
105        return galley;
106    }
107    let mut shape = egui::epaint::TextShape::new(Pos2::ZERO, galley, color);
108    shape.transform(egui::emath::TSTransform::from_scaling(scale));
109    shape.galley
110}
111
112/// `galley` placed by `align` about `anchor` as it would be unturned, then
113/// turned `degrees` counter-clockwise as seen about `anchor`.
114pub(crate) fn turned_text(
115    painter: &egui::Painter,
116    anchor: Pos2,
117    align: Align2,
118    galley: std::sync::Arc<egui::Galley>,
119    color: Color32,
120    degrees: i32,
121) {
122    let min = align.anchor_size(anchor, galley.size()).min;
123    // egui turns clockwise; the model's angles are counter-clockwise.
124    let angle = -(degrees as f32).to_radians();
125    let pos = anchor + egui::emath::Rot2::from_angle(angle) * (min - anchor);
126    painter.add(egui::epaint::TextShape::new(pos, galley, color).with_angle(angle));
127}
128
129const INK: Color32 = Color32::from_rgb(211, 220, 233);
130const ACCENT: Color32 = Color32::from_rgb(89, 218, 180);
131const WIRE: Color32 = Color32::from_rgb(93, 186, 228);
132/// Emphasis in panel text: the theme's own accent, so a label reads on the light
133/// theme as well as the dark. [`ACCENT`] is for the canvases, which paint their own
134/// dark ground; on a light panel it measured 1.63:1 against a 4.5:1 floor.
135pub(crate) fn accent(ui: &egui::Ui) -> Color32 {
136    ui.visuals().selection.stroke.color
137}
138/// Whether an eCAD editor that is up takes this frame's keys: every key, wherever
139/// the pointer is, unless a TEXT FIELD has the keyboard (in the Inspector, a side
140/// pane, the tool card or a window). All four editors ask this before their
141/// shortcuts: Diagram and PCB in their own `show`, Symbol and Pads in their
142/// `run_shortcuts`. The host's Delete and Escape on an eCAD workbench ask it too. Not
143/// `egui_wants_keyboard_input`: that is ANY focused widget, and a button reached by
144/// Tab would take R from the editor while doing nothing with it.
145///
146/// Nor while a MENU or a combo box is open: it owns the keys, and it closes on
147/// `key_pressed(Escape)`, which a key the editor consumed never is. The canvas's own
148/// right-click menu is drawn after the editor's keys run, so without this Escape
149/// cancelled the editor's selection and left the menu standing over it. Tooltips
150/// are not counted: they are not held open in egui's memory.
151///
152/// Nor under a MODAL (`egui::Modal`, a host's file dialog or eCAD's own
153/// autoroute dialog): it owns every key, and its Escape closes it. egui keeps
154/// the top modal layer of the LAST pass, which is what this reads, so it covers
155/// an editor drawn by any host and needs no list of the modals. On the one
156/// frame a modal first opens it reads nothing: egui's current-pass record is
157/// private (`Focus::top_modal_layer_current_frame`), and a modal drawn after
158/// the editor has not been drawn when the editor's keys run in any case.
159pub fn keys_reach_editor(ctx: &egui::Context) -> bool {
160    !ctx.text_edit_focused()
161        && !egui::Popup::is_any_open(ctx)
162        && ctx.memory(|memory| memory.top_modal_layer()).is_none()
163}
164#[derive(Clone, Copy, PartialEq, Eq, Debug)]
165pub enum Tool {
166    Select,
167    Wire,
168    Junction,
169    Label,
170    Place,
171    Move,
172    /// Marks a pin as meant to be left open, KiCad's no-connect ✕; a second click
173    /// takes the mark off.
174    NoConnect,
175    /// Puts KiCad's PWR_FLAG on a pin, or on the net under the click: the net is
176    /// driven from off the sheet. A second click takes it off.
177    PowerFlag,
178    /// Places a power symbol for [`Editor::power_net_text`]: a part with one power
179    /// input pin whose net takes the symbol's name, so every symbol of one name is
180    /// one net, as in KiCad.
181    Power,
182}
183/// The power symbols the Power tool offers by name; any other name may be typed.
184pub const POWER_NETS: [&str; 4] = ["GND", "VCC", "+3V3", "+5V"];
185/// Whether a power net's symbol is drawn as a ground, bars below its pin, rather
186/// than as a supply, an arrow above it.
187pub fn is_ground(name: &str) -> bool {
188    let name = name.to_ascii_uppercase();
189    name.contains("GND") || name.starts_with("VSS") || name.starts_with("VEE") || name.starts_with('-')
190}
191/// The power symbol for net `name`, as KiCad's `power` library draws one: a single
192/// hidden power input pin at its origin, named for the net, under reference
193/// `#PWR`. [`Document::place`](brep_ecad_core::Document::place_power_symbol) names the pin's net after [`Symbol::power_net`], so
194/// every power symbol of one name is one net; the board and the parts list leave
195/// it out, as they leave out KiCad's. Its pin is a power INPUT, as KiCad's is, so
196/// it does not drive the net: a net fed from off the sheet still wants a power
197/// flag ([`Tool::PowerFlag`]).
198pub fn power_symbol(name: &str) -> Symbol {
199    let p = Point::new;
200    let graphics = if is_ground(name) {
201        // KiCad's GND: a stem down from the pin and a triangle under it.
202        vec![Graphic::Path(vec![
203            p(0, 0),
204            p(0, 1270),
205            p(1270, 1270),
206            p(0, 2540),
207            p(-1270, 1270),
208            p(0, 1270),
209        ])]
210    } else {
211        // KiCad's +5V: a stem up from the pin and an arrowhead on it.
212        vec![
213            Graphic::Path(vec![p(0, 0), p(0, -2540)]),
214            Graphic::Path(vec![p(-762, -1270), p(0, -2540), p(762, -1270)]),
215        ]
216    };
217    Symbol {
218        unit_count: 1,
219        properties: BTreeMap::from([("Value".to_owned(), name.to_owned())]),
220        power_net: Some(name.to_owned()),
221        library_id: format!("power:{name}"),
222        reference_prefix: "#PWR".into(),
223        description: format!("Power symbol: the {name} net"),
224        graphics,
225        pins: vec![brep_ecad_core::Pin {
226            hidden: true,
227            unit: 0,
228            gate: 0,
229            number: "1".into(),
230            name: name.to_owned(),
231            alternates: vec![],
232            electrical_type: "power_in".into(),
233            at: Point::default(),
234            end: Point::default(),
235        }],
236        graphic_gates: vec![],
237        hide_pin_names: true,
238        hide_pin_numbers: true,
239    }
240}
241#[derive(Clone, Copy, PartialEq, Eq, Debug)]
242pub enum Selection {
243    Component(Uuid),
244    Wire(Uuid),
245    Label(Uuid),
246    Junction(Point),
247}
248
249/// Private payload type prevents collisions with the embedding host's drag data.
250struct LibraryPartDrag(Part);
251
252/// A part the host offers to place: its own key and version, the name to show, the
253/// symbol and pads a placed component copies, and the label it goes by.
254#[derive(Clone, Debug, PartialEq)]
255pub struct Part {
256    pub source: PartSource,
257    pub name: String,
258    pub symbol: Symbol,
259    pub pads: Option<brep_ecad_core::board::Footprint>,
260    /// The label the placed component takes, such as `J1`, when the host keeps the
261    /// labels; `None` takes the next free one for the symbol's prefix. A part whose
262    /// label is already on the sheet shows as placed and is not placed again.
263    pub reference: Option<String>,
264}
265
266/// Opening setup for a context menu or a dropdown list. egui lays these out
267/// justified, so an item is only as wide as the space the pointer happened to leave
268/// and its label wraps in the gap. Keep labels on one line and give the list a width
269/// to start from; it still grows to whatever the longest item needs.
270fn menu_ui(ui: &mut egui::Ui) {
271    ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
272    ui.set_min_width(170.);
273}
274
275#[derive(Clone, Copy, PartialEq, Eq, Debug)]
276enum HistoryKey {
277    Undo,
278    Redo,
279}
280/// An edit the host has not taken yet; see [`Editor::take_change`].
281#[derive(Clone, Debug, PartialEq, Eq)]
282pub struct Change {
283    /// Set for an edit repeated as the user types in one field of one object, such as a
284    /// component's reference. Consecutive changes with the same key may be kept as one
285    /// undo step.
286    pub coalesce: Option<String>,
287}
288
289impl Change {
290    /// Merge edits until the host takes them. A mixed batch cannot coalesce
291    /// with the host's previous undo step, even if its last key matches.
292    fn record(pending: &mut Option<Self>, coalesce: Option<String>) {
293        let coalesce = match pending.take() {
294            Some(change) if change.coalesce != coalesce => None,
295            _ => coalesce,
296        };
297        *pending = Some(Self { coalesce });
298    }
299}
300
301struct NetFlagEdit {
302    terminal: Terminal,
303    name: String,
304    focus: bool,
305}
306
307pub struct Editor {
308    pub document: Document,
309    pub history: History,
310    /// The parts the host offers to place, shown in the library panel. Components
311    /// are placed from parts only: a part carries its symbol and pads.
312    pub parts: Vec<Part>,
313    /// Shown in the library panel while the host offers no parts: where they come from.
314    pub parts_hint: String,
315    /// The keys of the parts the user asked to open, newest last, for the host to take
316    /// and open where it edits a part's symbol and pads.
317    pub open_part_requests: Vec<String>,
318    /// Set when the host can add a part to what [`Editor::parts`] lists: the label of
319    /// the library panel's button that asks it to. `None` draws no button, since a
320    /// button the host cannot answer would be a dead end of its own.
321    pub add_part_label: Option<String>,
322    /// Set by that button, for the host to take and answer.
323    pub add_part_requested: bool,
324    /// Set by **Duplicate** on a component placed from a part every offered
325    /// occurrence of which is already on the sheet: the part keys the user asked
326    /// for ANOTHER occurrence of, for the host to take and add to the assembly
327    /// (a board is an assembly, so another footprint is another component). The
328    /// editor arms placement of the new occurrence when the host offers it
329    /// ([`Editor::arm_pending_duplicate`]).
330    pub duplicate_requests: Vec<String>,
331    /// The part key and rotation a duplicate is waiting on, until the host
332    /// offers an occurrence of it that is not on the sheet.
333    pending_duplicate: Option<(String, u8)>,
334    /// The library panel's widgets as last drawn, keyed for automation (`parts:add`,
335    /// `parts:search`, `parts:card:<reference, else name>`), for the host to take each frame. Empty
336    /// when the panel was not drawn, so a hidden panel publishes nothing stale.
337    pub library_hits: Vec<(String, Rect)>,
338    /// Set when the host keeps the labels of placed parts ([`Part::reference`]): a
339    /// component placed from a part then shows its reference instead of editing it,
340    /// with this text saying where it is set.
341    pub labels_from_host: Option<String>,
342    placing_part: Option<Part>,
343    pub tool: Tool,
344    pub selected: Option<Selection>,
345    /// The other selected items, oldest first (owner 2026-11-27: one shared
346    /// multi-selection, a set plus its primary `selected`). They count only
347    /// while `selected` is still `also_primary`, so a host that sets
348    /// `selected` itself selects that alone.
349    also: Vec<Selection>,
350    also_primary: Option<Selection>,
351    /// A box selection being dragged: where it started and what it does.
352    boxing: Option<(Pos2, footprint_editor::BoxMode)>,
353    /// A drag of a multi-selection: the document before it and where it began.
354    group_drag: Option<(Document, Point)>,
355    /// Which gate of the selected component the pointer picked, for a
356    /// component whose gates are placed apart; see [`Editor::selected_gate`].
357    selected_gate: Option<(Uuid, u32)>,
358    pub label_text: String,
359    /// The net the Power tool's next symbol is for, such as `GND`.
360    pub power_net_text: String,
361    /// Set when the Label tool places a label, for the host's name field to take the
362    /// keyboard back with its text selected: see [`Editor::take_label_placed`].
363    label_placed: bool,
364    /// Stock part number given to new connections in a wiring diagram.
365    pub stock_part_number: String,
366    /// Boards of their own the user asked to edit (by occurrence), for the host to
367    /// open as the Work part ([`Editor::take_enter_requests`]).
368    enter_requests: Vec<String>,
369    /// On a [`DocumentKind::Sheet`]: the HARNESS tools are up (a host's Harness
370    /// diagram workbench) rather than the net tools (its PCB diagram). A connection
371    /// drawn is then a harness wire, a part placed goes off the board, and the
372    /// sheet's net tools are not offered. A wiring diagram has only these and a
373    /// schematic none, whatever this says.
374    pub harness_tools: bool,
375    pub status: String,
376    /// Why the last edit on the sheet was refused, or what it could not do; shown until
377    /// the next press there.
378    notice: Option<String>,
379    /// What the last edit on the sheet did that is worth a line and no alarm,
380    /// such as a label joining a pin to the net its name already names: shown in
381    /// the text colour, until the next press there. A [`Editor::notice`] wins.
382    note: Option<String>,
383    /// [`Editor::offered_mark`] at the last automatic board pass, so the pass runs when
384    /// the host's offer of devices MOVES and not on the frames between. Deliberately
385    /// NOT cleared by [`Editor::set_document`]: the host pulls its own copy of the
386    /// document back under the editor on every undo, and a pass that ran again there
387    /// would put back exactly what the undo took away.
388    followed_parts: Option<u64>,
389    /// [`Editor::stale_mark`] of the board state the last automatic pass in
390    /// [`Editor::show`] healed FROM, so the same state arriving again — which is what an
391    /// app-level undo looks like from here — is left alone. Deliberately NOT cleared by
392    /// [`Editor::set_document`], for the same reason as `followed_parts`.
393    healed_stale: Option<u64>,
394    /// The components already named as wanting a place on the board and having no pads
395    /// to take one with; see [`Editor::announce_without_pads`].
396    reported_without_pads: Vec<String>,
397    /// Edits since the host last called [`Editor::take_change`].
398    pending_change: Option<Change>,
399    pub changed: bool,
400    search: String,
401    placing: Option<Symbol>,
402    rotation: u8,
403    wire_start: Option<Point>,
404    vertical_first: bool,
405    pan: Vec2,
406    zoom: f32,
407    drag: Option<(Document, Point, Point)>,
408    canvas_size: Vec2,
409    terminal_drag: Option<ConnectionTarget>,
410    path_drag: Option<(Document, Uuid, usize, Point)>,
411    selected_segment: usize,
412    context_terminal: Option<Terminal>,
413    net_flag_edit: Option<NetFlagEdit>,
414    pub view: View,
415    board_view: board_view::BoardView,
416    /// The Connectivity panel's electrical rule check ([`erc_panel`]).
417    erc: erc_panel::ErcView,
418    /// The pass the sheet was last drawn in, for the Inspector's rects.
419    canvas_pass: u64,
420    /// A part the palette just put down: the Inspector's Value field takes the
421    /// keyboard once, with the symbol's value selected, so `10k` is typed over it
422    /// as the part lands (the third eCAD audit, B3).
423    value_prompt: Option<Uuid>,
424    /// The Properties section's rects (`inspector:value`, `inspector:value_siblings`).
425    properties_hits: symbol_editor::InspectorHits,
426}
427/// How far the board zone on a sheet reaches past the parts on the board: 5.08 mm.
428pub const ZONE_MARGIN: i32 = 5080;
429
430impl Default for Editor {
431    fn default() -> Self {
432        Self {
433            document: Document::default(),
434            history: History::default(),
435            parts: vec![],
436            parts_hint: "No parts to place.".into(),
437            open_part_requests: vec![],
438            add_part_label: None,
439            add_part_requested: false,
440            duplicate_requests: vec![],
441            pending_duplicate: None,
442            library_hits: vec![],
443            labels_from_host: None,
444            placing_part: None,
445            tool: Tool::Select,
446            selected: None,
447            also: vec![],
448            also_primary: None,
449            boxing: None,
450            group_drag: None,
451            selected_gate: None,
452            label_text: "SIGNAL".into(),
453            power_net_text: "GND".into(),
454            label_placed: false,
455            stock_part_number: String::new(),
456            enter_requests: vec![],
457            harness_tools: false,
458            status: "Choose a part to begin".into(),
459            notice: None,
460            note: None,
461            followed_parts: None,
462            healed_stale: None,
463            reported_without_pads: vec![],
464            pending_change: None,
465            changed: false,
466            search: String::new(),
467            placing: None,
468            rotation: 0,
469            wire_start: None,
470            vertical_first: false,
471            pan: Vec2::ZERO,
472            zoom: 0.012,
473            drag: None,
474            canvas_size: Vec2::new(800., 600.),
475            terminal_drag: None,
476            path_drag: None,
477            selected_segment: 0,
478            context_terminal: None,
479            net_flag_edit: None,
480            view: View::Schematic,
481            board_view: Default::default(),
482            erc: Default::default(),
483            canvas_pass: 0,
484            value_prompt: None,
485            properties_hits: Default::default(),
486        }
487    }
488}
489impl Editor {
490    pub fn replace_document(&mut self, document: Document) {
491        self.document = document;
492        self.history = History::default();
493        self.select_only(None);
494        self.drag = None;
495        self.terminal_drag = None;
496        self.path_drag = None;
497        self.net_flag_edit = None;
498        self.context_terminal = None;
499        self.wire_start = None;
500        self.notice = None;
501        self.note = None;
502        self.followed_parts = None;
503        self.healed_stale = None;
504        self.reported_without_pads = vec![];
505        self.pending_change = None;
506        self.tool = Tool::Select;
507        self.changed = false;
508        self.pan = Vec2::ZERO;
509        self.view = View::Schematic;
510        self.board_view = Default::default();
511        self.erc = Default::default();
512    }
513    /// Load a document the host keeps its own copy of, such as after the host's undo or
514    /// on returning to its tab. Unlike [`Editor::replace_document`] this keeps pan, zoom,
515    /// and the view. Selection, gestures in
516    /// progress, and the editor's own undo history are cleared, and the load is not
517    /// reported by [`Editor::take_change`].
518    pub fn set_document(&mut self, document: Document) {
519        self.cancel();
520        self.reset_board_gestures();
521        self.document = document;
522        self.history = History::default();
523        self.select_only(None);
524        self.net_flag_edit = None;
525        self.context_terminal = None;
526        self.notice = None;
527        self.note = None;
528        self.pending_change = None;
529        self.changed = false;
530        if self.wiring() && self.view == View::Board {
531            self.view = View::Schematic;
532        }
533    }
534    /// Bring the sheet's multi-unit parts saved before gates existed up to the gate
535    /// shape ([`Document::migrate_legacy_units`]), and report that to the host as a
536    /// change, OUTSIDE this editor's own undo. Returns the references it changed.
537    ///
538    /// A host calls it on the frame it first loads the stored sheet, and writes what
539    /// is reported then as part of the document with no undo step, as it does the
540    /// board a sheet saved before the board followed it gets on that frame. It is not
541    /// run on every load: the host's undo also loads the sheet, and a migration there
542    /// would be a fresh edit that ends the user's redo.
543    pub fn adopt_legacy_units(&mut self) -> Vec<String> {
544        let migrated = self.document.migrate_legacy_units();
545        if !migrated.is_empty() {
546            self.changed = true;
547            self.note_change(None);
548        }
549        migrated
550    }
551    /// The edits made since the last call, merged into one, or `None` when the document
552    /// has not changed. A host that saves the document inside its own file calls this
553    /// once a frame and stores [`Editor::document`] when it returns a change. Undo and
554    /// redo in the editor count as changes.
555    pub fn take_change(&mut self) -> Option<Change> {
556        self.pending_change.take()
557    }
558    /// Where the view in front is looking — the sheet's or, on the board view, the
559    /// board's: the drawing origin's offset from the canvas centre in points, and the
560    /// zoom in points per micrometre. Read-only, for a host that shows the view.
561    pub fn pan_zoom(&self) -> (Vec2, f32) {
562        match self.view {
563            View::Board => self.board_view.pan_zoom(),
564            View::Schematic => (self.pan, self.zoom),
565        }
566    }
567    fn note_change(&mut self, coalesce: Option<String>) {
568        Change::record(&mut self.pending_change, coalesce);
569    }
570    /// Record a finished edit that started from `before`, for undo and for the host.
571    fn commit(&mut self, before: Document, coalesce: Option<String>) -> bool {
572        // A sub-board's parts and nets are its own document's: an edit that changes
573        // them other than by moving the whole zone is taken back, and says why.
574        if let Some(refusal) = self.document.zone_edit_refusal(&before) {
575            self.document = before;
576            self.notice = Some(refusal);
577            return false;
578        }
579        // The board follows the sheet INSIDE the edit that moved it: recorded below as
580        // one undo step and reported to the host as one change, with the edit's own
581        // coalesce key, so a part placed on the schematic lands on the board without a
582        // view switch and without a second step to undo. The gate is two id sets
583        // ([`Editor::board_is_stale`]); the sweep behind it runs on the edits that add
584        // or remove a component and on no others.
585        if self.board_is_stale() {
586            let sync = self.document.sync_board();
587            self.announce(&sync, &[]);
588        }
589        if before != self.document {
590            self.changed = true;
591            self.board_view.violations = None;
592            self.note_change(coalesce);
593        }
594        self.history.record(before, &self.document);
595        true
596    }
597    /// Apply one undoable edit. Returns false when the edit was refused because it would
598    /// break a wiring diagram's rules; the document is then unchanged.
599    fn transaction(&mut self, f: impl FnOnce(&mut Document)) -> bool {
600        self.transaction_as(None, f)
601    }
602    /// A transaction whose repeats, such as typing in one field, share `coalesce`.
603    fn transaction_as(&mut self, coalesce: Option<String>, f: impl FnOnce(&mut Document)) -> bool {
604        let before = self.document.clone();
605        f(&mut self.document);
606        // Core edits already keep a wiring diagram valid; this catches any that would not,
607        // so the document can always be saved. Drags that bypass this only move devices,
608        // slide segments between fixed ends, or move labels, which a wiring diagram lacks.
609        if self.document.kind == DocumentKind::Wiring
610            && before != self.document
611            && before.validate().is_ok()
612            && let Err(e) = self.document.validate()
613        {
614            self.document = before;
615            self.notice = Some(e);
616            return false;
617        }
618        self.commit(before, coalesce)
619    }
620    /// Whether the tools up are the harness tools: a wiring diagram's, or a sheet's
621    /// with [`Editor::harness_tools`].
622    fn wiring(&self) -> bool {
623        match self.document.kind {
624            DocumentKind::Wiring => true,
625            DocumentKind::Sheet => self.harness_tools,
626            DocumentKind::Schematic => false,
627        }
628    }
629    /// Whether the harness tools are up, for a host: true for a wiring document, and for a
630    /// sheet while its harness tools are shown.
631    pub fn harness_tools_up(&self) -> bool {
632        self.wiring()
633    }
634    /// Whether the document has no board at all: a wiring diagram. A sheet has one
635    /// whichever tools are up, so the board follows its parts in either.
636    pub(crate) fn boardless(&self) -> bool {
637        self.document.kind == DocumentKind::Wiring
638    }
639    /// Put the selected part of a sheet on the board or take it off, as one edit;
640    /// what refused it is the notice. The action table's `sheet.part.on_board` and
641    /// `sheet.part.off_board`, and the drop of a drag across the board zone's edge.
642    pub fn set_selected_off_board(&mut self, off_board: bool) -> bool {
643        let Some(Selection::Component(id)) = self.selected else { return false };
644        self.set_component_off_board(id, off_board)
645    }
646    fn set_component_off_board(&mut self, id: Uuid, off_board: bool) -> bool {
647        let mut refused = None;
648        let moved = self.transaction(|d| refused = d.set_off_board(id, off_board).err());
649        if let Some(refusal) = refused {
650            self.notice = Some(refusal);
651            return false;
652        }
653        if let Some(c) = self.document.components.iter().find(|c| c.id == id) {
654            self.note = Some(match off_board {
655                true => format!("{} is off the board: its nets let go, and its harness wires stay.", c.reference),
656                false => format!("{} is on the board.", c.reference),
657            });
658        }
659        moved
660    }
661    /// Whether the selection is a part of a sheet that is off the board (`Some(true)`),
662    /// on it (`Some(false)`), or neither.
663    pub fn selected_off_board(&self) -> Option<bool> {
664        let Some(Selection::Component(id)) = self.selected else { return None };
665        (self.document.kind == DocumentKind::Sheet && self.document.zone_member(id).is_none())
666            .then(|| self.document.components.iter().find(|c| c.id == id).map(|c| c.off_board))
667            .flatten()
668    }
669    /// Ask the host to edit the board of its own the selected part is drawn from:
670    /// it becomes the Work part, and the sheet shows the board's own document.
671    pub fn enter_selected_zone(&mut self) -> bool {
672        let Some(Selection::Component(id)) = self.selected else { return false };
673        let Some(z) = self.document.zone_member(id) else { return false };
674        self.enter_requests.push(z.occurrence.clone());
675        true
676    }
677    /// The boards the user asked to edit since the last call, by occurrence.
678    pub fn take_enter_requests(&mut self) -> Vec<String> {
679        std::mem::take(&mut self.enter_requests)
680    }
681    /// The board of its own the selected part of a sheet is drawn from, by label.
682    pub fn selected_zone(&self) -> Option<&str> {
683        let Some(Selection::Component(id)) = self.selected else { return None };
684        self.document.zone_member(id).map(|z| z.reference.as_str())
685    }
686    /// Why a net may not start or end at `target`: a pin of a part off the board.
687    fn net_refusal(&self, target: &ConnectionTarget) -> Option<String> {
688        match target {
689            ConnectionTarget::Terminal(t) if !self.wiring() => self.document.net_reaches(t).err(),
690            ConnectionTarget::Terminal(t) => self.document.harness_reaches(t).err(),
691            _ => None,
692        }
693    }
694    /// The occurrence a component is bound to and the host does not offer — UNLINKED.
695    ///
696    /// A component names its device by OCCURRENCE ([`PartSource::instance`]), which
697    /// changes whenever the device is moved in the assembly tree, and the host's
698    /// `parts` are the devices that assembly reaches. So a bound occurrence the offer
699    /// does not carry is a broken link, and the answer is the user's:
700    /// [`Editor::relink_picker`] asks which device it is and nothing here guesses.
701    ///
702    /// Read where the host owns the parts ([`Editor::labels_from_host`]) and nowhere
703    /// else: on a sheet whose components come from a library rather than from an
704    /// assembly, `parts` says nothing about which occurrences exist.
705    ///
706    /// This is a SUPERSET of the host's own UNLINKED test (`ecad_parts::follow_sheet`),
707    /// by one case: a device the assembly reaches whose part its library does not carry
708    /// is reached there and cannot be offered here, so it reads as unlinked. The host
709    /// reports that state too, in its own words, and picking another device is a fair
710    /// answer to it.
711    fn unlinked_device<'a>(&self, c: &'a Component) -> Option<&'a str> {
712        if self.labels_from_host.is_none() || self.document.zone_member(c.id).is_some() {
713            return None;
714        }
715        let lost = c.part.as_ref()?.instance.as_deref()?;
716        let offered = self
717            .parts
718            .iter()
719            .any(|p| p.source.instance.as_deref() == Some(lost));
720        (!offered).then_some(lost)
721    }
722    /// [`Editor::unlinked_device`] over the whole sheet, in sheet order.
723    fn unlinked(&self) -> Vec<(Uuid, &str)> {
724        self.document
725            .components
726            .iter()
727            .filter_map(|c| Some((c.id, self.unlinked_device(c)?)))
728            .collect()
729    }
730    /// The devices an unlinked component could be bound to, each with the pins it would
731    /// cost, in the order they are offered in.
732    ///
733    /// Every device the host offers that no component of this sheet already carries —
734    /// [`Document::relink`] refuses one that is placed twice, as placing it twice is
735    /// refused. A device of the same PART the component was placed from comes first,
736    /// because a moved or re-versioned occurrence is the likely answer. That is an
737    /// ORDER and not a guess: nothing is preselected, one is never applied on its own,
738    /// and a single candidate is offered exactly as five are.
739    fn relink_candidates(&self, id: Uuid) -> Vec<(Part, Vec<String>)> {
740        let taken: std::collections::BTreeSet<&str> = self
741            .document
742            .components
743            .iter()
744            .filter(|c| c.id != id)
745            .filter_map(|c| c.part.as_ref()?.instance.as_deref())
746            .collect();
747        let own = self
748            .document
749            .components
750            .iter()
751            .find(|c| c.id == id)
752            .and_then(|c| c.part.as_ref())
753            .map(|p| p.key.as_str());
754        let mut candidates: Vec<(Part, Vec<String>)> = self
755            .parts
756            .iter()
757            .filter(|p| {
758                p.source
759                    .instance
760                    .as_deref()
761                    .is_some_and(|instance| !taken.contains(instance))
762            })
763            .map(|p| (p.clone(), self.dropped_pins(id, &p.symbol)))
764            .collect();
765        // Stable, so the assembly's own order — a parent before its children — survives
766        // inside each half.
767        candidates.sort_by_key(|(p, _)| own.is_some_and(|key| key != p.source.key));
768        candidates
769    }
770    /// The pins of a component that carry a wire or a net label and that `symbol` has
771    /// not got, so binding the component to it would drop them.
772    ///
773    /// [`Document::relink`] takes a rename map and this editor has none to give: a
774    /// rename is evidence two saved versions of ONE part carry, and a different device
775    /// is not that. So a pin is kept when the new symbol has one by the same name and
776    /// dropped when it has not, and the cost is shown on the candidate before it is
777    /// picked rather than discovered after.
778    fn dropped_pins(&self, id: Uuid, symbol: &Symbol) -> Vec<String> {
779        let kept: std::collections::BTreeSet<&str> =
780            symbol.pins.iter().map(|p| p.number.as_str()).collect();
781        let mut pins: Vec<String> = self
782            .document
783            .wires
784            .iter()
785            .flat_map(|w| [w.start.as_ref(), w.end.as_ref()])
786            .chain(self.document.labels.iter().map(|l| l.terminal.as_ref()))
787            .flatten()
788            .filter(|t| t.component == id && !kept.contains(t.pin.as_str()))
789            .map(|t| t.pin.clone())
790            .collect();
791        pins.sort();
792        pins.dedup();
793        pins
794    }
795    /// Offer the devices an UNLINKED component could be bound to, and bind it to the one
796    /// the user picks. The resolving half of the UNLINKED lane; the operation is
797    /// [`Document::relink`] and the decision is the user's.
798    fn relink_picker(&mut self, ui: &mut egui::Ui, id: Uuid, lost: &str) {
799        ui.add_space(6.);
800        ui.label(
801            egui::RichText::new("UNLINKED")
802                .color(board_view::WARNING)
803                .strong(),
804        );
805        ui.small(format!(
806            "This component is bound to the occurrence '{lost}', which this assembly no \
807             longer offers. Pick the device it belongs to."
808        ));
809        let candidates = self.relink_candidates(id);
810        if candidates.is_empty() {
811            ui.small("No device of this assembly is free to take it.");
812            return;
813        }
814        let mut chosen = None;
815        egui::ScrollArea::vertical()
816            .id_salt(("relink", id))
817            .max_height(170.)
818            .show(ui, |ui| {
819                for (part, dropped) in &candidates {
820                    let label = part.reference.as_deref().unwrap_or(&part.name);
821                    let caption = match dropped.len() {
822                        0 => format!("{label}  ·  {}", part.source.key),
823                        n => format!("{label}  ·  {}  ·  drops {n}", part.source.key),
824                    };
825                    let hover = match dropped.is_empty() {
826                        true => format!(
827                            "Takes {}'s symbol and pads. Where this component sits, what it \
828                             is called and every wire on it stay as they are.",
829                            part.source.key
830                        ),
831                        false => format!(
832                            "{} has no {} {}, so the connections there are dropped. \
833                             Everything else stays as it is.",
834                            part.source.key,
835                            match dropped.len() {
836                                1 => "pin",
837                                _ => "pins",
838                            },
839                            dropped.join(", ")
840                        ),
841                    };
842                    if ui.button(caption).on_hover_text(hover).clicked() {
843                        chosen = Some(part.clone());
844                    }
845                }
846            });
847        if let Some(part) = chosen {
848            let mut done = Ok(());
849            self.transaction(|d| {
850                done = d.relink(
851                    id,
852                    part.source.clone(),
853                    &part.symbol,
854                    part.pads.as_ref(),
855                    &Default::default(),
856                );
857            });
858            match done {
859                Ok(()) => {
860                    self.notice = None;
861                    self.note = None;
862                    self.board_view.message = format!(
863                        "Linked to {}.",
864                        part.reference.unwrap_or(part.source.key)
865                    );
866                }
867                Err(refusal) => self.notice = Some(refusal),
868            }
869        }
870    }
871    /// Start placing one of the host's parts: the next click on the sheet puts it down
872    /// with a copy of its symbol and pads.
873    pub fn begin_placing_part(&mut self, part: Part) {
874        self.placing = Some(part.symbol.clone());
875        self.placing_part = Some(part);
876        self.tool = Tool::Place;
877        self.rotation = 0;
878    }
879    /// Place the part being placed — the assembly occurrence it is — or `symbol`
880    /// for a power symbol. An occurrence is placed once: the tool is put down after
881    /// it, and one already on the sheet, or a label already on the sheet, is refused
882    /// with a notice.
883    fn place_here(&mut self, symbol: Symbol, at: Point, rotation: u8) -> Option<Uuid> {
884        let part = self.placing_part.clone();
885        // An assembly occurrence is placed ONCE: the tool is put down after it.
886        let labelled = part.is_some();
887        let mut placed = Ok(None);
888        self.transaction(|d| {
889            placed = match part {
890                // A part is placed as the assembly component it IS: the host offers
891                // occurrences, and a card without one is not a part a sheet takes.
892                Some(part) => match part.source.instance.clone() {
893                    Some(occurrence) => d
894                        .place_assembly_component(
895                            &occurrence,
896                            part.source,
897                            part.symbol,
898                            part.pads,
899                            part.reference,
900                            at,
901                            rotation,
902                        )
903                        .map(Some),
904                    None => Err(format!(
905                        "{} is not an assembly component. Add the part to the assembly with \
906                         Add component; it is placed from there.",
907                        part.reference.as_deref().unwrap_or(&part.name)
908                    )),
909                },
910                // A symbol with no part behind it is a net flag, or nothing a sheet
911                // takes: a copy of a legacy free symbol is refused here.
912                None => d.place_power_symbol(symbol, at, rotation).map(Some),
913            }
914        });
915        // On a sheet, the harness tools place a part off the board.
916        if let Ok(Some(id)) = placed
917            && self.document.kind == DocumentKind::Sheet
918            && self.harness_tools
919            && let Some(c) = self.document.components.iter_mut().find(|c| c.id == id)
920        {
921            c.off_board = true;
922            self.document.board.placements.retain(|p| p.component != id);
923        }
924        match placed {
925            Ok(id) => {
926                if labelled {
927                    self.set_tool(Tool::Select);
928                    // A wiring diagram's devices are named, not valued, and a power
929                    // symbol (`#PWR`) names a net: neither is asked for a value.
930                    self.value_prompt = id.filter(|id| !self.wiring() && self.document.components.iter()
931                        .any(|c| c.id == *id && c.is_valued_part()));
932                }
933                id
934            }
935            Err(refusal) => {
936                self.notice = Some(refusal);
937                None
938            }
939        }
940    }
941    pub fn set_tool(&mut self, tool: Tool) {
942        // A wiring diagram's connections are dragged pin to pin; it has no nets.
943        if self.wiring()
944            && matches!(
945                tool,
946                Tool::Wire | Tool::Junction | Tool::Label | Tool::NoConnect | Tool::PowerFlag | Tool::Power
947            )
948        {
949            return;
950        }
951        self.tool = tool;
952        self.wire_start = None;
953        if tool != Tool::Place {
954            self.placing_part = None;
955        }
956    }
957    /// Why a connection may not start or end at this target: in a wiring diagram, a pin
958    /// that already has its one connection.
959    fn taken(&self, target: &ConnectionTarget) -> Option<String> {
960        let ConnectionTarget::Terminal(terminal) = target else {
961            return None;
962        };
963        let wire = self
964            .document
965            .attached_harness_wire(terminal)
966            .filter(|_| self.wiring())?;
967        Some(format!(
968            "{} already has connection {}. Each pin in a wiring diagram takes one connection.",
969            self.document.terminal_name(terminal),
970            wire.connection_id
971        ))
972    }
973    pub fn undo(&mut self) {
974        self.cancel();
975        if self.history.can_undo() {
976            self.history.undo(&mut self.document);
977            self.select_only(None);
978            self.changed = true;
979            self.note_change(None);
980        }
981    }
982    pub fn redo(&mut self) {
983        self.cancel();
984        if self.history.can_redo() {
985            self.history.redo(&mut self.document);
986            self.select_only(None);
987            self.changed = true;
988            self.note_change(None);
989        }
990    }
991    pub fn cancel(&mut self) {
992        self.terminal_drag = None;
993        if let Some((before, _, _, _)) = self.path_drag.take() {
994            self.document = before;
995        }
996        if let Some((before, _, _)) = self.drag.take() {
997            self.document = before;
998        }
999        self.wire_start = None;
1000        self.tool = Tool::Select;
1001        self.cancel_board();
1002    }
1003    fn view_switch(&mut self, ui: &mut egui::Ui) {
1004        if self.wiring() {
1005            // Without nets there is nothing to lay out on a board.
1006            ui.label(egui::RichText::new("Wiring diagram").color(accent(ui)));
1007            ui.separator();
1008            return;
1009        }
1010        self.action_buttons(ui, ActionGroup::View);
1011        ui.separator();
1012    }
1013    pub fn toolbar(&mut self, ui: &mut egui::Ui) {
1014        if self.view == View::Board {
1015            return self.board_toolbar(ui);
1016        }
1017        let wiring = self.wiring();
1018        ui.horizontal_wrapped(|ui| {
1019            self.view_switch(ui);
1020            self.action_buttons(ui, ActionGroup::Tool);
1021            ui.separator();
1022            self.action_buttons(ui, ActionGroup::History);
1023            ui.separator();
1024            self.action_buttons(ui, ActionGroup::Zoom);
1025        });
1026        ui.horizontal_wrapped(|ui| {
1027            match self.tool {
1028                Tool::Place => {
1029                    ui.label("Click the sheet to place a symbol.");
1030                }
1031                Tool::Wire => {
1032                    ui.label("Click a pin or grid point, then click to draw. A wire ends on a pin, wire or junction; Escape stops drawing.");
1033                }
1034                Tool::Label => {
1035                    ui.label("Name:");
1036                    ui.add(egui::TextEdit::singleline(&mut self.label_text).desired_width(140.));
1037                    ui.label("Click a wire or pin to place.");
1038                }
1039                Tool::Move => {
1040                    ui.label("Click the new position. Attached wires follow.");
1041                }
1042                Tool::Junction => {
1043                    ui.label("Click a crossing to connect it; click the dot again to remove it.");
1044                }
1045                Tool::NoConnect => {
1046                    ui.label("Click a pin's end to mark it no-connect; click a marked pin again to take the mark off.");
1047                }
1048                Tool::PowerFlag => {
1049                    ui.label("Click a pin, or a wire of a net, to flag it driven from off the sheet (PWR_FLAG); click a flagged pin again to take the flag off.");
1050                }
1051                Tool::Power => {
1052                    ui.label("Power net:");
1053                    for name in POWER_NETS {
1054                        if ui.selectable_label(self.power_net_text == name, name).clicked() {
1055                            self.power_net_text = name.into();
1056                        }
1057                    }
1058                    ui.add(egui::TextEdit::singleline(&mut self.power_net_text).desired_width(80.));
1059                    ui.label("Click a pin, wire or grid point to place. Every symbol of one name is one net.");
1060                }
1061                Tool::Select if wiring => {
1062                    ui.label("Drag from pin to pin to connect; each pin takes one connection. Drag devices or wire segments to adjust. Right-drag pans.");
1063                    ui.label("Stock part for new connections:");
1064                    ui.add(
1065                        egui::TextEdit::singleline(&mut self.stock_part_number)
1066                            .desired_width(140.),
1067                    );
1068                }
1069                Tool::Select => {
1070                    ui.label("Drag between terminals or junctions to connect. Drag devices or wire segments to adjust. Right-drag pans.");
1071                }
1072            }
1073            self.action_buttons(ui, ActionGroup::Context);
1074        });
1075    }
1076    fn zoom_by(&mut self, factor: f32) {
1077        zoom_at(&mut self.zoom, &mut self.pan, factor, Vec2::ZERO);
1078    }
1079    pub fn library_panel(&mut self, ui: &mut egui::Ui) {
1080        self.library_hits.clear();
1081        if self.view == View::Board {
1082            return self.board_panel(ui);
1083        }
1084        ui.add_space(8.);
1085        // The tab this pane sits under says Assembly parts, and so does every
1086        // page and the canvas's own empty state: one name for one list.
1087        ui.heading("Assembly parts");
1088        // The way to fill this list, at the top of it whether it is empty or not.
1089        // While it is empty it is the pane's only action and is drawn as one:
1090        // an empty list that only SAYS where parts come from is a dead end.
1091        if let Some(label) = self.add_part_label.clone() {
1092            let empty = self.parts.is_empty();
1093            let text = egui::RichText::new(format!("+ {label}"));
1094            let button = if empty {
1095                egui::Button::new(text.strong().color(ui.visuals().selection.stroke.color))
1096                    .fill(ui.visuals().selection.bg_fill)
1097            } else {
1098                egui::Button::new(text)
1099            };
1100            let add = ui.add_sized(
1101                Vec2::new(ui.available_width(), if empty { 30. } else { 24. }),
1102                button,
1103            );
1104            self.library_hits.push(("parts:add".into(), add.rect));
1105            if add.clicked() {
1106                self.add_part_requested = true;
1107            }
1108            ui.add_space(4.);
1109        }
1110        // Named where the parts are, because a component whose device the assembly does
1111        // not offer is a broken reference to one of them, and the inspector's picker is
1112        // no use to a user who cannot find which component to select.
1113        let flagged: Vec<Uuid> = self.unlinked().into_iter().map(|(id, _)| id).collect();
1114        let unlinked: Vec<(Uuid, String)> = flagged
1115            .into_iter()
1116            .filter_map(|id| {
1117                self.document
1118                    .components
1119                    .iter()
1120                    .find(|c| c.id == id)
1121                    .map(|c| (id, c.reference.clone()))
1122            })
1123            .collect();
1124        if !unlinked.is_empty() {
1125            ui.label(
1126                egui::RichText::new("Unlinked")
1127                    .color(board_view::WARNING)
1128                    .strong(),
1129            );
1130            ui.small("These name a device this assembly does not offer. Select one to pick its device.");
1131            let mut chosen = None;
1132            for (id, reference) in &unlinked {
1133                if ui.button(reference).clicked() {
1134                    chosen = Some(*id);
1135                }
1136            }
1137            if let Some(id) = chosen {
1138                self.select_only(Some(Selection::Component(id)));
1139            }
1140            ui.separator();
1141        }
1142        if self.parts.is_empty() {
1143            ui.label(egui::RichText::new(&self.parts_hint).weak());
1144            return;
1145        }
1146        let search = ui.add(
1147            egui::TextEdit::singleline(&mut self.search)
1148                .hint_text("Search parts…")
1149                .desired_width(f32::INFINITY),
1150        );
1151        self.library_hits.push(("parts:search".into(), search.rect));
1152        let query = self.search.to_lowercase();
1153        let on_sheet: std::collections::BTreeSet<&str> = self
1154            .document
1155            .components
1156            .iter()
1157            .map(|c| c.reference.as_str())
1158            .collect();
1159        let entries: Vec<(&Part, bool)> = self
1160            .parts
1161            .iter()
1162            .filter(|p| {
1163                format!(
1164                    "{} {} {} {}",
1165                    p.name,
1166                    p.reference.as_deref().unwrap_or(""),
1167                    p.source.key,
1168                    p.symbol.description
1169                )
1170                .to_lowercase()
1171                .contains(&query)
1172            })
1173            .map(|p| {
1174                // A component drawn before components carried an occurrence has none,
1175                // and is bound by its part's key and its label, as the host binds it
1176                // (`ecad_parts::follow_sheet`). Read by occurrence alone, such a sheet
1177                // offered every part on it as unplaced, and a click was then refused.
1178                let placed = match &p.source.instance {
1179                    Some(instance) => self.document.components.iter().any(|c| {
1180                        c.part.as_ref().is_some_and(|source| match &source.instance {
1181                            Some(bound) => bound == instance,
1182                            None => source.key == p.source.key
1183                                && p.reference.as_deref() == Some(c.reference.as_str()),
1184                        })
1185                    }),
1186                    None => p.reference.as_deref().is_some_and(|r| on_sheet.contains(r)),
1187                };
1188                (p, placed)
1189            })
1190            .collect();
1191        let (mut chosen, mut open, mut dragging) = (None, None, false);
1192        let mut hits = Vec::new();
1193        egui::ScrollArea::vertical()
1194            .id_salt(("parts", &self.search))
1195            .max_height((ui.available_height() - 55.).max(80.))
1196            .show_rows(ui, 88., entries.len(), |ui, range| {
1197                for (part, placed) in &entries[range] {
1198                    let selected =
1199                        self.tool == Tool::Place && self.placing_part.as_ref() == Some(*part);
1200                    let response = part_card(ui, part, selected, *placed);
1201                    // By label: two parts of one name (ten 10k resistors) are two
1202                    // cards, and keyed by name the last would hide the rest.
1203                    let label = part.reference.as_deref().unwrap_or(&part.name);
1204                    hits.push((format!("parts:card:{label}"), response.rect));
1205                    response.context_menu(|ui| {
1206                        menu_ui(ui);
1207                        if ui.button("Open part").clicked() {
1208                            open = Some(part.source.key.clone());
1209                            ui.close();
1210                        }
1211                    });
1212                    if *placed {
1213                        continue;
1214                    }
1215                    if response.clicked() {
1216                        chosen = Some((*part).clone());
1217                    }
1218                    if response.drag_started() {
1219                        response.dnd_set_drag_payload(LibraryPartDrag((*part).clone()));
1220                        dragging = true;
1221                    }
1222                }
1223            });
1224        self.library_hits.extend(hits);
1225        if let Some(key) = open {
1226            self.open_part_requests.push(key);
1227        }
1228        if dragging {
1229            self.cancel();
1230        }
1231        if let Some(part) = chosen {
1232            self.begin_placing_part(part);
1233        }
1234        ui.separator();
1235        // Body size, weak, as the hint over an empty list is: this is the only
1236        // place the pane says how its cards are used.
1237        ui.label(
1238            egui::RichText::new(if self.wiring() {
1239                "Drag a part onto the sheet. Right-click one to open it."
1240            } else {
1241                "Drag a part onto the sheet. Right-click one to open it.\nRight-click a terminal to add a net flag."
1242            })
1243            .weak(),
1244        );
1245    }
1246    /// The whole inspector scrolls: a selected component's properties sit
1247    /// ABOVE the connection / net lists, and in a short pane they overflowed
1248    /// with only the list below them scrollable. Inside this area the inner
1249    /// lists grow to their content and scroll with everything else.
1250    pub fn inspector(&mut self, ui: &mut egui::Ui) {
1251        egui::ScrollArea::vertical()
1252            .id_salt("ecad-inspector")
1253            .auto_shrink([false, false])
1254            .show(ui, |ui| self.inspector_body(ui));
1255    }
1256
1257    fn inspector_body(&mut self, ui: &mut egui::Ui) {
1258        if self.view == View::Board {
1259            return self.board_inspector(ui);
1260        }
1261        self.properties_hits.begin(ui.ctx());
1262        ui.add_space(12.);
1263        ui.heading("Properties");
1264        ui.add_space(12.);
1265        if let Some(Selection::Component(id)) = self.selected {
1266            if let Some(c) = self
1267                .document
1268                .components
1269                .iter()
1270                .find(|c| c.id == id)
1271                .cloned()
1272            {
1273                // A placed component's symbol is a copy of its part's, and the host
1274                // refreshes it from the part: it is edited on the part, never here.
1275                ui.label(egui::RichText::new(&c.symbol.library_id).color(accent(ui)));
1276                if !c.gates.is_empty() {
1277                    let names: Vec<String> = c.gates.iter().map(|g| c.gate_reference(g.gate)).collect();
1278                    ui.small(format!(
1279                        "One part in {} gates, {}: drag a gate to move it on its own, or \
1280                         Shift-drag to move the whole part. They share one reference, one \
1281                         footprint and one place on the board.",
1282                        names.len(),
1283                        names.join(", ")
1284                    ));
1285                }
1286                let mut reference = c.reference.clone();
1287                let mut value = c.value.clone();
1288                ui.label("Reference");
1289                // A label the host keeps is shown, never edited here.
1290                let host_label = self.labels_from_host.clone().filter(|_| c.part.is_some());
1291                let r = match &host_label {
1292                    Some(hint) => {
1293                        ui.label(egui::RichText::new(&reference).strong());
1294                        ui.small(hint);
1295                        false
1296                    }
1297                    None => ui.text_edit_singleline(&mut reference).changed(),
1298                };
1299                ui.label("Value");
1300                let v = ui.add(egui::TextEdit::singleline(&mut value).hint_text("10k, 100nF, LM358"));
1301                self.properties_hits.mark("value", &v);
1302                if self.value_prompt.take() == Some(id) {
1303                    v.request_focus();
1304                    let mut state = egui::TextEdit::load_state(ui.ctx(), v.id).unwrap_or_default();
1305                    let end = egui::text::CCursor::new(value.chars().count());
1306                    state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(0), end)));
1307                    egui::TextEdit::store_state(ui.ctx(), v.id, state);
1308                }
1309                let default = c.symbol.default_value();
1310                if !self.wiring() && c.is_valued_part() {
1311                    if c.value == default {
1312                        ui.small(egui::RichText::new(
1313                            "The symbol's own value. Type this part's, such as 10k: \
1314                             the BOM groups by it, and the netlist and pick-and-place write it.",
1315                        ).weak());
1316                    } else if !c.value.trim().is_empty() {
1317                        // The value typed here, offered to the parts placed from the same
1318                        // symbol that still read its value: four resistors are one edit.
1319                        let siblings = self.document.unvalued_siblings(id);
1320                        if !siblings.is_empty() {
1321                            let names: Vec<&str> = self.document.components.iter()
1322                                .filter(|o| siblings.contains(&o.id)).map(|o| o.reference.as_str()).collect();
1323                            let mut shown = names.iter().take(4).copied().collect::<Vec<_>>().join(", ");
1324                            if names.len() > 4 {
1325                                shown += &format!(" and {} more", names.len() - 4);
1326                            }
1327                            let b = ui.button(format!("{} for {shown} too", c.value)).on_hover_text(format!(
1328                                "{} placed from {} still read its value '{default}'. Give them '{}' as well, in one undo step.",
1329                                if names.len() == 1 { "This part is" } else { "These parts are" },
1330                                c.symbol.library_id, c.value
1331                            ));
1332                            self.properties_hits.mark("value_siblings", &b);
1333                            if b.clicked() {
1334                                let given = c.value.clone();
1335                                self.transaction(|d| {
1336                                    d.set_value(&siblings, &given);
1337                                });
1338                            }
1339                        }
1340                    }
1341                }
1342                if (r || v.changed())
1343                    && !reference.trim().is_empty()
1344                    && !self
1345                        .document
1346                        .components
1347                        .iter()
1348                        .any(|c| c.id != id && c.reference == reference)
1349                {
1350                    self.transaction_as(Some(format!("component:{id}:text")), |d| {
1351                        let c = d.components.iter_mut().find(|c| c.id == id).unwrap();
1352                        c.reference = reference;
1353                        c.value = value;
1354                    });
1355                }
1356                if ui.button("Move").clicked() {
1357                    self.set_tool(Tool::Move);
1358                }
1359                if ui.button("Rotate 90°").clicked() {
1360                    self.rotate();
1361                }
1362                if ui.button("Duplicate").clicked() {
1363                    self.duplicate();
1364                }
1365                ui.small("Connected wires follow moves and rotation.");
1366                self.pin_functions_table(ui, &c);
1367                if let Some(part) = &c.part {
1368                    ui.separator();
1369                    ui.label("Part");
1370                    ui.small(&part.key);
1371                    if ui
1372                        .button("Open part")
1373                        .on_hover_text("Its symbol and pads are edited on the part.")
1374                        .clicked()
1375                    {
1376                        self.open_part_requests.push(part.key.clone());
1377                    }
1378                    if let Some(lost) = self.unlinked_device(&c).map(str::to_owned) {
1379                        self.relink_picker(ui, id, &lost);
1380                    }
1381                }
1382                ui.separator();
1383                ui.label("Pins");
1384                for pin in &c.symbol.pins {
1385                    ui.small(format!("{} · {}", pin.number, pin.electrical_type));
1386                }
1387            }
1388        } else if let Some(Selection::Wire(id)) = self.selected {
1389            if self.wiring()
1390                && let Some(w) = self.document.wires.iter().find(|w| w.id == id).cloned()
1391            {
1392                let pin = |t: &Option<Terminal>| {
1393                    t.as_ref()
1394                        .map_or("?".into(), |t| self.document.terminal_name(t))
1395                };
1396                ui.label(
1397                    egui::RichText::new(format!("{} to {}", pin(&w.start), pin(&w.end)))
1398                        .color(accent(ui)),
1399                );
1400                let mut connection_id = w.connection_id.clone();
1401                let mut stock_part_number = w.stock_part_number.clone();
1402                ui.label("Connection ID");
1403                let c = ui.text_edit_singleline(&mut connection_id);
1404                ui.label("Stock part number");
1405                let s = ui.text_edit_singleline(&mut stock_part_number);
1406                if (c.changed() || s.changed())
1407                    && !connection_id.trim().is_empty()
1408                    && !self
1409                        .document
1410                        .wires
1411                        .iter()
1412                        .any(|w| w.id != id && w.connection_id == connection_id)
1413                {
1414                    self.transaction_as(Some(format!("wire:{id}:text")), |d| {
1415                        let w = d.wires.iter_mut().find(|w| w.id == id).unwrap();
1416                        w.connection_id = connection_id;
1417                        w.stock_part_number = stock_part_number;
1418                    });
1419                }
1420                ui.separator();
1421            }
1422            ui.label("Connection path");
1423            ui.small("Drag a segment or its square handle to move it. Endpoints stay attached.");
1424            if ui.button("Add jog").clicked() {
1425                let index = self.selected_segment;
1426                self.transaction(|d| {
1427                    if let Some(w) = d.wires.iter_mut().find(|w| w.id == id) {
1428                        w.add_jog(index);
1429                    }
1430                });
1431                self.selected_segment = index + 2;
1432            }
1433            let can_remove = self
1434                .document
1435                .wires
1436                .iter()
1437                .find(|w| w.id == id)
1438                .is_some_and(|w| w.removable_jog(self.selected_segment).is_some());
1439            if ui
1440                .add_enabled(can_remove, egui::Button::new("Remove jog"))
1441                .clicked()
1442            {
1443                let index = self.selected_segment;
1444                self.transaction(|d| {
1445                    if let Some(w) = d.wires.iter_mut().find(|w| w.id == id) {
1446                        w.remove_jog(index);
1447                    }
1448                });
1449                self.selected_segment = 0;
1450            }
1451        } else if let Some(Selection::Label(id)) = self.selected {
1452            if let Some(label) = self.document.labels.iter().find(|l| l.id == id) {
1453                let mut name = label.name.clone();
1454                ui.label("Net name");
1455                if ui.text_edit_singleline(&mut name).changed() && !name.trim().is_empty() {
1456                    self.transaction_as(Some(format!("label:{id}:name")), |d| {
1457                        d.labels.iter_mut().find(|l| l.id == id).unwrap().name = name.trim().into()
1458                    });
1459                }
1460                if ui.button("Move").clicked() {
1461                    self.set_tool(Tool::Move);
1462                }
1463                if ui.button("Rotate 90°").clicked() {
1464                    self.rotate();
1465                }
1466                ui.small("Drag the body to move. Drag from the tip to draw a wire.");
1467            }
1468        } else {
1469            ui.label("Select a device or connection to edit it.");
1470            if !self.wiring() {
1471                self.values_table(ui);
1472            }
1473        }
1474        // A part of a sheet is on the board or off it; a drag across the board
1475        // zone's edge moves it too.
1476        if let Some(board) = self.selected_zone().map(str::to_owned) {
1477            ui.label(format!(
1478                "Part of the board {board}, a document of its own: read-only here. A harness wire may end on a point \
1479                 {board} declares."
1480            ));
1481            if ui.button(format!("Edit {board}")).clicked() {
1482                self.enter_selected_zone();
1483            }
1484        }
1485        if let Some(off) = self.selected_off_board() {
1486            ui.label(if off { "Off the board: harness wires only." } else { "On the board." });
1487            if ui.button(if off { "Move onto the board" } else { "Take off the board" }).clicked() {
1488                self.set_selected_off_board(!off);
1489            }
1490        }
1491        if self.selected.is_some() && ui.button("Delete selection").clicked() {
1492            self.delete();
1493        }
1494        ui.add_space(16.);
1495        ui.separator();
1496        if self.wiring() {
1497            ui.heading("Connections");
1498            let connections = self.document.connections();
1499            ui.label(format!(
1500                "{} · {}",
1501                count(self.document.components.len(), "component", "components"),
1502                count(connections.len(), "connection", "connections")
1503            ));
1504            egui::ScrollArea::vertical()
1505                .id_salt("connections")
1506                .show(ui, |ui| {
1507                    for c in &connections {
1508                        ui.small(format!(
1509                            "{}  {}.{} to {}.{}  {}",
1510                            c.connection_id,
1511                            c.from_ref_des,
1512                            c.from_port,
1513                            c.to_ref_des,
1514                            c.to_port,
1515                            c.stock_part_number
1516                        ));
1517                    }
1518                });
1519            return;
1520        }
1521        ui.heading("Connectivity");
1522        let netlist = self.document.netlist();
1523        ui.label(format!(
1524            "{} · {}",
1525            count(self.document.components.len(), "component", "components"),
1526            count(netlist.nets.len(), "net", "nets")
1527        ));
1528        self.erc_section(ui);
1529        ui.add_space(8.);
1530        ui.label(egui::RichText::new("Nets").strong());
1531        egui::ScrollArea::vertical().id_salt("nets").show(ui, |ui| {
1532            for net in &netlist.nets {
1533                ui.collapsing(format!("{}  ·  {}", net.name, count(net.pins.len(), "pin", "pins")), |ui| {
1534                    for pin in &net.pins {
1535                        ui.small(format!("{}.{}", pin.reference, pin.number));
1536                    }
1537                });
1538            }
1539        });
1540    }
1541    /// Every part's value in one table, as KiCad's Symbol Fields Table gives them:
1542    /// a part the host seats on its own (Add Component on the PCB workbench) is never
1543    /// placed from the palette, so this is where its value is typed, and four
1544    /// resistors are four fields in a column rather than four selections (the third
1545    /// eCAD audit, B3). A value still the symbol's own is drawn weak.
1546    fn values_table(&mut self, ui: &mut egui::Ui) {
1547        let mut rows: Vec<(Uuid, String, String, bool)> = self
1548            .document
1549            .components
1550            .iter()
1551            .filter(|c| c.is_valued_part())
1552            .map(|c| (c.id, c.reference.clone(), c.value.clone(), c.value == c.symbol.default_value()))
1553            .collect();
1554        if rows.is_empty() {
1555            return;
1556        }
1557        rows.sort_by(|a, b| brep_ecad_core::footprint::natural_cmp(&a.1, &b.1));
1558        let unvalued = rows.iter().filter(|r| r.3).count();
1559        ui.add_space(12.);
1560        ui.label(egui::RichText::new("Values").strong());
1561        ui.small(match unvalued {
1562            0 => "Each part has its own value.".to_owned(),
1563            n => format!(
1564                "{n} of {} have no value of their own yet (grey). Type each part's, such as \
1565                 10k: the BOM groups by it, and the netlist and pick-and-place write it.",
1566                rows.len()
1567            ),
1568        });
1569        let weak = ui.visuals().weak_text_color();
1570        egui::ScrollArea::vertical()
1571            .id_salt("values")
1572            .max_height(260.)
1573            .show(ui, |ui| {
1574                egui::Grid::new("values").num_columns(2).striped(true).show(ui, |ui| {
1575                    for (id, reference, mut value, default) in rows {
1576                        ui.label(&reference);
1577                        let mut field =
1578                            egui::TextEdit::singleline(&mut value).desired_width(120.).hint_text("10k");
1579                        if default {
1580                            field = field.text_color(weak);
1581                        }
1582                        let field = ui.add(field);
1583                        self.properties_hits.mark(format!("value:{reference}"), &field);
1584                        if field.changed() {
1585                            self.transaction_as(Some(format!("component:{id}:text")), |d| {
1586                                d.set_value(&[id], &value);
1587                            });
1588                        }
1589                        ui.end_row();
1590                    }
1591                });
1592            });
1593    }
1594    fn rotate(&mut self) {
1595        if self.tool == Tool::Place {
1596            self.rotation = (self.rotation + 1) % 4;
1597        } else if self.selected_count() > 1 {
1598            self.rotate_group();
1599        } else if let Some(Selection::Component(id)) = self.selected {
1600            let gate = self.selected_gate();
1601            self.transaction(|d| Self::move_component(d, id, gate, None, Some(1)));
1602        } else if let Some(Selection::Label(id)) = self.selected {
1603            self.transaction(|d| {
1604                if let Some(l) = d.labels.iter_mut().find(|l| l.id == id) {
1605                    l.rotation = (l.rotation + 1) % 4;
1606                }
1607            });
1608        }
1609    }
1610    /// Move component `id` to `at` and turn it by `turn` more quarter turns,
1611    /// or only the one gate `gate` of it; `None` leaves that alone.
1612    fn move_component(d: &mut Document, id: Uuid, gate: Option<u32>, at: Option<Point>, turn: Option<u8>) {
1613        let Some(c) = d.components.iter().find(|c| c.id == id) else {
1614            return;
1615        };
1616        let (old_at, old_rotation) = match gate.and_then(|g| c.gate(g)) {
1617            Some(g) => (g.at, g.rotation),
1618            None => (c.at, c.rotation),
1619        };
1620        let at = at.unwrap_or(old_at);
1621        let rotation = (old_rotation + turn.unwrap_or(0)) % 4;
1622        match gate {
1623            Some(gate) => d.transform_gate(id, gate, at, rotation),
1624            None => d.transform_component(id, at, rotation),
1625        }
1626    }
1627    /// Place another of the selected component. For a component placed from a part
1628    /// that is the next one of that part the host offers that is not on the sheet yet.
1629    fn duplicate(&mut self) {
1630        let Some(Selection::Component(id)) = self.selected else {
1631            return;
1632        };
1633        let Some(c) = self.document.components.iter().find(|c| c.id == id) else {
1634            return;
1635        };
1636        let rotation = c.rotation;
1637        let Some(source) = &c.part else {
1638            self.placing = Some(c.symbol.clone());
1639            self.set_tool(Tool::Place);
1640            self.rotation = rotation;
1641            return;
1642        };
1643        let on_sheet = |r: &String| self.document.components.iter().any(|c| &c.reference == r);
1644        let next = self
1645            .parts
1646            .iter()
1647            .find(|p| p.source.key == source.key && !p.reference.as_ref().is_some_and(on_sheet))
1648            .cloned();
1649        match next {
1650            Some(part) => {
1651                self.begin_placing_part(part);
1652                self.rotation = rotation;
1653            }
1654            // Every occurrence of the part is on the sheet, so another footprint
1655            // means another component: ask the host to add one to the assembly.
1656            // Placement is armed when the host offers it (`arm_pending_duplicate`).
1657            None => {
1658                let key = source.key.clone();
1659                self.note = Some(format!("Adding another {} to the assembly\u{2026}", c.value));
1660                self.pending_duplicate = Some((key.clone(), rotation));
1661                self.duplicate_requests.push(key);
1662            }
1663        }
1664    }
1665    /// Arm placement of the occurrence a **Duplicate** asked the host for, once the
1666    /// host offers one of that part that is not on the sheet yet. Called by the host
1667    /// after it refreshes [`Editor::parts`]; returns whether placement was armed.
1668    pub fn arm_pending_duplicate(&mut self) -> bool {
1669        let Some((key, rotation)) = self.pending_duplicate.clone() else {
1670            return false;
1671        };
1672        let on_sheet = |r: &String| self.document.components.iter().any(|c| &c.reference == r);
1673        let bound: std::collections::BTreeSet<&str> = self
1674            .document
1675            .components
1676            .iter()
1677            .filter_map(|c| c.part.as_ref()?.instance.as_deref())
1678            .collect();
1679        let next = self
1680            .parts
1681            .iter()
1682            .find(|p| {
1683                p.source.key == key
1684                    && p.source.instance.as_deref().is_some_and(|i| !bound.contains(i))
1685                    && !p.reference.as_ref().is_some_and(on_sheet)
1686            })
1687            .cloned();
1688        let Some(part) = next else {
1689            return false;
1690        };
1691        self.pending_duplicate = None;
1692        // On the PCB's sheet a part with pads is seated by the board the frame
1693        // it is offered (`follow_parts`): arming it too would place the
1694        // occurrence twice, and the second would be refused.
1695        if part.pads.is_some() && !self.wiring() {
1696            self.note = Some(format!(
1697                "{} added to the assembly; the board seats it.",
1698                part.reference.as_deref().unwrap_or(&part.name)
1699            ));
1700            return false;
1701        }
1702        self.begin_placing_part(part);
1703        self.rotation = rotation;
1704        true
1705    }
1706    /// Forget a duplicate the host could not answer (a part it cannot add another
1707    /// of), so the next offer does not arm a placement nobody asked for.
1708    pub fn cancel_pending_duplicate(&mut self) {
1709        self.pending_duplicate = None;
1710    }
1711    /// Every selected item, oldest first and the primary last.
1712    pub fn selected_items(&self) -> Vec<Selection> {
1713        let mut all = if self.selected.is_some() && self.selected == self.also_primary { self.also.clone() } else { vec![] };
1714        all.extend(self.selected);
1715        all
1716    }
1717    /// How many items are selected.
1718    pub fn selected_count(&self) -> usize {
1719        self.selected_items().len()
1720    }
1721    fn is_selected(&self, item: Selection) -> bool {
1722        self.selected_items().contains(&item)
1723    }
1724    fn set_selection(&mut self, items: Vec<Selection>) {
1725        let mut items = items;
1726        self.selected = items.pop();
1727        self.also = items;
1728        self.also_primary = self.selected;
1729        self.selected_gate = None;
1730    }
1731    /// Select `item` alone (or nothing).
1732    fn select_only(&mut self, item: Option<Selection>) {
1733        self.selected = item;
1734        self.also.clear();
1735        self.also_primary = None;
1736    }
1737    /// Add `item` as the primary (one already selected becomes primary).
1738    fn add_selected(&mut self, item: Selection) {
1739        let mut items = self.selected_items();
1740        items.retain(|i| *i != item);
1741        items.push(item);
1742        self.set_selection(items);
1743    }
1744    /// Ctrl/Cmd+click: add `item`, or take it out when it is selected.
1745    fn toggle_selected(&mut self, item: Selection) {
1746        let mut items = self.selected_items();
1747        if items.contains(&item) {
1748            items.retain(|i| *i != item);
1749        } else {
1750            items.push(item);
1751        }
1752        self.set_selection(items);
1753    }
1754    /// Ctrl/Cmd+A: select every item of the sheet.
1755    pub(crate) fn select_all(&mut self) {
1756        let all = self.all_items();
1757        self.set_selection(all);
1758    }
1759    /// Every item of the sheet: parts, wires, labels a click can pick, junctions.
1760    fn all_items(&self) -> Vec<Selection> {
1761        let d = &self.document;
1762        d.components.iter().map(|c| Selection::Component(c.id))
1763            .chain(d.wires.iter().map(|w| Selection::Wire(w.id)))
1764            .chain(d.labels.iter().filter(|l| !self.names_power_symbol(l)).map(|l| Selection::Label(l.id)))
1765            .chain(d.junctions.iter().map(|p| Selection::Junction(*p)))
1766            .collect()
1767    }
1768    /// The points an item covers on the sheet: a part's origin, gates and pin
1769    /// ends, a wire's corners, a label's point, a junction.
1770    fn item_points(&self, item: Selection) -> Vec<Point> {
1771        let d = &self.document;
1772        match item {
1773            Selection::Component(id) => d.components.iter().find(|c| c.id == id).map(|c| {
1774                c.symbol.pins.iter().map(|p| c.pin_at(p)).chain(std::iter::once(c.at)).chain(c.gates.iter().map(|g| g.at)).collect()
1775            }).unwrap_or_default(),
1776            Selection::Wire(id) => d.wires.iter().find(|w| w.id == id).map(|w| w.points()).unwrap_or_default(),
1777            Selection::Label(id) => d.labels.iter().find(|l| l.id == id).map(|l| vec![l.at]).unwrap_or_default(),
1778            Selection::Junction(p) => vec![p],
1779        }
1780    }
1781    /// Apply a box drawn over `area` (screen): left to right takes the items
1782    /// wholly inside it, right to left those it touches.
1783    fn box_select(&mut self, area: Rect, crossing: bool, mode: footprint_editor::BoxMode, rect: Rect) {
1784        use footprint_editor::BoxMode;
1785        let caught: Vec<Selection> = self.all_items().into_iter().filter(|item| {
1786            let points: Vec<Pos2> = self.item_points(*item).into_iter().map(|p| self.screen(p, rect)).collect();
1787            !points.is_empty() && if crossing {
1788                area.intersects(Rect::from_points(&points).expand(1.))
1789            } else {
1790                points.iter().all(|p| area.contains(*p))
1791            }
1792        }).collect();
1793        let mut items = match mode {
1794            BoxMode::Replace => vec![],
1795            _ => self.selected_items(),
1796        };
1797        for item in caught {
1798            items.retain(|i| *i != item);
1799            if mode != BoxMode::Remove {
1800                items.push(item);
1801            }
1802        }
1803        self.set_selection(items);
1804    }
1805    /// Move every selected item by `delta`: parts (their wires and flags
1806    /// follow), then the free ends and corners of selected wires, free labels
1807    /// and junctions.
1808    fn move_group(d: &mut Document, items: &[Selection], delta: Point) {
1809        Self::transform_group(d, items, |p| p.offset(delta), 0);
1810    }
1811    /// Apply `map` to every selected item's position, turning parts and labels
1812    /// `turn` more quarter turns, as ONE rigid motion: the selected parts and
1813    /// their gates; a wire whose ends are all on moved parts, or free and the
1814    /// wire selected, whole (corners included, once); a wire with one end on a
1815    /// moved part and the other held, by that end (it follows, as it does for
1816    /// one part); the flags on moved pins; selected free labels and junctions.
1817    fn transform_group(d: &mut Document, items: &[Selection], map: impl Fn(Point) -> Point, turn: u8) {
1818        let moved: Vec<Uuid> = items.iter().filter_map(|i| match i { Selection::Component(id) => Some(*id), _ => None }).collect();
1819        // Where the moved parts' pins are before the move: a wire end left
1820        // unbound on one is on that pin, as a part's own move reads it.
1821        let moved_pins: Vec<Point> = d.components.iter().filter(|c| moved.contains(&c.id))
1822            .flat_map(|c| c.symbol.pins.iter().map(|p| c.pin_at(p)).collect::<Vec<_>>()).collect();
1823        for c in d.components.iter_mut().filter(|c| moved.contains(&c.id)) {
1824            c.at = map(c.at);
1825            c.rotation = (c.rotation + turn) % 4;
1826            for g in &mut c.gates {
1827                g.at = map(g.at);
1828                g.rotation = (g.rotation + turn) % 4;
1829            }
1830        }
1831        for w in &mut d.wires {
1832            let selected = items.contains(&Selection::Wire(w.id));
1833            let on_moved = |t: &Option<Terminal>, p: Point| match t {
1834                Some(t) => moved.contains(&t.component),
1835                None => moved_pins.contains(&p),
1836            };
1837            // An end goes with the group when it is on a moved part, or free on a selected wire.
1838            let goes = |t: &Option<Terminal>, p: Point| on_moved(t, p) || selected && t.is_none();
1839            match (goes(&w.start, w.a), goes(&w.end, w.b)) {
1840                (true, true) => {
1841                    w.a = map(w.a);
1842                    w.b = map(w.b);
1843                    for p in &mut w.bends {
1844                        *p = map(*p);
1845                    }
1846                }
1847                (true, false) => {
1848                    let (a, b) = (map(w.a), w.b);
1849                    w.follow(a, b);
1850                }
1851                (false, true) => {
1852                    let (a, b) = (w.a, map(w.b));
1853                    w.follow(a, b);
1854                }
1855                (false, false) => {}
1856            }
1857        }
1858        for l in &mut d.labels {
1859            if l.terminal.as_ref().is_some_and(|t| moved.contains(&t.component)) {
1860                l.at = map(l.at);
1861                l.rotation = (l.rotation + turn) % 4;
1862            }
1863        }
1864        for item in items {
1865            match *item {
1866                Selection::Label(id) => {
1867                    let free = d.labels.iter().find(|l| l.id == id).filter(|l| l.terminal.as_ref().is_none_or(|t| !moved.contains(&t.component)));
1868                    if let Some((at, rotation)) = free.map(|l| (map(l.at), (l.rotation + turn) % 4)) {
1869                        d.transform_label(id, at, rotation);
1870                    }
1871                }
1872                Selection::Junction(p) => {
1873                    if d.junctions.remove(&p) {
1874                        d.junctions.insert(map(p));
1875                    }
1876                }
1877                Selection::Component(_) | Selection::Wire(_) => {}
1878            }
1879        }
1880    }
1881    /// R with several items selected: turn them all a quarter turn about the
1882    /// grid point nearest the middle of their extent, one undo step.
1883    fn rotate_group(&mut self) {
1884        let items = self.selected_items();
1885        let points: Vec<Point> = items.iter().flat_map(|i| self.item_points(*i)).collect();
1886        let (Some(x0), Some(x1), Some(y0), Some(y1)) = (
1887            points.iter().map(|p| p.x).min(), points.iter().map(|p| p.x).max(),
1888            points.iter().map(|p| p.y).min(), points.iter().map(|p| p.y).max(),
1889        ) else { return };
1890        let about = Point::new(((i64::from(x0) + i64::from(x1)) / 2) as i32, ((i64::from(y0) + i64::from(y1)) / 2) as i32).snapped();
1891        let turned = |p: Point| Point::new(p.x - about.x, p.y - about.y).rotate(1).offset(about);
1892        let selection = self.selected_items();
1893        self.transaction(|d| Self::transform_group(d, &items, turned, 1));
1894        self.set_selection(selection);
1895    }
1896    fn delete(&mut self) {
1897        if self.selected_count() > 1 {
1898            let items = self.selected_items();
1899            self.select_only(None);
1900            self.transaction(|d| {
1901                for s in items {
1902                    match s {
1903                        Selection::Component(id) => d.delete_component(id),
1904                        Selection::Wire(id) => d.wires.retain(|w| w.id != id),
1905                        Selection::Label(id) => d.labels.retain(|l| l.id != id),
1906                        Selection::Junction(p) => {
1907                            d.junctions.remove(&p);
1908                        }
1909                    }
1910                }
1911            });
1912            return;
1913        }
1914        self.also.clear();
1915        if let Some(s) = self.selected.take() {
1916            self.transaction(|d| match s {
1917                Selection::Component(id) => d.delete_component(id),
1918                Selection::Wire(id) => d.wires.retain(|w| w.id != id),
1919                Selection::Label(id) => d.labels.retain(|l| l.id != id),
1920                Selection::Junction(p) => {
1921                    d.junctions.remove(&p);
1922                }
1923            });
1924        }
1925    }
1926    fn fit(&mut self, size: Vec2) {
1927        let mut points: Vec<_> = self
1928            .document
1929            .components
1930            .iter()
1931            .flat_map(|c| {
1932                c.symbol
1933                    .pins
1934                    .iter()
1935                    .map(|p| c.pin_at(p))
1936                    .chain(std::iter::once(c.at))
1937                    .chain(c.gates.iter().map(|g| g.at))
1938            })
1939            .collect();
1940        points.extend(self.document.wires.iter().flat_map(|w| w.points()));
1941        points.extend(self.document.labels.iter().map(|l| l.at));
1942        if points.is_empty() {
1943            self.pan = Vec2::ZERO;
1944            self.zoom = 0.012;
1945            return;
1946        }
1947        let min = Point::new(
1948            points.iter().map(|p| p.x).min().unwrap() - 10000,
1949            points.iter().map(|p| p.y).min().unwrap() - 10000,
1950        );
1951        // The right side also holds each part's reference and value.
1952        let max = Point::new(
1953            points.iter().map(|p| p.x).max().unwrap() + 17780,
1954            points.iter().map(|p| p.y).max().unwrap() + 10000,
1955        );
1956        self.zoom = valid_zoom(
1957            (size.x / (max.x - min.x) as f32)
1958                .min(size.y / (max.y - min.y) as f32)
1959                .min(0.03),
1960            self.zoom,
1961        );
1962        self.pan = -Vec2::new((min.x + max.x) as f32 / 2., (min.y + max.y) as f32 / 2.) * self.zoom;
1963    }
1964    fn screen(&self, p: Point, rect: Rect) -> Pos2 {
1965        rect.center() + self.pan + Vec2::new(p.x as f32, p.y as f32) * self.zoom
1966    }
1967    fn world(&self, p: Pos2, rect: Rect) -> Point {
1968        let v = (p - rect.center() - self.pan) / self.zoom;
1969        Point::new(v.x.round() as i32, v.y.round() as i32)
1970    }
1971    fn snap(&self, p: Pos2, rect: Rect) -> Point {
1972        let mut candidates: Vec<_> = self
1973            .document
1974            .components
1975            .iter()
1976            .flat_map(|c| c.symbol.pins.iter().map(|pin| c.pin_at(pin)))
1977            .collect();
1978        candidates.extend(self.document.wires.iter().flat_map(|w| w.points()));
1979        candidates.extend(self.document.junctions.iter().copied());
1980        candidates
1981            .into_iter()
1982            .filter_map(|q| {
1983                let d = self.screen(q, rect).distance(p);
1984                (d < 10.).then_some((q, d))
1985            })
1986            .min_by(|a, b| a.1.total_cmp(&b.1))
1987            .map_or_else(|| self.world(p, rect).snapped(), |v| v.0)
1988    }
1989    /// Whether `l` is the net name a power symbol gives its own pin. The symbol
1990    /// draws that name itself, so the flag is neither drawn nor picked: a click
1991    /// there picks the symbol.
1992    fn names_power_symbol(&self, l: &Label) -> bool {
1993        l.terminal.as_ref().is_some_and(|t| {
1994            self.document
1995                .components
1996                .iter()
1997                .any(|c| c.id == t.component && c.symbol.power_net.is_some())
1998        })
1999    }
2000    fn hit(&self, p: Pos2, rect: Rect, ctx: &egui::Context) -> Option<Selection> {
2001        for l in self.document.labels.iter().rev() {
2002            if self.names_power_symbol(l) {
2003                continue;
2004            }
2005            let tip = self.screen(l.at, rect);
2006            if l.flag || l.terminal.is_some() {
2007                let (_, outline, _) =
2008                    net_flag_layout(ctx, &l.name, tip, self.zoom / 0.012, l.rotation);
2009                if Rect::from_points(&outline).contains(p) {
2010                    return Some(Selection::Label(l.id));
2011                }
2012            } else if tip.distance(p) < 14. {
2013                return Some(Selection::Label(l.id));
2014            }
2015        }
2016        for j in &self.document.junctions {
2017            if self.screen(*j, rect).distance(p) < 7. {
2018                return Some(Selection::Junction(*j));
2019            }
2020        }
2021        for c in self.document.components.iter().rev() {
2022            if self
2023                .drawn_gates(c, rect)
2024                .iter()
2025                .any(|(_, bounds)| bounds.expand(7.).contains(p))
2026            {
2027                return Some(Selection::Component(c.id));
2028            }
2029        }
2030        self.hit_segment(p, rect).map(|(id, _)| Selection::Wire(id))
2031    }
2032    fn hit_target(&self, p: Pos2, rect: Rect) -> Option<ConnectionTarget> {
2033        if let Some(t) = self.hit_terminal(p, rect) {
2034            return Some(ConnectionTarget::Terminal(t));
2035        }
2036        self.document
2037            .junctions
2038            .iter()
2039            .chain(self.document.labels.iter().map(|l| &l.at))
2040            .filter_map(|q| {
2041                let distance = self.screen(*q, rect).distance(p);
2042                (distance <= 12.).then_some((*q, distance))
2043            })
2044            .min_by(|a, b| a.1.total_cmp(&b.1))
2045            .map(|(q, _)| ConnectionTarget::Junction(q))
2046    }
2047    /// Whether a label was placed since the last call. A click on the sheet takes
2048    /// the keyboard from the host's name field, so without this the next name typed
2049    /// went to the canvas and the next click silently repeated the last name (the
2050    /// 2026-09-23 audit's VCC placed twice, shorting GND). The host answers by
2051    /// focusing the field again with its text selected: typing replaces the name,
2052    /// another click repeats it.
2053    pub fn take_label_placed(&mut self) -> bool {
2054        std::mem::take(&mut self.label_placed)
2055    }
2056    /// What a label named `name` at `at` would join, when it joins two nets that
2057    /// were already distinct and each reach a pin: the one under it and the one the
2058    /// name already names. The line says so, pins and all, because joining by name
2059    /// is the label's job and a mistyped or repeated name does it just as quietly.
2060    ///
2061    /// `true` with it is a WARNING: two nets that each already had a NAME are now
2062    /// one, which is what a mistyped name does (VCC on the GND net). Joining a
2063    /// pin or an unnamed net to the net a name names is what a label is placed
2064    /// FOR, and says so without the alarm: the 2026-09-23 re-audit counted 12 of
2065    /// its 18 intended placements drawing the red line.
2066    fn label_joins(&self, what: &str, name: &str, at: Point) -> Option<(String, bool)> {
2067        let before = self.document.netlist();
2068        let mut after = self.document.clone();
2069        after.labels.push(Label {
2070            flag: false,
2071            rotation: 0,
2072            terminal: None,
2073            id: Uuid::nil(),
2074            name: name.to_owned(),
2075            at,
2076        });
2077        let after = after.netlist();
2078        let net = after.nets.iter().find(|n| n.points.contains(&at))?;
2079        let joined: Vec<_> = before
2080            .nets
2081            .iter()
2082            .filter(|b| {
2083                b.pins.iter().any(|p| {
2084                    net.pins
2085                        .iter()
2086                        .any(|q| q.component_id == p.component_id && q.number == p.number)
2087                })
2088            })
2089            .collect();
2090        if joined.len() < 2 {
2091            return None;
2092        }
2093        let named = joined.iter().filter(|n| !n.labels.is_empty()).count();
2094        let describe = |n: &brep_ecad_core::Net| {
2095            let mut pins: Vec<_> = n
2096                .pins
2097                .iter()
2098                .take(3)
2099                .map(|p| format!("{}.{}", p.reference, p.number))
2100                .collect();
2101            if n.pins.len() > 3 {
2102                pins.push("…".into());
2103            }
2104            format!("{} ({})", n.name, pins.join(", "))
2105        };
2106        let nets = joined.iter().map(|n| describe(n)).collect::<Vec<_>>().join(" and ");
2107        Some(if named >= 2 {
2108            (
2109                format!(
2110                    "{what} {name} joined {nets}, two named nets, into one net of {} pins. Undo if that was not meant.",
2111                    net.pins.len()
2112                ),
2113                true,
2114            )
2115        } else {
2116            (format!("{what} {name} joined {nets} into one net of {} pins.", net.pins.len()), false)
2117        })
2118    }
2119    /// Mark `terminal` no-connect, or take its mark off. A mark on a pin that is
2120    /// joined is kept, and said: the check reports it until one or the other goes.
2121    fn toggle_no_connect(&mut self, terminal: Terminal) {
2122        let name = self.document.terminal_name(&terminal);
2123        let marked = self.document.no_connects.contains(&terminal);
2124        self.transaction(|d| {
2125            if marked {
2126                d.no_connects.retain(|t| *t != terminal);
2127            } else {
2128                d.no_connects.push(terminal.clone());
2129            }
2130        });
2131        if marked {
2132            self.note = Some(format!("{name}: no-connect taken off."));
2133            return;
2134        }
2135        let joined = self.document.netlist().nets.into_iter().find(|n| {
2136            n.pins.len() > 1
2137                && n.pins.iter().any(|p| p.component_id == terminal.component && p.number == terminal.pin)
2138        });
2139        match joined {
2140            Some(net) => {
2141                self.notice = Some(format!(
2142                    "{name} is marked no-connect, but it is joined to {}: the check reports the mark until the wire or the mark goes.",
2143                    net.name
2144                ))
2145            }
2146            None => self.note = Some(format!("{name} marked no-connect: the check does not ask for it to be joined.")),
2147        }
2148    }
2149    /// Put a power flag on `terminal`, or take it off.
2150    fn toggle_power_flag(&mut self, terminal: Terminal) {
2151        let name = self.document.terminal_name(&terminal);
2152        let flagged = self.document.power_flags.contains(&terminal);
2153        self.transaction(|d| {
2154            if flagged {
2155                d.power_flags.retain(|t| *t != terminal);
2156            } else {
2157                d.power_flags.push(terminal.clone());
2158            }
2159        });
2160        let net = self
2161            .document
2162            .netlist()
2163            .nets
2164            .into_iter()
2165            .find(|n| n.pins.iter().any(|p| p.component_id == terminal.component && p.number == terminal.pin))
2166            .map_or_else(String::new, |n| n.name);
2167        self.note = Some(if flagged {
2168            format!("{name}: power flag taken off {net}.")
2169        } else {
2170            format!("Power flag on {name}: {net} is driven from off the sheet.")
2171        });
2172    }
2173    /// The pin the Power flag tool flags for a click at `p` (snapped to `q`): the pin
2174    /// under it, or, on a wire, label or junction of a net, that net's first power
2175    /// input, or its first pin when it has none. A flag marks the NET, and the net
2176    /// is what the check reads.
2177    fn power_flag_target(&self, p: Pos2, q: Point, rect: Rect) -> Option<Terminal> {
2178        if let Some(t) = self.hit_terminal(p, rect) {
2179            return Some(t);
2180        }
2181        if !self.lands_on_net(q) {
2182            return None;
2183        }
2184        // A point along a wire is not one of the net's points; the wire's end is.
2185        let anchor = self
2186            .document
2187            .wires
2188            .iter()
2189            .find(|w| w.points().windows(2).any(|s| brep_ecad_core::on_segment(q, s[0], s[1])))
2190            .map_or(q, |w| w.a);
2191        let net = self.document.netlist().nets.into_iter().find(|n| n.points.contains(&anchor))?;
2192        // A pin already flagged on the net is the one a second click takes off.
2193        let pin = net
2194            .pins
2195            .iter()
2196            .find(|p| {
2197                self.document
2198                    .power_flags
2199                    .iter()
2200                    .any(|t| t.component == p.component_id && t.pin == p.number)
2201            })
2202            .or_else(|| net.pins.iter().find(|p| p.electrical_type == "power_in"))
2203            .or_else(|| net.pins.first())?;
2204        Some(Terminal {
2205            component: pin.component_id,
2206            pin: pin.number.clone(),
2207        })
2208    }
2209    /// Place the Power tool's symbol at `q`, saying what it joined.
2210    fn place_power_symbol(&mut self, q: Point) {
2211        let name = self.power_net_text.trim().to_owned();
2212        if name.is_empty() {
2213            self.notice = Some("Choose or type a power net name first.".into());
2214            return;
2215        }
2216        let joined = self.label_joins("Power symbol", &name, q);
2217        let mut id = None;
2218        self.transaction(|d| id = d.place_power_symbol(power_symbol(&name), q, 0).ok());
2219        self.select_only(id.map(Selection::Component));
2220        match joined {
2221            Some((line, true)) => self.notice = Some(line),
2222            Some((line, false)) => self.note = Some(line),
2223            None => {
2224                let reference = id
2225                    .and_then(|id| self.document.components.iter().find(|c| c.id == id))
2226                    .map(|c| c.reference.clone())
2227                    .unwrap_or_default();
2228                self.note = Some(format!("{reference} placed on {name}."));
2229            }
2230        }
2231    }
2232    /// Whether `q` is already a point of the net: a pin, a junction, a label, or
2233    /// anywhere along a wire, which is where [`Tool::Wire`] ends a run.
2234    /// The board zone on a sheet: the box round the parts on the board, grown by
2235    /// [`ZONE_MARGIN`]; `None` with none on it.
2236    pub fn board_zone(&self) -> Option<(Point, Point)> {
2237        Self::zone_of(&self.document)
2238    }
2239    fn zone_of(document: &Document) -> Option<(Point, Point)> {
2240        let (lo, hi) = document.board_zone_extent()?;
2241        Some((lo.offset(Point::new(-ZONE_MARGIN, -ZONE_MARGIN)), hi.offset(Point::new(ZONE_MARGIN, ZONE_MARGIN))))
2242    }
2243    /// A part dragged across the board zone's edge: its id, and whether it is now
2244    /// off the board. The zone is the one `before` had, as the drag began, because
2245    /// the zone is drawn round its parts and a part dragged inside it would carry
2246    /// the edge along with it.
2247    fn zone_crossing(&self, before: &Document) -> Option<(Uuid, bool)> {
2248        if self.document.kind != DocumentKind::Sheet {
2249            return None;
2250        }
2251        let Some(Selection::Component(id)) = self.selected else { return None };
2252        if self.document.zone_member(id).is_some() {
2253            return None;
2254        }
2255        let c = self.document.components.iter().find(|c| c.id == id)?;
2256        if before.components.iter().find(|c| c.id == id).is_none_or(|was| was.at == c.at && was.gates == c.gates) {
2257            return None;
2258        }
2259        let boxes = c.sheet_boxes();
2260        let n = boxes.len().max(1) as i64;
2261        let (sx, sy) = boxes.iter().fold((0i64, 0i64), |(x, y), (_, a, b)| {
2262            (x + (a.x as i64 + b.x as i64) / 2, y + (a.y as i64 + b.y as i64) / 2)
2263        });
2264        let center = Point::new((sx / n) as i32, (sy / n) as i32);
2265        let inside = Self::zone_of(before)
2266            .is_some_and(|(lo, hi)| (lo.x..=hi.x).contains(&center.x) && (lo.y..=hi.y).contains(&center.y));
2267        // Out of the zone only with the harness tools up: laying out the board's
2268        // schematic with the net tools, a part dragged past the edge makes room and
2269        // the zone grows round it, rather than the part leaving the board.
2270        match (c.off_board, inside) {
2271            (true, true) => Some((id, false)),
2272            (false, false) if self.wiring() => Some((id, true)),
2273            _ => None,
2274        }
2275    }
2276    /// Why the Wire tool may not run a net to `q`: a pin of a part off the board.
2277    fn off_board_pin_at(&self, q: Point) -> Option<String> {
2278        if self.wiring() || self.document.kind != DocumentKind::Sheet {
2279            return None;
2280        }
2281        let c = self
2282            .document
2283            .components
2284            .iter()
2285            .filter(|c| c.off_board)
2286            .find(|c| c.symbol.pins.iter().any(|p| c.pin_at(p) == q))?;
2287        let pin = c.symbol.pins.iter().find(|p| c.pin_at(p) == q)?;
2288        self.document.net_reaches(&Terminal { component: c.id, pin: pin.number.clone() }).err()
2289    }
2290    fn lands_on_net(&self, q: Point) -> bool {
2291        let d = &self.document;
2292        d.terminal_at(q).is_some()
2293            || d.junctions.contains(&q)
2294            || d.labels.iter().any(|l| l.at == q)
2295            || d.wires.iter().any(|w| {
2296                w.points()
2297                    .windows(2)
2298                    .any(|s| brep_ecad_core::on_segment(q, s[0], s[1]))
2299            })
2300    }
2301    fn hit_terminal(&self, p: Pos2, rect: Rect) -> Option<Terminal> {
2302        self.document
2303            .components
2304            .iter()
2305            .flat_map(|c| c.symbol.pins.iter().map(move |pin| (c, pin)))
2306            .filter_map(|(c, pin)| {
2307                let distance = self.screen(c.pin_at(pin), rect).distance(p);
2308                (distance <= 12.).then_some((
2309                    Terminal {
2310                        component: c.id,
2311                        pin: pin.number.clone(),
2312                    },
2313                    distance,
2314                ))
2315            })
2316            .min_by(|a, b| a.1.total_cmp(&b.1))
2317            .map(|(terminal, _)| terminal)
2318    }
2319    fn hit_segment(&self, p: Pos2, rect: Rect) -> Option<(Uuid, usize)> {
2320        self.document
2321            .wires
2322            .iter()
2323            .flat_map(|w| {
2324                w.points()
2325                    .windows(2)
2326                    .enumerate()
2327                    .map(|(i, s)| {
2328                        (
2329                            w.id,
2330                            i,
2331                            segment_distance(p, self.screen(s[0], rect), self.screen(s[1], rect)),
2332                        )
2333                    })
2334                    .collect::<Vec<_>>()
2335            })
2336            .filter(|(_, _, d)| *d < 9.)
2337            .min_by(|a, b| a.2.total_cmp(&b.2))
2338            .map(|(id, i, _)| (id, i))
2339    }
2340    fn bounds(&self, c: &Component, rect: Rect) -> Rect {
2341        self.gate_bounds(c, None, rect)
2342    }
2343    /// The screen box of one gate of `c` ([`Component::gates`]), or of all of it
2344    /// for `None`. A component drawn whole has one box whichever is asked.
2345    fn gate_bounds(&self, c: &Component, gate: Option<u32>, rect: Rect) -> Rect {
2346        let drawn = |g: u32| c.gates.is_empty() || gate.is_none_or(|gate| gate == g);
2347        let at = gate.and_then(|g| c.gate(g)).map_or(c.at, |g| g.at);
2348        let mut r = Rect::from_center_size(self.screen(at, rect), Vec2::splat(8.));
2349        for (i, g) in c.symbol.graphics.iter().enumerate() {
2350            if !drawn(c.symbol.graphic_gate(i)) {
2351                continue;
2352            }
2353            match g {
2354                Graphic::Text { at, .. } => {
2355                    r.extend_with(self.screen(c.graphic_transform(i, *at), rect));
2356                }
2357                Graphic::Path(points) => {
2358                    for p in points {
2359                        r.extend_with(self.screen(c.graphic_transform(i, *p), rect));
2360                    }
2361                }
2362                Graphic::Circle { center, radius } => {
2363                    let center = self.screen(c.graphic_transform(i, *center), rect);
2364                    r = r.union(Rect::from_center_size(
2365                        center,
2366                        Vec2::splat(*radius as f32 * self.zoom * 2.),
2367                    ));
2368                }
2369            }
2370        }
2371        for p in c.symbol.pins.iter().filter(|p| drawn(p.gate)) {
2372            r.extend_with(self.screen(c.pin_at(p), rect));
2373        }
2374        r
2375    }
2376    /// The gates `c` is drawn as, each with its box: `(gate, box)`, gate `0` for
2377    /// a component drawn whole.
2378    fn drawn_gates(&self, c: &Component, rect: Rect) -> Vec<(u32, Rect)> {
2379        if c.gates.is_empty() {
2380            vec![(0, self.bounds(c, rect))]
2381        } else {
2382            c.gates
2383                .iter()
2384                .map(|g| (g.gate, self.gate_bounds(c, Some(g.gate), rect)))
2385                .collect()
2386        }
2387    }
2388    /// The gate of the selected component that selection picked, when it places
2389    /// its gates apart: what a drag, Move or Rotate acts on.
2390    fn selected_gate(&self) -> Option<u32> {
2391        match (self.selected, self.selected_gate) {
2392            (Some(Selection::Component(id)), Some((gid, gate))) if id == gid => self
2393                .document
2394                .components
2395                .iter()
2396                .find(|c| c.id == id)
2397                .and_then(|c| c.gate(gate))
2398                .map(|g| g.gate),
2399            _ => None,
2400        }
2401    }
2402    /// Select what is under `p`, remembering which gate of a component it was.
2403    /// With Shift held no gate is remembered: the whole part is picked, and a
2404    /// drag, Move or Rotate then acts on every gate of it together.
2405    fn pick(&mut self, p: Pos2, rect: Rect, ctx: &egui::Context) {
2406        let hit = self.hit(p, rect, ctx);
2407        self.select_only(hit);
2408        let whole = ctx.input(|i| i.modifiers.shift);
2409        self.selected_gate = match self.selected {
2410            Some(Selection::Component(id)) if !whole => self.hit_gate(id, p, rect).map(|g| (id, g)),
2411            _ => None,
2412        };
2413    }
2414    /// Which gate of component `id` is under `p`, when it places its gates apart.
2415    fn hit_gate(&self, id: Uuid, p: Pos2, rect: Rect) -> Option<u32> {
2416        let c = self.document.components.iter().find(|c| c.id == id)?;
2417        self.drawn_gates(c, rect)
2418            .into_iter()
2419            .rev()
2420            .find(|(g, r)| *g > 0 && r.expand(7.).contains(p))
2421            .map(|(g, _)| g)
2422    }
2423    /// Where each clickable thing of the view in front is drawn, in screen points,
2424    /// keyed for a host that drives the editor by key rather than by coordinate.
2425    /// `canvas` is the rect [`Editor::show`] was given; the board keeps its own.
2426    /// Computed with the same mapping and bounds the canvas paints and hit-tests
2427    /// with, so the centre of each rect is a point the editor answers for that
2428    /// thing. On the sheet: `component:<reference>` (its bounds),
2429    /// `pin:<reference>.<pin>` (the pin's tip), `wire:<index>` (the middle of its
2430    /// longest segment), `label:<index>`, `junction:<index>`, and the Connectivity
2431    /// panel's check, while it is drawn: `inspector:erc:run`, `inspector:erc:row:<i>`
2432    /// and `inspector:erc:fix:<i>`. On the board:
2433    /// `part:<reference>` (its courtyard), `pad:<reference>.<number>` (one pad as
2434    /// drawn; a mechanical pad has no number and publishes none), `track:<index>`,
2435    /// `via:<index>`.
2436    pub fn hits(&self, canvas: Rect) -> Vec<(String, Rect)> {
2437        if self.view == View::Board {
2438            return self.board_hits();
2439        }
2440        // The canvas's empty corners, `canvas:corner` and `canvas:far`: a drag
2441        // from one to the other draws a box over everything Fit shows.
2442        let mut out = vec![
2443            ("canvas:corner".to_string(), Rect::from_min_size(canvas.min + Vec2::splat(4.), Vec2::splat(8.))),
2444            ("canvas:far".to_string(), Rect::from_min_size(canvas.max - Vec2::splat(12.), Vec2::splat(8.))),
2445        ];
2446        for c in &self.document.components {
2447            // A component whose gates are placed apart is one rect per gate, by
2448            // the name the sheet gives it (`component:U1B`), and `component:U1`
2449            // is its first gate: a point the editor answers with U1, where the
2450            // box around every gate may hold nothing at all. So a click there
2451            // picks the part and a drag moves gate A, as a drag of U1A does; a
2452            // Shift-drag from any gate's rect moves the whole part.
2453            let gates = self.drawn_gates(c, canvas);
2454            out.push((format!("component:{}", c.reference), gates[0].1));
2455            for (gate, bounds) in gates.iter().filter(|(g, _)| *g > 0) {
2456                out.push((format!("component:{}", c.gate_reference(*gate)), *bounds));
2457            }
2458            for pin in &c.symbol.pins {
2459                let tip = self.screen(c.pin_at(pin), canvas);
2460                out.push((format!("pin:{}.{}", c.reference, pin.number), Rect::from_center_size(tip, Vec2::splat(12.))));
2461            }
2462        }
2463        for (i, w) in self.document.wires.iter().enumerate() {
2464            let points = w.points();
2465            let longest = points
2466                .windows(2)
2467                .map(|s| (self.screen(s[0], canvas), self.screen(s[1], canvas)))
2468                .max_by(|a, b| a.0.distance(a.1).total_cmp(&b.0.distance(b.1)));
2469            if let Some((a, b)) = longest {
2470                out.push((format!("wire:{i}"), Rect::from_center_size(a.lerp(b, 0.5), Vec2::splat(8.))));
2471            }
2472        }
2473        for (i, l) in self.document.labels.iter().enumerate() {
2474            out.push((format!("label:{i}"), Rect::from_center_size(self.screen(l.at, canvas), Vec2::splat(12.))));
2475        }
2476        for (i, j) in self.document.junctions.iter().enumerate() {
2477            out.push((format!("junction:{i}"), Rect::from_center_size(self.screen(*j, canvas), Vec2::splat(8.))));
2478        }
2479        // The markers, by the pin they mark, where each is drawn.
2480        for (prefix, marks) in [("no_connect", &self.document.no_connects), ("power_flag", &self.document.power_flags)] {
2481            for t in marks {
2482                if let Some(at) = self.document.terminal_position(t) {
2483                    let r = Rect::from_center_size(self.screen(at, canvas), Vec2::splat(12.));
2484                    out.push((format!("{prefix}:{}", self.document.terminal_name(t)), r));
2485                }
2486            }
2487        }
2488        out.extend(self.erc.hits.shown(self.canvas_pass));
2489        out.extend(self.properties_hits.shown(self.canvas_pass));
2490        out
2491    }
2492    /// Draw and interact inside any egui Ui; no global panels or file dialogs.
2493    pub fn show(&mut self, ui: &mut egui::Ui) {
2494        // Before anything is drawn, because a device the HOST added reaches the editor
2495        // as a change to `parts` and never as an edit here. Gated; see
2496        // [`Editor::follow_parts`].
2497        self.follow_parts();
2498        if self.view == View::Board {
2499            return self.show_board(ui);
2500        }
2501        let (response, painter) = ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
2502        let rect = response.rect;
2503        self.canvas_size = rect.size();
2504        self.canvas_pass = ui.ctx().cumulative_pass_nr();
2505        let pointer = ui.input(|i| i.pointer.hover_pos());
2506        if response.hovered() && ui.input(|i| i.pointer.primary_pressed()) {
2507            self.notice = None;
2508            self.note = None;
2509            // A value prompt the Inspector never drew (its tab behind another) dies
2510            // here rather than taking the keys whenever the tab comes forward.
2511            self.value_prompt = None;
2512        }
2513        if let Some(payload) = response.dnd_release_payload::<LibraryPartDrag>()
2514            && let Some(p) = pointer
2515        {
2516            let at = self.snap(p, rect);
2517            self.placing_part = Some(payload.0.clone());
2518            let id = self.place_here(payload.0.symbol.clone(), at, 0);
2519            self.select_only(id.map(Selection::Component));
2520            self.set_tool(Tool::Select);
2521        }
2522        // The wheel zooms about the pointer, so it needs the pointer here. The keys
2523        // do not: see [`keys_reach_editor`].
2524        if response.hovered()
2525            && !ui.ctx().egui_wants_keyboard_input()
2526            && let Some((factor, p)) = pointer_zoom(ui)
2527        {
2528            zoom_at(&mut self.zoom, &mut self.pan, factor, p - rect.center());
2529        }
2530        let pinch = pinching(ui);
2531        if pinch {
2532            self.terminal_drag = None;
2533            self.boxing = None;
2534            if let Some((before, _)) = self.group_drag.take() {
2535                self.document = before;
2536            }
2537            if let Some((before, ..)) = self.path_drag.take() {
2538                self.document = before;
2539            }
2540            if let Some((before, ..)) = self.drag.take() {
2541                self.document = before;
2542            }
2543        }
2544        if keys_reach_editor(ui.ctx()) {
2545            self.run_shortcuts(ui.ctx());
2546        }
2547        if response.dragged_by(PointerButton::Middle)
2548            || response.dragged_by(PointerButton::Secondary)
2549        {
2550            self.pan += ui.input(|i| i.pointer.delta());
2551        }
2552        if response.secondary_clicked() {
2553            self.cancel();
2554            self.context_terminal = pointer.and_then(|p| self.hit_terminal(p, rect));
2555            // A right-click on the selection keeps it, for its menu.
2556            match pointer {
2557                Some(p) if self.hit(p, rect, ui.ctx()).is_some_and(|hit| self.is_selected(hit)) => {}
2558                Some(p) => self.pick(p, rect, ui.ctx()),
2559                None => self.select_only(None),
2560            }
2561        }
2562        response.context_menu(|ui| {
2563            menu_ui(ui);
2564            if matches!(
2565                self.selected,
2566                Some(Selection::Component(_) | Selection::Label(_))
2567            ) && ui.button("Rotate 90°").clicked()
2568            {
2569                self.rotate();
2570                ui.close();
2571            }
2572            if self.selected.is_some() && ui.button("Delete").clicked() {
2573                self.delete();
2574                ui.close();
2575            }
2576            if !self.wiring()
2577                && let Some(terminal) = self.context_terminal.clone()
2578            {
2579                let existing = self
2580                    .document
2581                    .labels
2582                    .iter()
2583                    .find(|l| l.terminal.as_ref() == Some(&terminal));
2584                if ui
2585                    .button(if existing.is_some() {
2586                        "Edit net flag…"
2587                    } else {
2588                        "Add net flag…"
2589                    })
2590                    .clicked()
2591                {
2592                    self.net_flag_edit = Some(NetFlagEdit {
2593                        terminal: terminal.clone(),
2594                        name: existing.map_or(String::new(), |l| l.name.clone()),
2595                        focus: true,
2596                    });
2597                    ui.close();
2598                }
2599                if existing.is_some() && ui.button("Remove net flag").clicked() {
2600                    self.transaction(|d| {
2601                        d.labels.retain(|l| l.terminal.as_ref() != Some(&terminal))
2602                    });
2603                    ui.close();
2604                }
2605            }
2606        });
2607        if matches!(self.tool, Tool::Select | Tool::Wire)
2608            && !pinch
2609            && response.drag_started_by(PointerButton::Primary)
2610            && let Some(p) = ui.input(|i| i.pointer.press_origin())
2611        {
2612            if let Some(terminal) = self.hit_target(p, rect) {
2613                if let Some(refusal) = self.taken(&terminal).or_else(|| self.net_refusal(&terminal)) {
2614                    self.notice = Some(refusal);
2615                } else {
2616                    self.wire_start = None;
2617                    self.terminal_drag = Some(terminal);
2618                }
2619            } else if self.tool == Tool::Select
2620                && let Some(mode) = {
2621                    // A drag from empty canvas draws a box: Ctrl/Cmd adds, Alt
2622                    // removes. (Shift keeps its meaning here: the whole part.)
2623                    let mods = ui.input(|i| i.modifiers);
2624                    self.hit(p, rect, ui.ctx()).is_none().then(|| {
2625                        use footprint_editor::BoxMode;
2626                        if mods.alt { BoxMode::Remove } else if mods.command { BoxMode::Add } else { BoxMode::Replace }
2627                    })
2628                }
2629            {
2630                self.boxing = Some((p, mode));
2631            } else if self.tool == Tool::Select
2632                && let Some(hit) = self.hit(p, rect, ui.ctx())
2633                && (self.selected_count() > 1 && self.is_selected(hit) || ui.input(|i| i.modifiers.command))
2634            {
2635                // On a member of the selection, or with Ctrl/Cmd held, the
2636                // whole selection moves, that item primary.
2637                self.add_selected(hit);
2638                self.group_drag = Some((self.document.clone(), self.world(p, rect)));
2639            } else if self.tool == Tool::Select {
2640                self.pick(p, rect, ui.ctx());
2641                match self.selected {
2642                    Some(Selection::Component(id)) => {
2643                        if let Some(c) = self.document.components.iter().find(|c| c.id == id) {
2644                            let at = self.selected_gate().and_then(|g| c.gate(g)).map_or(c.at, |g| g.at);
2645                            self.drag = Some((self.document.clone(), self.world(p, rect), at));
2646                        }
2647                    }
2648                    Some(Selection::Label(id)) => {
2649                        if let Some(l) = self.document.labels.iter().find(|l| l.id == id) {
2650                            self.drag = Some((self.document.clone(), self.world(p, rect), l.at));
2651                        }
2652                    }
2653                    Some(Selection::Wire(id)) => {
2654                        if let Some((_, index)) = self.hit_segment(p, rect) {
2655                            self.selected_segment = index;
2656                            self.path_drag =
2657                                Some((self.document.clone(), id, index, self.world(p, rect)));
2658                        }
2659                    }
2660                    _ => {}
2661                }
2662            }
2663        }
2664        if let (Some((before, start, at)), Some(p), Some(Selection::Component(id))) =
2665            (&self.drag, pointer, self.selected)
2666        {
2667            let q = self.world(p, rect);
2668            let target = Point::new(at.x + q.x - start.x, at.y + q.y - start.y).snapped();
2669            let gate = self.selected_gate();
2670            self.document = before.clone();
2671            // A sub-board's part moves its whole zone.
2672            match self.document.zone_member(id).map(|z| z.occurrence.clone()) {
2673                Some(zone) => {
2674                    let by = Point::new(target.x - at.x, target.y - at.y);
2675                    let _ = self.document.move_zone(&zone, by);
2676                }
2677                None => Self::move_component(&mut self.document, id, gate, Some(target), None),
2678            }
2679        }
2680        if let (Some((before, start, at)), Some(p), Some(Selection::Label(id))) =
2681            (&self.drag, pointer, self.selected)
2682        {
2683            let q = self.world(p, rect);
2684            let target_screen =
2685                self.screen(Point::new(at.x + q.x - start.x, at.y + q.y - start.y), rect);
2686            self.document = before.clone();
2687            let target = self.snap(target_screen, rect);
2688            let rotation = self
2689                .document
2690                .labels
2691                .iter()
2692                .find(|l| l.id == id)
2693                .map_or(0, |l| l.rotation);
2694            self.document.transform_label(id, target, rotation);
2695        }
2696        if let (Some((before, start)), Some(p)) = (&self.group_drag, pointer) {
2697            let q = self.world(p, rect);
2698            let delta = Point::new(q.x - start.x, q.y - start.y).snapped();
2699            let items = self.selected_items();
2700            self.document = before.clone();
2701            Self::move_group(&mut self.document, &items, delta);
2702        }
2703        if let (Some((before, id, index, start)), Some(p)) = (&self.path_drag, pointer) {
2704            let q = self.world(p, rect);
2705            let delta = Point::new(q.x - start.x, q.y - start.y).snapped();
2706            self.document = before.clone();
2707            if let Some(w) = self.document.wires.iter_mut().find(|w| w.id == *id) {
2708                w.slide_segment(*index, delta);
2709            }
2710        }
2711        if response.drag_stopped_by(PointerButton::Primary) {
2712            if let Some(start) = self.terminal_drag.take()
2713                && let Some(end) = pointer
2714                    .filter(|p| rect.contains(*p))
2715                    .and_then(|p| self.hit_target(p, rect))
2716            {
2717                if let Some(refusal) = self.taken(&end).or_else(|| self.net_refusal(&end)) {
2718                    self.notice = Some(refusal);
2719                } else {
2720                    let mut id = None;
2721                    let stock_part_number = self.stock_part_number.trim().to_owned();
2722                    let harness = self.wiring();
2723                    self.transaction(|d| {
2724                        id = d.connect_targets_as(start, end, harness);
2725                        if harness
2726                            && let Some(w) = d.wires.iter_mut().find(|w| Some(w.id) == id)
2727                        {
2728                            w.stock_part_number = stock_part_number;
2729                        }
2730                    });
2731                    if let Some(id) = id {
2732                        self.select_only(Some(Selection::Wire(id)));
2733                        self.selected_segment = 0;
2734                    }
2735                }
2736            }
2737            if let Some((before, _, _)) = self.drag.take() {
2738                let crossing = self.zone_crossing(&before);
2739                self.commit(before, None);
2740                // A part dropped across the board zone's edge, as the zone stood
2741                // when the drag began, moves on or off the board. It is a second
2742                // transaction in the same frame, so the host stores the two as one
2743                // undo step; a refusal leaves the move itself standing, and says why.
2744                if let Some((id, off_board)) = crossing {
2745                    self.set_component_off_board(id, off_board);
2746                }
2747            }
2748            if let Some((before, _, _, _)) = self.path_drag.take() {
2749                self.commit(before, None);
2750            }
2751            if let Some((before, _)) = self.group_drag.take() {
2752                let selection = self.selected_items();
2753                self.commit(before, None);
2754                self.set_selection(selection);
2755            }
2756            if let (Some((from, mode)), Some(to)) = (self.boxing.take(), pointer) {
2757                self.box_select(Rect::from_two_pos(from, to), to.x < from.x, mode, rect);
2758            }
2759        }
2760        // A double click on a board of its own's part edits that board.
2761        if response.double_clicked_by(PointerButton::Primary)
2762            && self.tool == Tool::Select
2763            && let Some(p) = pointer
2764        {
2765            self.pick(p, rect, ui.ctx());
2766            self.enter_selected_zone();
2767        }
2768        if response.clicked_by(PointerButton::Primary)
2769            && let Some(p) = pointer
2770        {
2771            let q = self.snap(p, rect);
2772            match self.tool {
2773                // Ctrl/Cmd+click adds or takes out one item.
2774                Tool::Select if ui.input(|i| i.modifiers.command) => {
2775                    if let Some(hit) = self.hit(p, rect, ui.ctx()) {
2776                        self.toggle_selected(hit);
2777                    }
2778                }
2779                Tool::Select => {
2780                    self.pick(p, rect, ui.ctx());
2781                    if let Some((_, index)) = self.hit_segment(p, rect) {
2782                        self.selected_segment = index;
2783                    }
2784                }
2785                Tool::Move => {
2786                    if let Some(Selection::Component(id)) = self.selected {
2787                        let gate = self.selected_gate();
2788                        self.transaction(|d| Self::move_component(d, id, gate, Some(q), None));
2789                    }
2790                    if let Some(Selection::Label(id)) = self.selected {
2791                        self.transaction(|d| {
2792                            if let Some(l) = d.labels.iter().find(|l| l.id == id) {
2793                                let rotation = l.rotation;
2794                                d.transform_label(id, q, rotation);
2795                            }
2796                        });
2797                    }
2798                    self.set_tool(Tool::Select);
2799                }
2800                Tool::Place => {
2801                    if let Some(s) = self.placing.clone() {
2802                        let rotation = self.rotation;
2803                        let id = self.place_here(s, q, rotation);
2804                        self.select_only(id.map(Selection::Component));
2805                    }
2806                }
2807                Tool::Junction => {
2808                    self.transaction(|d| {
2809                        if !d.junctions.remove(&q) {
2810                            d.junctions.insert(q);
2811                        }
2812                    });
2813                }
2814                Tool::NoConnect => match self.hit_terminal(p, rect) {
2815                    Some(terminal) => self.toggle_no_connect(terminal),
2816                    None => self.notice = Some("Click the end of a pin to mark it no-connect.".into()),
2817                },
2818                Tool::PowerFlag => match self.power_flag_target(p, q, rect) {
2819                    Some(terminal) => self.toggle_power_flag(terminal),
2820                    None => {
2821                        self.notice = Some(
2822                            "Click a pin, or a wire of a net that reaches a pin, to put a power flag on it.".into(),
2823                        )
2824                    }
2825                },
2826                Tool::Power => self.place_power_symbol(q),
2827                Tool::Label => {
2828                    let name = self.label_text.trim().to_owned();
2829                    if name.is_empty() {
2830                        self.notice = Some("Type a label name first.".into());
2831                    } else {
2832                        let joined = self.label_joins("Label", &name, q);
2833                        self.transaction(|d| {
2834                            d.labels.push(Label {
2835                                flag: false,
2836                                rotation: 0,
2837                                terminal: None,
2838                                id: Uuid::new_v4(),
2839                                name,
2840                                at: q,
2841                            })
2842                        });
2843                        match joined {
2844                            Some((line, true)) => self.notice = Some(line),
2845                            Some((line, false)) => self.note = Some(line),
2846                            None => {}
2847                        }
2848                        self.label_placed = true;
2849                    }
2850                }
2851                Tool::Wire if self.off_board_pin_at(q).is_some() => {
2852                    self.notice = self.off_board_pin_at(q);
2853                }
2854                Tool::Wire => {
2855                    // A run ends where it lands on the net: a pin, a junction, a
2856                    // label or a wire (KiCad's rule), so A to B then C is two
2857                    // wires and not one run shorting all three. Asked of the sheet
2858                    // BEFORE this click's segments, which would contain `q`.
2859                    let lands = self.wire_start.is_some() && self.lands_on_net(q);
2860                    if let Some(a) = self.wire_start {
2861                        let bend = if self.vertical_first {
2862                            Point::new(a.x, q.y)
2863                        } else {
2864                            Point::new(q.x, a.y)
2865                        };
2866                        self.transaction(|d| {
2867                            d.add_wire(a, bend);
2868                            d.add_wire(bend, q);
2869                        });
2870                    }
2871                    self.wire_start = (!lands).then_some(q);
2872                }
2873            }
2874        }
2875        painter.rect_filled(rect, 0., Color32::from_rgb(17, 23, 32));
2876        if let (Some((from, _)), Some(to)) = (self.boxing, pointer) {
2877            footprint_editor::paint_box(&painter, from, to, ui.visuals().selection.stroke.color);
2878        }
2879        // Every selected item is drawn selected.
2880        let members = self.selected_items();
2881        let spacing = grid_spacing(self.zoom);
2882        let origin = rect.center() + self.pan;
2883        let mut x = rect.left() + (origin.x - rect.left()).rem_euclid(spacing);
2884        while x < rect.right() {
2885            let mut y = rect.top() + (origin.y - rect.top()).rem_euclid(spacing);
2886            while y < rect.bottom() {
2887                painter.circle_filled(Pos2::new(x, y), 0.8, Color32::from_rgb(41, 51, 65));
2888                y += spacing;
2889            }
2890            x += spacing;
2891        }
2892        for w in &self.document.wires {
2893            let color = if members.contains(&Selection::Wire(w.id)) {
2894                ACCENT
2895            } else {
2896                WIRE
2897            };
2898            let points = w.points();
2899            painter.add(egui::Shape::line(
2900                points.iter().map(|p| self.screen(*p, rect)).collect(),
2901                Stroke::new(2., color),
2902            ));
2903            // A wiring diagram labels each connection on its longest segment.
2904            if !w.connection_id.is_empty()
2905                && self.zoom > 0.006
2906                && let Some(s) = points
2907                    .windows(2)
2908                    .max_by_key(|s| s[0].x.abs_diff(s[1].x) + s[0].y.abs_diff(s[1].y))
2909            {
2910                painter.text(
2911                    self.screen(s[0], rect).lerp(self.screen(s[1], rect), 0.5) + Vec2::new(0., -4.),
2912                    Align2::CENTER_BOTTOM,
2913                    &w.connection_id,
2914                    FontId::monospace(11.),
2915                    color,
2916                );
2917            }
2918            if self.selected == Some(Selection::Wire(w.id)) && members.len() == 1 {
2919                for (i, s) in points.windows(2).enumerate() {
2920                    let center = self.screen(s[0], rect).lerp(self.screen(s[1], rect), 0.5);
2921                    painter.rect_filled(
2922                        Rect::from_center_size(
2923                            center,
2924                            Vec2::splat(if i == self.selected_segment { 8. } else { 6. }),
2925                        ),
2926                        1.,
2927                        ACCENT,
2928                    );
2929                }
2930            }
2931        }
2932        // The board zone, round the parts on the board, under them.
2933        if let Some((lo, hi)) = self.board_zone() {
2934            let zone = Rect::from_two_pos(self.screen(lo, rect), self.screen(hi, rect));
2935            painter.rect_filled(zone, 6., Color32::from_rgba_unmultiplied(70, 120, 90, 28));
2936            painter.rect_stroke(zone, 6., Stroke::new(1.5, Color32::from_rgb(90, 160, 115)), egui::StrokeKind::Inside);
2937            painter.text(
2938                zone.left_top() + Vec2::new(6., 4.),
2939                egui::Align2::LEFT_TOP,
2940                "Board",
2941                egui::FontId::proportional(12.),
2942                Color32::from_rgb(120, 190, 140),
2943            );
2944        }
2945        // Each board of its own the assembly places: its zone, read-only, by label.
2946        for z in &self.document.zones {
2947            let Some((lo, hi)) = self.document.sub_zone_extent(&z.occurrence) else { continue };
2948            let lo = lo.offset(Point::new(-ZONE_MARGIN, -ZONE_MARGIN));
2949            let hi = hi.offset(Point::new(ZONE_MARGIN, ZONE_MARGIN));
2950            let zone = Rect::from_two_pos(self.screen(lo, rect), self.screen(hi, rect));
2951            painter.rect_filled(zone, 6., Color32::from_rgba_unmultiplied(70, 100, 140, 28));
2952            painter.rect_stroke(zone, 6., Stroke::new(1.5, Color32::from_rgb(100, 140, 190)), egui::StrokeKind::Inside);
2953            painter.text(
2954                zone.left_top() + Vec2::new(6., 4.),
2955                egui::Align2::LEFT_TOP,
2956                format!("Board {} (read-only)", z.reference),
2957                egui::FontId::proportional(12.),
2958                Color32::from_rgb(140, 170, 210),
2959            );
2960        }
2961        for c in &self.document.components {
2962            // A component whose device the assembly does not offer is drawn in the
2963            // warning colour, so a broken link is seen on the sheet and not only in a
2964            // panel the user may not have open.
2965            let color = match self.unlinked_device(c).is_some() {
2966                true => board_view::WARNING,
2967                false => INK,
2968            };
2969            self.paint_component(&painter, c, rect, color);
2970            if members.contains(&Selection::Component(c.id)) {
2971                // Every gate of the part is ringed; the one a drag or Rotate acts
2972                // on more strongly.
2973                let picked = self.selected_gate();
2974                for (gate, bounds) in self.drawn_gates(c, rect) {
2975                    let width = if picked == Some(gate) { 2. } else { 1. };
2976                    painter.rect_stroke(
2977                        bounds.expand(8.),
2978                        3.,
2979                        Stroke::new(width, ACCENT),
2980                        egui::StrokeKind::Outside,
2981                    );
2982                }
2983            }
2984        }
2985        for p in &self.document.junctions {
2986            painter.circle_filled(self.screen(*p, rect), 4., ACCENT);
2987        }
2988        for l in &self.document.labels {
2989            if self.names_power_symbol(l) {
2990                continue;
2991            }
2992            let tip = self.screen(l.at, rect);
2993            if l.flag || l.terminal.is_some() {
2994                let (galley, outline, text_origin) =
2995                    net_flag_layout(ui.ctx(), &l.name, tip, self.zoom / 0.012, l.rotation);
2996                let width = if members.contains(&Selection::Label(l.id)) {
2997                    2.5
2998                } else {
2999                    1.5
3000                };
3001                painter.add(egui::Shape::convex_polygon(
3002                    outline.to_vec(),
3003                    Color32::from_rgb(20, 42, 40),
3004                    Stroke::new(width, ACCENT),
3005                ));
3006                painter.add(
3007                    egui::epaint::TextShape::new(text_origin, galley, ACCENT)
3008                        .with_angle(l.rotation as f32 * std::f32::consts::FRAC_PI_2),
3009                );
3010            } else {
3011                painter.circle_filled(tip, 3., ACCENT);
3012                let end = self.document.terminal_at(l.at).and_then(|t| {
3013                    let c = self.document.components.iter().find(|c| c.id == t.component)?;
3014                    let pin = c.symbol.pins.iter().find(|p| p.number == t.pin)?;
3015                    Some(self.screen(c.pin_end(pin), rect))
3016                });
3017                let (align, offset) = label_placement(tip, end);
3018                painter.text(tip + offset, align, &l.name, FontId::monospace(13.), ACCENT);
3019            }
3020        }
3021        self.paint_erc(&painter, rect);
3022        if let Some(payload) = response.dnd_hover_payload::<LibraryPartDrag>()
3023            && let Some(p) = pointer
3024        {
3025            let at = self.snap(p, rect);
3026            let symbol = &payload.0.symbol;
3027            let preview = Component {
3028                id: Uuid::nil(),
3029                reference: payload
3030                    .0
3031                    .reference
3032                    .clone()
3033                    .unwrap_or_else(|| format!("{}?", symbol.reference_prefix)),
3034                value: symbol
3035                    .library_id
3036                    .split(':')
3037                    .next_back()
3038                    .unwrap_or("")
3039                    .into(),
3040                symbol: symbol.clone(),
3041                at,
3042                rotation: 0,
3043                part: None,
3044                pads: None,
3045                gates: vec![],
3046                pin_functions: Default::default(),
3047                off_board: false,
3048            };
3049            self.paint_component(&painter, &preview, rect, ACCENT);
3050            ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
3051        }
3052        if let Some(p) = pointer.filter(|p| rect.contains(*p)) {
3053            let q = self.snap(p, rect);
3054            let at = self.screen(q, rect);
3055            if self.tool != Tool::Select {
3056                painter.circle_stroke(at, 5., Stroke::new(1., ACCENT));
3057                ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
3058            }
3059            if matches!(self.tool, Tool::Select | Tool::Wire) {
3060                if let Some(terminal) = self.hit_target(p, rect) {
3061                    let t = self.document.target_position(&terminal).unwrap();
3062                    let taken = self.taken(&terminal).is_some();
3063                    painter.circle_stroke(
3064                        self.screen(t, rect),
3065                        8.,
3066                        Stroke::new(2., if taken { board_view::WARNING } else { ACCENT }),
3067                    );
3068                    ui.ctx().set_cursor_icon(if taken {
3069                        egui::CursorIcon::NotAllowed
3070                    } else {
3071                        egui::CursorIcon::Crosshair
3072                    });
3073                } else if let Some((id, i)) = self.hit_segment(p, rect)
3074                    && let Some(w) = self.document.wires.iter().find(|w| w.id == id)
3075                {
3076                    let points = w.points();
3077                    ui.ctx().set_cursor_icon(if points[i].y == points[i + 1].y {
3078                        egui::CursorIcon::ResizeVertical
3079                    } else {
3080                        egui::CursorIcon::ResizeHorizontal
3081                    });
3082                }
3083            }
3084            if let Some(start) = &self.terminal_drag {
3085                let a = self.document.target_position(start).unwrap();
3086                let target = self.hit_target(p, rect).filter(|t| self.taken(t).is_none());
3087                let end = target
3088                    .as_ref()
3089                    .and_then(|t| self.document.target_position(t))
3090                    .unwrap_or(q);
3091                let path = target
3092                    .as_ref()
3093                    .and_then(|t| self.document.target_path(start, t))
3094                    .unwrap_or_else(|| vec![a, Point::new(end.x, a.y), end]);
3095                painter.add(egui::Shape::line(
3096                    path.iter().map(|p| self.screen(*p, rect)).collect(),
3097                    Stroke::new(2.5, ACCENT),
3098                ));
3099            }
3100            if self.tool == Tool::Place
3101                && let Some(s) = &self.placing
3102            {
3103                let c = Component {
3104                    id: Uuid::nil(),
3105                    reference: format!("{}?", s.reference_prefix),
3106                    value: s.library_id.split(':').next_back().unwrap_or("").into(),
3107                    symbol: s.clone(),
3108                    at: q,
3109                    rotation: self.rotation,
3110                    part: None,
3111                    pads: None,
3112                    gates: vec![],
3113                    pin_functions: Default::default(),
3114                    off_board: false,
3115                };
3116                self.paint_component(&painter, &c, rect, ACCENT);
3117            }
3118            if self.tool == Tool::Wire
3119                && let Some(a) = self.wire_start
3120            {
3121                let bend = if self.vertical_first {
3122                    Point::new(a.x, q.y)
3123                } else {
3124                    Point::new(q.x, a.y)
3125                };
3126                painter.add(egui::Shape::line(
3127                    vec![self.screen(a, rect), self.screen(bend, rect), at],
3128                    Stroke::new(2., ACCENT),
3129                ));
3130            }
3131            if self.tool == Tool::Label {
3132                painter.text(
3133                    at,
3134                    Align2::LEFT_BOTTOM,
3135                    &self.label_text,
3136                    FontId::monospace(13.),
3137                    ACCENT,
3138                );
3139            }
3140            let name = self.power_net_text.trim();
3141            if self.tool == Tool::Power && !name.is_empty() {
3142                let preview = Component {
3143                    id: Uuid::nil(),
3144                    reference: "#PWR?".into(),
3145                    value: name.into(),
3146                    symbol: power_symbol(name),
3147                    at: q,
3148                    rotation: 0,
3149                    part: None,
3150                    pads: None,
3151                    gates: vec![],
3152                    pin_functions: Default::default(),
3153                    off_board: false,
3154                };
3155                self.paint_component(&painter, &preview, rect, ACCENT.gamma_multiply(0.6));
3156            }
3157            self.status = format!(
3158                "{:?}   ·   {:.2}, {:.2} mm   ·   Grid 1.27 mm   ·   {:.0}%",
3159                self.tool,
3160                q.x as f64 / 1000.,
3161                q.y as f64 / 1000.,
3162                self.zoom / 0.012 * 100.
3163            );
3164        }
3165        painter.text(
3166            rect.left_top() + Vec2::new(20., 18.),
3167            Align2::LEFT_TOP,
3168            &self.document.title,
3169            FontId::proportional(14.),
3170            Color32::from_rgb(119, 137, 158),
3171        );
3172        if let Some(notice) = &self.notice {
3173            painter.text(
3174                rect.left_top() + Vec2::new(20., 40.),
3175                Align2::LEFT_TOP,
3176                notice,
3177                FontId::proportional(13.),
3178                board_view::WARNING,
3179            );
3180        } else if let Some(note) = &self.note {
3181            painter.text(
3182                rect.left_top() + Vec2::new(20., 40.),
3183                Align2::LEFT_TOP,
3184                note,
3185                FontId::proportional(13.),
3186                Color32::from_rgb(119, 137, 158),
3187            );
3188        }
3189        if self.document.components.is_empty()
3190            && self.document.wires.is_empty()
3191            && self.tool == Tool::Select
3192            && response.dnd_hover_payload::<LibraryPartDrag>().is_none()
3193        {
3194            // Names the pane by the name its tab carries, and says what to do there:
3195            // with nothing listed yet there is no part to choose, only one to add.
3196            let start = if self.wiring() {
3197                "Your wiring diagram starts here"
3198            } else {
3199                "Your circuit starts here"
3200            };
3201            let next = match (self.parts.is_empty(), &self.add_part_label) {
3202                (false, _) => "Choose a part from Assembly parts",
3203                (true, Some(_)) => "Add a part to the assembly in Assembly parts",
3204                (true, None) => "No parts to place yet",
3205            };
3206            painter.text(
3207                rect.center(),
3208                Align2::CENTER_CENTER,
3209                format!("{start}\n{next}"),
3210                FontId::proportional(20.),
3211                Color32::from_rgb(119, 137, 158),
3212            );
3213        }
3214        self.net_flag_dialog(ui.ctx());
3215    }
3216    fn net_flag_dialog(&mut self, ctx: &egui::Context) {
3217        let Some(mut edit) = self.net_flag_edit.take() else {
3218            return;
3219        };
3220        let mut open = true;
3221        let mut apply = false;
3222        let mut cancel = false;
3223        egui::Window::new("Net flag")
3224            .collapsible(false)
3225            .resizable(false)
3226            .open(&mut open)
3227            .show(ctx, |ui| {
3228                ui.label("Same name = same electrical net, without a wire.");
3229                ui.label("Net name");
3230                let field = ui.add(
3231                    egui::TextEdit::singleline(&mut edit.name).hint_text("e.g. GND, +5V, SIGNAL"),
3232                );
3233                if (field.has_focus() || field.lost_focus())
3234                    && ui.input(|i| i.key_pressed(Key::Enter))
3235                    && !edit.name.trim().is_empty()
3236                {
3237                    apply = true;
3238                }
3239                if edit.focus {
3240                    field.request_focus();
3241                    edit.focus = false;
3242                }
3243                let names: std::collections::BTreeSet<_> = self
3244                    .document
3245                    .labels
3246                    .iter()
3247                    .map(|l| l.name.clone())
3248                    .collect();
3249                if !names.is_empty() {
3250                    ui.label("Existing nets");
3251                    egui::ScrollArea::vertical()
3252                        .max_height(150.)
3253                        .show(ui, |ui| {
3254                            for name in names {
3255                                if ui.selectable_label(edit.name == name, &name).clicked() {
3256                                    edit.name = name;
3257                                }
3258                            }
3259                        });
3260                }
3261                ui.horizontal(|ui| {
3262                    if ui
3263                        .add_enabled(
3264                            !edit.name.trim().is_empty(),
3265                            egui::Button::new("Apply net flag"),
3266                        )
3267                        .clicked()
3268                    {
3269                        apply = true;
3270                    }
3271                    if ui.button("Cancel").clicked() {
3272                        cancel = true;
3273                    }
3274                });
3275            });
3276        if apply {
3277            let terminal = edit.terminal.clone();
3278            self.transaction(|d| {
3279                let _ = d.set_net_flag(terminal, &edit.name);
3280            });
3281        } else if open && !cancel {
3282            self.net_flag_edit = Some(edit);
3283        }
3284    }
3285    fn paint_component(&self, painter: &egui::Painter, c: &Component, rect: Rect, color: Color32) {
3286        // Each gate's body, on screen: where a pin's name has room inside it.
3287        let mut bodies: BTreeMap<u32, Rect> = BTreeMap::new();
3288        for (i, g) in c.symbol.graphics.iter().enumerate() {
3289            let transform = |p| self.screen(c.graphic_transform(i, p), rect);
3290            let gate = c.symbol.graphic_gate(i);
3291            let mut body = |p: Pos2| {
3292                let r = bodies.entry(gate).or_insert(Rect::from_min_max(p, p));
3293                r.extend_with(p);
3294            };
3295            match g {
3296                Graphic::Text { at, text, size, angle } => {
3297                    let font = FontId::proportional((*size as f32 * self.zoom).clamp(6., 36.));
3298                    let galley = painter.layout_no_wrap(text.clone(), font, color);
3299                    turned_text(painter, transform(*at), Align2::CENTER_CENTER, galley, color, *angle);
3300                }
3301                Graphic::Path(points) => {
3302                    let points: Vec<Pos2> = points.iter().map(|p| transform(*p)).collect();
3303                    points.iter().for_each(|p| body(*p));
3304                    painter.add(egui::Shape::line(points, Stroke::new(1.8, color)));
3305                }
3306                Graphic::Circle { center, radius } => {
3307                    let (center, radius) = (transform(*center), *radius as f32 * self.zoom);
3308                    body(center - Vec2::splat(radius));
3309                    body(center + Vec2::splat(radius));
3310                    painter.circle_stroke(center, radius, Stroke::new(1.8, color));
3311                }
3312            }
3313        }
3314        // A power symbol shows its net's name past its body, away from its pin,
3315        // and nothing else: KiCad hides a power symbol's `#PWR` reference and its
3316        // one pin.
3317        if let Some(net) = &c.symbol.power_net {
3318            let pin = c.symbol.pins.first().map_or(self.screen(c.at, rect), |p| self.screen(c.pin_at(p), rect));
3319            let body = bodies.values().fold(Rect::from_min_max(pin, pin), |a, b| a.union(*b));
3320            let away = body.center() - pin;
3321            let (at, align) = if away.y.abs() >= away.x.abs() {
3322                if away.y >= 0. {
3323                    (Pos2::new(pin.x, body.bottom() + 2.), Align2::CENTER_TOP)
3324                } else {
3325                    (Pos2::new(pin.x, body.top() - 2.), Align2::CENTER_BOTTOM)
3326                }
3327            } else if away.x >= 0. {
3328                (Pos2::new(body.right() + 3., pin.y), Align2::LEFT_CENTER)
3329            } else {
3330                (Pos2::new(body.left() - 3., pin.y), Align2::RIGHT_CENTER)
3331            };
3332            painter.text(at, align, net, FontId::proportional(12.), color);
3333            return;
3334        }
3335        // What the pins print, by gate, so the reference is written clear of it.
3336        let mut printed: BTreeMap<u32, Rect> = BTreeMap::new();
3337        let mut print = |gate: u32, r: Rect| {
3338            printed.entry(gate).and_modify(|p| *p = p.union(r)).or_insert(r);
3339        };
3340        let leads: Vec<(Pos2, Pos2)> = c
3341            .symbol
3342            .pins
3343            .iter()
3344            .map(|pin| (self.screen(c.pin_at(pin), rect), self.screen(c.pin_end(pin), rect)))
3345            .collect();
3346        for (index, pin) in c.symbol.pins.iter().enumerate() {
3347            let (a, b) = leads[index];
3348            painter.line_segment([a, b], Stroke::new(1.5, color));
3349            let flagged = self.document.labels.iter().any(|l| {
3350                l.terminal
3351                    .as_ref()
3352                    .is_some_and(|t| t.component == c.id && t.pin == pin.number)
3353            });
3354            if !flagged {
3355                painter.circle_stroke(a, 2.5, Stroke::new(1., WIRE));
3356            }
3357            if self.zoom <= 0.006 {
3358                continue;
3359            }
3360            // KiCad's symbol-level `(pin_numbers (hide yes))` and `(pin_names
3361            // (hide yes))`, as a resistor and a connector carry them.
3362            let middle = a.lerp(b, 0.5);
3363            let across = (b.x - a.x).abs() >= (b.y - a.y).abs();
3364            if !c.symbol.hide_pin_numbers {
3365                // Over a lead that runs across, beside one that runs up or down:
3366                // never on the lead, and never where a net label goes (see
3367                // [`label_placement`]).
3368                let (align, offset) = if across {
3369                    (Align2::CENTER_BOTTOM, Vec2::new(0., -4.))
3370                } else {
3371                    (Align2::RIGHT_CENTER, Vec2::new(-4., 0.))
3372                };
3373                print(
3374                    pin.gate,
3375                    painter.text(
3376                        middle + offset,
3377                        align,
3378                        &pin.number,
3379                        FontId::monospace(10.),
3380                        Color32::from_rgb(145, 166, 190),
3381                    ),
3382                );
3383            }
3384            // The function chosen for this pin on this part, else its main name.
3385            let Some(name) = pin_name(c.pin_label(pin)).filter(|_| !c.symbol.hide_pin_names) else {
3386                continue;
3387            };
3388            // The name belongs inside the body, past the lead, as the symbol editor
3389            // and KiCad both show it — when it fits there. Two names that face
3390            // each other across a small body share it; one that would run into the
3391            // other ("P1P2") goes outside, under its own lead.
3392            let font = FontId::monospace(10.);
3393            let width = painter.layout_no_wrap(name.to_owned(), font.clone(), color).size().x;
3394            let room = bodies
3395                .get(&pin.gate)
3396                .map_or(0., |body| name_room(*body, a, b, &leads));
3397            let (at, align) = if width + 4. <= room {
3398                let (align, offset) = pin_name_placement(a, b);
3399                (b + offset, align)
3400            } else if across {
3401                (middle + Vec2::new(0., 3.), Align2::CENTER_TOP)
3402            } else {
3403                (middle + Vec2::new(4., 0.), Align2::LEFT_CENTER)
3404            };
3405            print(pin.gate, painter.text(at, align, name, font, color));
3406        }
3407        for (gate, bounds) in self.drawn_gates(c, rect) {
3408            // Beside the body, clear of what its pins print; ABOVE it when a pin
3409            // leaves from its right side, where that pin's wire and net label go
3410            // (an op-amp's output).
3411            let right_lead = c.symbol.pins.iter().zip(&leads).any(|(pin, (a, b))| {
3412                (c.gates.is_empty() || pin.gate == gate)
3413                    && a.x >= bounds.right() - 1.
3414                    && (a.x - b.x).abs() > (a.y - b.y).abs()
3415            });
3416            let clear = printed
3417                .get(&gate)
3418                .filter(|_| !c.gates.is_empty())
3419                .or(printed.get(&0).filter(|_| c.gates.is_empty()))
3420                .map_or(bounds, |p| bounds.union(*p));
3421            let (anchor, align) = if right_lead {
3422                (bounds.left_top() + Vec2::new(0., -6.), Align2::LEFT_BOTTOM)
3423            } else {
3424                (Pos2::new(clear.right(), bounds.top()) + Vec2::new(9., 0.), Align2::LEFT_TOP)
3425            };
3426            painter.text(
3427                anchor,
3428                align,
3429                // A part with no value, such as one from a symbol nobody has named
3430                // yet, shows its reference alone rather than a blank second line.
3431                if c.value.trim().is_empty() {
3432                    c.gate_reference(gate)
3433                } else {
3434                    format!("{}\n{}", c.gate_reference(gate), c.value)
3435                },
3436                FontId::proportional(12.),
3437                color,
3438            );
3439        }
3440    }
3441}
3442/// How much room, in screen points, a pin's name has inside `body` past the
3443/// pin's body end `b` (its terminal is `a`): up to the far side of the body,
3444/// or to halfway when another pin's body end faces this one across it on the
3445/// same line. `0` when the lead does not end on the body at all.
3446pub(crate) fn name_room(body: Rect, a: Pos2, b: Pos2, leads: &[(Pos2, Pos2)]) -> f32 {
3447    let inward = (b - a).normalized();
3448    if !body.expand(1.).contains(b) || !inward.is_finite() {
3449        return 0.;
3450    }
3451    let far = |p: Pos2| {
3452        let to = |edge: f32, from: f32, d: f32| if d.abs() < 0.5 { f32::INFINITY } else { (edge - from) / d };
3453        to(if inward.x > 0. { body.max.x } else { body.min.x }, p.x, inward.x)
3454            .min(to(if inward.y > 0. { body.max.y } else { body.min.y }, p.y, inward.y))
3455    };
3456    let room = far(b).max(0.);
3457    let facing = leads.iter().any(|(oa, ob)| {
3458        let theirs = (*ob - *oa).normalized();
3459        *ob != b
3460            && theirs.dot(inward) < -0.9
3461            && (*ob - b).dot(inward) > 0.
3462            && ((*ob - b) - inward * (*ob - b).dot(inward)).length() < 1.
3463    });
3464    if facing { room / 2. } else { room }
3465}
3466/// Where a free net label's name goes, when the label sits on a pin whose lead
3467/// runs from `tip` to `end`: on the far side of the tip from the body, so it
3468/// never overprints the pin's number or name. `None` when it is not on a pin.
3469pub(crate) fn label_placement(tip: Pos2, end: Option<Pos2>) -> (Align2, Vec2) {
3470    let Some(end) = end else {
3471        return (Align2::LEFT_BOTTOM, Vec2::new(5., -5.));
3472    };
3473    let (dx, dy) = (end.x - tip.x, end.y - tip.y);
3474    if dx.abs() >= dy.abs() {
3475        if dx > 0. {
3476            // The body is to the right: read leftward from the tip.
3477            (Align2::RIGHT_BOTTOM, Vec2::new(-5., -3.))
3478        } else {
3479            (Align2::LEFT_BOTTOM, Vec2::new(5., -3.))
3480        }
3481    } else if dy < 0. {
3482        // The body is above: below the tip, beside where the wire leaves.
3483        (Align2::LEFT_TOP, Vec2::new(5., 3.))
3484    } else {
3485        (Align2::LEFT_BOTTOM, Vec2::new(5., -5.))
3486    }
3487}
3488/// A pin's name, or `None` when it has none: KiCad writes an unnamed pin as `~`.
3489pub(crate) fn pin_name(name: &str) -> Option<&str> {
3490    let name = name.trim();
3491    (!name.is_empty() && name != "~").then_some(name)
3492}
3493
3494/// Where a pin's name goes, given the lead from its terminal `at` to its body end
3495/// `b` on screen: just beyond the body end, reading away from the terminal.
3496pub(crate) fn pin_name_placement(at: Pos2, b: Pos2) -> (Align2, Vec2) {
3497    let (dx, dy) = (b.x - at.x, b.y - at.y);
3498    if dx.abs() >= dy.abs() {
3499        if dx >= 0. {
3500            (Align2::LEFT_CENTER, Vec2::new(4., 0.))
3501        } else {
3502            (Align2::RIGHT_CENTER, Vec2::new(-4., 0.))
3503        }
3504    } else if dy >= 0. {
3505        (Align2::CENTER_TOP, Vec2::new(0., 3.))
3506    } else {
3507        (Align2::CENTER_BOTTOM, Vec2::new(0., -3.))
3508    }
3509}
3510
3511/// The arrow shoulder is one half-height behind the terminal, so the two
3512/// diagonal edges meet at a 90-degree tip. Text stays inside the rectangular body.
3513fn net_flag_layout(
3514    ctx: &egui::Context,
3515    name: &str,
3516    tip: Pos2,
3517    scale: f32,
3518    rotation: u8,
3519) -> (std::sync::Arc<egui::Galley>, [Pos2; 5], Pos2) {
3520    let font = FontId::monospace(13. * scale);
3521    let galley = zoomed_text(ctx, name.into(), font, ACCENT);
3522    let padding = 5. * scale;
3523    let half_height = galley.size().y / 2. + padding;
3524    let shoulder = tip.x - half_height;
3525    let left = shoulder - galley.size().x - 2. * padding;
3526    let outline = [
3527        Pos2::new(left, tip.y - half_height),
3528        Pos2::new(shoulder, tip.y - half_height),
3529        tip,
3530        Pos2::new(shoulder, tip.y + half_height),
3531        Pos2::new(left, tip.y + half_height),
3532    ];
3533    let origin = Pos2::new(left + padding, tip.y - galley.size().y / 2.);
3534    let rotate = egui::emath::Rot2::from_angle(rotation as f32 * std::f32::consts::FRAC_PI_2);
3535    (
3536        galley,
3537        outline.map(|p| tip + rotate * (p - tip)),
3538        tip + rotate * (origin - tip),
3539    )
3540}
3541
3542/// A part's card in the library: its symbol drawn small, its name, and its label or
3543/// description. A part already on the sheet is drawn dimmed and says so.
3544fn part_card(ui: &mut egui::Ui, part: &Part, selected: bool, placed: bool) -> egui::Response {
3545    let symbol = &part.symbol;
3546    let description = symbol
3547        .description
3548        .split(", script generated")
3549        .next()
3550        .unwrap_or("");
3551    let name = part.name.as_str();
3552    let about = match (&part.reference, placed) {
3553        (Some(reference), true) => format!("{reference} · on the sheet"),
3554        (Some(reference), false) => reference.clone(),
3555        (None, _) => description.to_owned(),
3556    };
3557    let (rect, response) = ui.allocate_exact_size(
3558        Vec2::new(ui.available_width(), 88.),
3559        if placed { Sense::click() } else { Sense::click_and_drag() },
3560    );
3561    response.widget_info(|| {
3562        egui::WidgetInfo::labeled(egui::WidgetType::Button, !placed, format!("{name}\n{about}"))
3563    });
3564    let response = if placed {
3565        response.on_hover_text(format!("{name}\n{about}\nRight-click to open the part."))
3566    } else {
3567        response
3568            .on_hover_text(format!(
3569                "{name}\n{about}\nDrag onto the sheet, or click to place. Right-click to open the part."
3570            ))
3571            .on_hover_cursor(egui::CursorIcon::Grab)
3572    };
3573    // The theme's own widget grounds and text, light or dark. A card used to
3574    // be painted a hand-set navy in either, and on the light theme's panel it
3575    // was the one dark block in the pane.
3576    let visuals = ui.visuals();
3577    let fill = if placed {
3578        None
3579    } else if selected || response.dragged() {
3580        Some(visuals.selection.bg_fill)
3581    } else if response.hovered() {
3582        Some(visuals.widgets.hovered.weak_bg_fill)
3583    } else {
3584        Some(visuals.widgets.inactive.weak_bg_fill)
3585    };
3586    // A placed card is not a button any more, so it is drawn as none: an
3587    // outline on the pane's own ground, its words in the theme's weak colour.
3588    // Weak words on a widget ground, or faded ones, measured 2.69:1 on the
3589    // light theme, under the 2.77:1 of its own weakest text on its panel.
3590    let (ink, faint) = if placed {
3591        (visuals.weak_text_color(), visuals.weak_text_color())
3592    } else {
3593        (visuals.strong_text_color(), visuals.text_color())
3594    };
3595    let (lines, dots) = (visuals.text_color(), accent(ui));
3596    match fill {
3597        Some(fill) => {
3598            ui.painter().rect_filled(rect, 5., fill);
3599        }
3600        None => {
3601            ui.painter().rect_stroke(
3602                rect.shrink(0.5),
3603                5.,
3604                visuals.widgets.noninteractive.bg_stroke,
3605                egui::StrokeKind::Inside,
3606            );
3607        }
3608    }
3609    let painter = ui.painter().clone();
3610    let mut preview = painter.clone();
3611    if placed {
3612        preview.multiply_opacity(0.45);
3613    }
3614    paint_symbol_preview(
3615        &preview,
3616        symbol,
3617        Rect::from_min_size(rect.min + Vec2::new(8., 10.), Vec2::new(62., 68.)),
3618        lines,
3619        dots,
3620    );
3621    let width = (rect.width() - 88.).max(20.);
3622    let title = painter.layout(name.into(), FontId::proportional(13.), ink, width);
3623    painter.galley(rect.min + Vec2::new(80., 15.), title.clone(), ink);
3624    let subtitle = if about.chars().count() > 32 {
3625        format!("{}…", about.chars().take(31).collect::<String>())
3626    } else {
3627        about
3628    };
3629    let subtitle = painter.layout(subtitle, FontId::proportional(11.), faint, width);
3630    painter.with_clip_rect(rect.shrink(5.)).galley(
3631        rect.min + Vec2::new(80., 20. + title.size().y),
3632        subtitle,
3633        faint,
3634    );
3635
3636    response
3637}
3638/// A symbol drawn small, its lines in `ink` and its pin tips in `dots`: the
3639/// card's theme gives both, since the card is drawn on the theme's ground.
3640fn paint_symbol_preview(painter: &egui::Painter, symbol: &Symbol, rect: Rect, ink: Color32, dots: Color32) {
3641    let mut bounds = Rect::NOTHING;
3642    let point = |p: Point| Pos2::new(p.x as f32, p.y as f32);
3643    for g in &symbol.graphics {
3644        match g {
3645            Graphic::Text { at, .. } => bounds.extend_with(point(*at)),
3646            Graphic::Path(points) => {
3647                for p in points {
3648                    bounds.extend_with(point(*p));
3649                }
3650            }
3651            Graphic::Circle { center, radius } => {
3652                bounds = bounds.union(Rect::from_center_size(
3653                    point(*center),
3654                    Vec2::splat(*radius as f32 * 2.),
3655                ))
3656            }
3657        }
3658    }
3659    for p in &symbol.pins {
3660        bounds.extend_with(point(p.at));
3661        bounds.extend_with(point(p.end));
3662    }
3663    if !bounds.is_finite() {
3664        return;
3665    }
3666    let scale = ((rect.width() - 8.) / bounds.width().max(1270.))
3667        .min((rect.height() - 8.) / bounds.height().max(1270.));
3668    let transform = |p: Point| rect.center() + (point(p) - bounds.center()) * scale;
3669    for g in &symbol.graphics {
3670        match g {
3671            Graphic::Text { at, text, size, angle } => {
3672                let font = FontId::proportional((*size as f32 * scale).clamp(4., 10.));
3673                let galley = painter.layout_no_wrap(text.clone(), font, ink);
3674                turned_text(painter, transform(*at), Align2::CENTER_CENTER, galley, ink, *angle);
3675            }
3676            Graphic::Path(points) => {
3677                painter.add(egui::Shape::line(
3678                    points.iter().map(|p| transform(*p)).collect(),
3679                    Stroke::new(1.5, ink),
3680                ));
3681            }
3682            Graphic::Circle { center, radius } => {
3683                painter.circle_stroke(
3684                    transform(*center),
3685                    *radius as f32 * scale,
3686                    Stroke::new(1.5, ink),
3687                );
3688            }
3689        }
3690    }
3691    for p in &symbol.pins {
3692        painter.line_segment([transform(p.at), transform(p.end)], Stroke::new(1.2, ink));
3693        painter.circle_filled(transform(p.at), 2., dots);
3694    }
3695}
3696fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 {
3697    let ab = b - a;
3698    let t = ((p - a).dot(ab) / ab.length_sq().max(0.001)).clamp(0., 1.);
3699    p.distance(a + ab * t)
3700}
3701
3702