Skip to main content

brep_ecad_egui/
board_view.rs

1//! PCB layout view: footprint placement, manual routing, autorouting, and checks.
2use crate::grips::{self, Handle};
3use super::*;
4use crate::actions::{Action, ActionGroup, command, key, sheet_action};
5use brep_ecad_core::autoroute::RouteJob;
6use brep_ecad_core::board::{
7    Airwire, Board, BoardSync, ClassReason, Connectivity, CopperRef, DEFAULT_CLASS, DesignRules, NetClass, Pad, Placement, Shape, Track,
8    Via, ViaKind, ViaPolicy, Violation, ViolationKind, Zone, layer_name, needs_footprint, rectangle,
9};
10use brep_ecad_core::board::zones::{self, ZoneReport};
11use brep_ecad_core::board::{BoardCutout, BoardGraphic, MAX_CUTOUTS};
12use brep_ecad_core::graphic::{GraphicLayer, GraphicShape, LayerGraphic};
13use crate::footprint_editor::{edit_graphic, graphic_kind, layer_choices, move_graphic, point_in};
14use crate::symbol_editor::{InspectorHits, key_word};
15use brep_ecad_core::footprint;
16use std::collections::{BTreeMap, BTreeSet};
17
18/// Grid for dragging footprints and drawing tracks by hand.
19const PLACE_GRID: i32 = 250;
20/// Autorouter work per frame, in grid node expansions.
21const ROUTE_BUDGET: u64 = 120_000;
22pub(crate) const BACKGROUND: Color32 = Color32::from_rgb(14, 19, 26);
23const SUBSTRATE: Color32 = Color32::from_rgb(19, 34, 33);
24const EDGE: Color32 = Color32::from_rgb(222, 196, 76);
25pub(crate) const THROUGH_HOLE: Color32 = Color32::from_rgb(201, 162, 72);
26const VIA: Color32 = Color32::from_rgb(178, 184, 192);
27pub(crate) const SILK: Color32 = Color32::from_rgb(222, 226, 232);
28/// Paint the inside of a closed outline (its last point repeating its first),
29/// concave or not: ear-clipped into triangles, as a fan when the clipping finds
30/// no ear (a self-crossing outline).
31pub(crate) fn paint_filled(painter: &egui::Painter, outline: &[Pos2], color: Color32) {
32    let mut ring: Vec<Pos2> = outline.to_vec();
33    if ring.len() > 1 && ring.first() == ring.last() {
34        ring.pop();
35    }
36    if ring.len() < 3 {
37        return;
38    }
39    let area: f32 = (0..ring.len())
40        .map(|i| {
41            let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
42            a.x * b.y - b.x * a.y
43        })
44        .sum();
45    let cross = |a: Pos2, b: Pos2, c: Pos2| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
46    let sign = if area >= 0. { 1. } else { -1. };
47    let mut left: Vec<usize> = (0..ring.len()).collect();
48    let mut triangles: Vec<[usize; 3]> = vec![];
49    let mut guard = ring.len() * ring.len();
50    while left.len() > 3 && guard > 0 {
51        guard -= 1;
52        let n = left.len();
53        let ear = (0..n).find(|&i| {
54            let (a, b, c) = (left[(i + n - 1) % n], left[i], left[(i + 1) % n]);
55            sign * cross(ring[a], ring[b], ring[c]) > 0.
56                && !left.iter().any(|&k| {
57                    k != a && k != b && k != c && {
58                        let p = ring[k];
59                        let (d1, d2, d3) = (cross(ring[a], ring[b], p), cross(ring[b], ring[c], p), cross(ring[c], ring[a], p));
60                        sign * d1 >= 0. && sign * d2 >= 0. && sign * d3 >= 0.
61                    }
62                })
63        });
64        let Some(i) = ear else { break };
65        triangles.push([left[(i + n - 1) % n], left[i], left[(i + 1) % n]]);
66        left.remove(i);
67    }
68    if left.len() == 3 {
69        triangles.push([left[0], left[1], left[2]]);
70    } else {
71        // No ear: fan what is left from its first corner.
72        triangles.extend((1..left.len().saturating_sub(1)).map(|i| [left[0], left[i], left[i + 1]]));
73    }
74    let mut mesh = egui::epaint::Mesh::default();
75    for p in &ring {
76        mesh.colored_vertex(*p, color);
77    }
78    for [a, b, c] in triangles {
79        mesh.add_triangle(a as u32, b as u32, c as u32);
80    }
81    painter.add(egui::Shape::mesh(mesh));
82}
83/// The colour a drawn item is painted in, by the board (or footprint) layer
84/// it is on: the silkscreen's, the fabrication drawing's and the courtyard's.
85pub(crate) fn graphic_color(layer: brep_ecad_core::graphic::GraphicLayer) -> Color32 {
86    use brep_ecad_core::graphic::GraphicLayer as L;
87    match layer {
88        L::FrontSilk => SILK.gamma_multiply(0.7),
89        L::BackSilk => Color32::from_rgb(142, 154, 186).gamma_multiply(0.7),
90        L::FrontFab | L::BackFab => Color32::from_rgb(176, 168, 120),
91        L::FrontCourtyard | L::BackCourtyard => Color32::from_rgb(200, 110, 200),
92    }
93}
94pub(crate) const WARNING: Color32 = Color32::from_rgb(238, 120, 96);
95/// The layers the board's own drawing can be on: a courtyard is a part's.
96fn board_layers() -> Vec<(GraphicLayer, &'static str, &'static str)> {
97    layer_choices().into_iter().filter(|c| !c.0.is_courtyard()).collect()
98}
99/// Whether board point `q` catches the board drawing `g`: within `tolerance`
100/// of one of its lines (grown by half its pen), or inside it when filled.
101fn board_drawing_hit(g: &BoardGraphic, q: Point, tolerance: f64) -> bool {
102    let strokes = g.graphic.strokes(!g.graphic.layer.front());
103    let reach = tolerance + f64::from(g.graphic.width()) / 2.;
104    // Text is caught anywhere in the box round its letters, as the Pads editor
105    // catches it: the inside of an "O" is still the text.
106    if matches!(g.graphic.shape, GraphicShape::Text { .. }) {
107        let all: Vec<Point> = strokes.iter().flatten().copied().collect();
108        let (Some(x0), Some(x1)) = (all.iter().map(|p| p.x).min(), all.iter().map(|p| p.x).max()) else {
109            return false;
110        };
111        let (y0, y1) = (all.iter().map(|p| p.y).min().unwrap_or(0), all.iter().map(|p| p.y).max().unwrap_or(0));
112        let (qx, qy) = (f64::from(q.x), f64::from(q.y));
113        return qx >= f64::from(x0) - reach && qx <= f64::from(x1) + reach && qy >= f64::from(y0) - reach && qy <= f64::from(y1) + reach;
114    }
115    strokes
116        .iter()
117        .flat_map(|line| line.windows(2))
118        .any(|s| Shape::segment(s[0], s[1], 0).distance_to_point(q) <= reach)
119        || (g.graphic.filled && strokes.first().is_some_and(|ring| point_in(q, ring)))
120}
121
122#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
123pub enum View {
124    #[default]
125    Schematic,
126    Board,
127}
128#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
129pub enum BoardTool {
130    #[default]
131    Select,
132    Route,
133    /// Draw a copper zone's outline, corner by corner.
134    Zone,
135    /// Draw a line or a closed shape on a silkscreen or fabrication layer of
136    /// the board itself, corner by corner.
137    Draw,
138    /// Put text on a silkscreen or fabrication layer of the board itself.
139    Text,
140    /// Draw a cutout, a hole milled through the board, corner by corner.
141    Cutout,
142}
143#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144pub enum BoardSelection {
145    Part(Uuid),
146    /// One PAD of a placed part: the component it belongs to, and the pad's
147    /// index in that placement's footprint. The index is the identity inside
148    /// the view, because a footprint may carry several pads with no number at
149    /// all (mechanical pads) and they are as selectable as the numbered ones;
150    /// [`Editor::select_board_pad`] and [`Editor::selected_board_pad`] speak
151    /// the NUMBER, which is the identity a pad shares with a pin and with a
152    /// part's connection point.
153    Pad(Uuid, usize),
154    /// One SILKSCREEN line of a placed part: the component, and the line's
155    /// index in that placement's footprint — the Pads editor's `silk:<index>`
156    /// identity, seen on the board. Silk is legend, never copper: selecting it
157    /// says which line of which part the pointer caught, and everything else it
158    /// answers for its part, as a pad does.
159    Silk(Uuid, usize),
160    Track(Uuid),
161    Via(Uuid),
162    /// An item drawn on the board itself ([`Board::graphics`]), owned by no part.
163    Drawing(Uuid),
164    /// A cutout milled through the board ([`Board::cutouts`]), by its id.
165    Cutout(Uuid),
166    /// A copper zone, by its id.
167    Zone(Uuid),
168}
169/// The part a board selection belongs to: a pad's is the part whose footprint
170/// carries it, so everything a part answers for — rotate, flip, a drag, its own
171/// right-click menu — answers for a pad of it too.
172fn part_of(selection: Option<BoardSelection>) -> Option<Uuid> {
173    match selection {
174        Some(
175            BoardSelection::Part(id) | BoardSelection::Pad(id, _) | BoardSelection::Silk(id, _),
176        ) => Some(id),
177        _ => None,
178    }
179}
180
181fn board(e: &Editor) -> bool {
182    e.view == View::Board
183}
184fn routing_tool(e: &Editor) -> bool {
185    board(e) && e.board_view.tool == BoardTool::Route
186}
187fn drafting(e: &Editor) -> bool {
188    e.board_view.draft.is_some()
189}
190fn zone_tool(e: &Editor) -> bool {
191    board(e) && e.board_view.tool == BoardTool::Zone
192}
193fn draw_tool(e: &Editor) -> bool {
194    board(e) && e.board_view.tool == BoardTool::Draw
195}
196fn cutout_tool(e: &Editor) -> bool {
197    board(e) && e.board_view.tool == BoardTool::Cutout
198}
199/// Choosing copper layer `layer` (from 0) on a board with at least `layer + 1` layers.
200const fn layer_action(
201    id: &'static str,
202    label: &'static str,
203    run: fn(&mut Editor),
204) -> Action<Editor> {
205    sheet_action(id, label, ActionGroup::Layer, run)
206}
207fn offers_layer(e: &Editor, layer: u8) -> bool {
208    board(e) && layer < e.document.board.layer_count
209}
210fn on_layer(e: &Editor, layer: u8) -> bool {
211    e.board_view
212        .active_layer
213        .min(e.document.board.layer_count - 1)
214        == layer
215}
216
217/// The board's actions; see [`crate::actions`].
218pub(crate) static BOARD_ACTIONS: &[Action<Editor>] = &[
219    sheet_action("board.tool.select", "Select", ActionGroup::Tool, |e| {
220        e.set_board_tool(BoardTool::Select)
221    })
222    .offered_when(board)
223    .pressed_when(|e| e.board_view.tool == BoardTool::Select),
224    sheet_action("board.tool.route", "Route track", ActionGroup::Tool, |e| {
225        e.set_board_tool(BoardTool::Route)
226    })
227    .keys(&[key(Key::X)])
228    .offered_when(board)
229    .pressed_when(|e| e.board_view.tool == BoardTool::Route),
230    sheet_action("board.tool.zone", "Draw zone", ActionGroup::Tool, |e| {
231        e.set_board_tool(BoardTool::Zone)
232    })
233    .offered_when(board)
234    .pressed_when(|e| e.board_view.tool == BoardTool::Zone),
235    sheet_action("board.tool.draw", "Draw line", ActionGroup::Tool, |e| {
236        e.set_board_tool(BoardTool::Draw)
237    })
238    .offered_when(board)
239    .pressed_when(|e| e.board_view.tool == BoardTool::Draw),
240    sheet_action("board.tool.text", "Place text", ActionGroup::Tool, |e| {
241        e.set_board_tool(BoardTool::Text)
242    })
243    .offered_when(board)
244    .pressed_when(|e| e.board_view.tool == BoardTool::Text),
245    sheet_action("board.tool.cutout", "Draw cutout", ActionGroup::Tool, |e| {
246        e.set_board_tool(BoardTool::Cutout)
247    })
248    .offered_when(board)
249    .pressed_when(|e| e.board_view.tool == BoardTool::Cutout),
250    layer_action("board.layer.1", "Copper layer 1", |e| e.choose_layer(0))
251        .offered_when(|e| offers_layer(e, 0))
252        .pressed_when(|e| on_layer(e, 0))
253        .captioned(|e| layer_name(0, e.document.board.layer_count)),
254    layer_action("board.layer.2", "Copper layer 2", |e| e.choose_layer(1))
255        .offered_when(|e| offers_layer(e, 1))
256        .pressed_when(|e| on_layer(e, 1))
257        .captioned(|e| layer_name(1, e.document.board.layer_count)),
258    layer_action("board.layer.3", "Copper layer 3", |e| e.choose_layer(2))
259        .offered_when(|e| offers_layer(e, 2))
260        .pressed_when(|e| on_layer(e, 2))
261        .captioned(|e| layer_name(2, e.document.board.layer_count)),
262    layer_action("board.layer.4", "Copper layer 4", |e| e.choose_layer(3))
263        .offered_when(|e| offers_layer(e, 3))
264        .pressed_when(|e| on_layer(e, 3))
265        .captioned(|e| layer_name(3, e.document.board.layer_count)),
266    layer_action("board.layer.5", "Copper layer 5", |e| e.choose_layer(4))
267        .offered_when(|e| offers_layer(e, 4))
268        .pressed_when(|e| on_layer(e, 4))
269        .captioned(|e| layer_name(4, e.document.board.layer_count)),
270    layer_action("board.layer.6", "Copper layer 6", |e| e.choose_layer(5))
271        .offered_when(|e| offers_layer(e, 5))
272        .pressed_when(|e| on_layer(e, 5))
273        .captioned(|e| layer_name(5, e.document.board.layer_count)),
274    sheet_action(
275        "board.route.corner",
276        "Corner direction",
277        ActionGroup::Context,
278        |e| e.board_view.diagonal_first = !e.board_view.diagonal_first,
279    )
280    .offered_when(routing_tool)
281    .captioned(|e| {
282        if e.board_view.diagonal_first {
283            "Corner: 45° first"
284        } else {
285            "Corner: straight first"
286        }
287        .into()
288    }),
289    sheet_action("board.route.via", "Place via", ActionGroup::Context, |e| {
290        let next = (e.board_view.active_layer + 1) % e.document.board.layer_count;
291        e.switch_layer(next);
292    })
293    .keys(&[key(Key::V)])
294    .offered_when(routing_tool)
295    .enabled_when(|e| drafting(e) && e.document.board.layer_count > 1),
296    sheet_action(
297        "board.route.finish",
298        "Finish track",
299        ActionGroup::Context,
300        Editor::finish_draft,
301    )
302    .keys(&[key(Key::Enter)])
303    .offered_when(routing_tool)
304    .enabled_when(drafting),
305    sheet_action(
306        "board.route.done",
307        "Done routing",
308        ActionGroup::Context,
309        |e| {
310            e.board_view.draft = None;
311            e.board_view.tool = BoardTool::Select;
312        },
313    )
314    .offered_when(routing_tool),
315    sheet_action(
316        "board.zone.finish",
317        "Close zone",
318        ActionGroup::Context,
319        Editor::finish_zone,
320    )
321    .keys(&[key(Key::Enter)])
322    .offered_when(zone_tool)
323    .enabled_when(|e| e.board_view.zone_draft.len() >= 3),
324    sheet_action(
325        "board.draw.finish",
326        "Finish line",
327        ActionGroup::Context,
328        Editor::finish_drawing,
329    )
330    .keys(&[key(Key::Enter)])
331    .offered_when(draw_tool)
332    .enabled_when(|e| e.board_view.drawing_draft.len() >= 2),
333    sheet_action(
334        "board.cutout.finish",
335        "Close cutout",
336        ActionGroup::Context,
337        Editor::finish_cutout,
338    )
339    .keys(&[key(Key::Enter)])
340    .offered_when(cutout_tool)
341    .enabled_when(|e| e.board_view.cutout_draft.len() >= 3),
342    sheet_action("board.zones.fill", "Fill zones", ActionGroup::Context, |e| {
343        e.fill_zones()
344    })
345    .keys(&[key(Key::B)])
346    .offered_when(board)
347    .enabled_when(|e| !e.document.board.zones.is_empty()),
348    sheet_action(
349        "board.rotate",
350        "Rotate 90°",
351        ActionGroup::Selection,
352        Editor::rotate_selection,
353    )
354    .keys(&[key(Key::R)])
355    .offered_when(board)
356    .enabled_when(|e| e.board_view.count() > 1 || part_of(e.board_view.selected).is_some() || e.turnable_drawing_or_cutout()),
357    sheet_action(
358        "board.delete",
359        "Delete selection",
360        ActionGroup::Selection,
361        Editor::delete_board_selection,
362    )
363    .keys(&[key(Key::Delete), key(Key::Backspace)])
364    .offered_when(board)
365    .enabled_when(|e| e.board_view.selected.is_some()),
366    sheet_action("board.select_all", "Select all", ActionGroup::Selection, Editor::select_all_board)
367        .keys(&[command(Key::A)])
368        .offered_when(board),
369    sheet_action("board.cancel", "Cancel", ActionGroup::Selection, |e| {
370        e.cancel_board();
371        e.board_view.selected = None;
372    })
373    .keys(&[key(Key::Escape)])
374    .offered_when(board),
375];
376
377/// A track being drawn by hand; completed layer runs and vias wait in `tracks`/`vias`.
378struct Draft {
379    layer: u8,
380    width: i32,
381    points: Vec<Point>,
382    tracks: Vec<Track>,
383    vias: Vec<Via>,
384}
385
386/// Where a track being drawn comes closer than the clearance between its net and
387/// another's to copper that is not its own: the gap in micrometres, what that
388/// copper is, the net it carries, where it is, and the clearance the two nets'
389/// classes ask for with the class that asks it ([`DesignRules::clearance_between`]).
390#[derive(Clone, Debug, PartialEq)]
391struct Clash {
392    gap: f64,
393    what: String,
394    net: Option<String>,
395    at: Point,
396    needed: i32,
397    class: String,
398}
399impl Clash {
400    /// Copper that touches is a short, not a narrow gap.
401    fn crosses(&self) -> bool {
402        self.gap < 0.5
403    }
404    /// "0.145 mm from R2 pad 2 (GND)", or "across R2 pad 2 (GND)" when it touches.
405    fn words(&self) -> String {
406        let net = self.net.as_deref().map_or(String::new(), |net| format!(" ({net})"));
407        if self.crosses() {
408            format!("across {}{net}", self.what)
409        } else {
410            format!("{:.3} mm from {}{net}", self.gap / 1000., self.what)
411        }
412    }
413    /// "0.200 mm needed (Default)", as the status line and the click's message say it.
414    fn needed_words(&self) -> String {
415        format!("{:.3} mm needed ({})", f64::from(self.needed) / 1000., self.class)
416    }
417}
418
419/// One leg a routing click would add: its points (from the draft's last point
420/// to the target), the clash it still has, and the clash of the corner it
421/// turned away from, if it turned.
422struct Leg {
423    points: Vec<Point>,
424    clash: Option<Clash>,
425    avoided: Option<Clash>,
426}
427
428/// What a part being dragged would come down on, judged every frame of the drag
429/// as the route tool judges a draft: each of its pads that comes within the
430/// board's clearance of another net's copper, closest first (a short before a
431/// narrow gap), and each part on its side whose courtyard its own overlaps.
432#[derive(Clone, Debug, Default, PartialEq)]
433struct Landfall {
434    /// The pad of the dragged part, as it is named ("C1 pad 1"), and its clash.
435    copper: Vec<(String, Clash)>,
436    /// The references of the parts whose courtyards it overlaps, and where each is.
437    courtyards: Vec<(String, Point)>,
438}
439impl Landfall {
440    fn is_clear(&self) -> bool {
441        self.copper.is_empty() && self.courtyards.is_empty()
442    }
443    /// The worst of it in a phrase: "short: C1 pad 1 is across U1 pad 1 (OUT)",
444    /// "clearance: C1 pad 2 is 0.120 mm from R2 pad 1 (GND)", "courtyard: C1
445    /// overlaps U1", with how many more there are.
446    fn words(&self, reference: &str) -> Option<String> {
447        let worst = if let Some((pad, clash)) = self.copper.first() {
448            let kind = if clash.crosses() { "short" } else { "clearance" };
449            format!("{kind}: {pad} is {}", clash.words())
450        } else {
451            let (other, _) = self.courtyards.first()?;
452            format!("courtyard: {reference} overlaps {other}")
453        };
454        Some(match self.copper.len() + self.courtyards.len() - 1 {
455            0 => worst,
456            n => format!("{worst}, and {n} more"),
457        })
458    }
459}
460
461/// What a board drag moves. A pad is never one — pressing a pad drags its part.
462#[derive(Clone, Copy, PartialEq, Eq, Debug)]
463enum Subject {
464    /// The whole multi-selection, moved together.
465    Group,
466    Part(Uuid),
467    Via(Uuid),
468    Track(Uuid, Grip),
469    Zone(Uuid, ZoneGrip),
470    Drawing(Uuid),
471    Cutout(Uuid),
472    /// One grab handle of a selected drawing or cutout: a resize.
473    DrawingHandle(Uuid, Handle),
474    CutoutHandle(Uuid, Handle),
475}
476
477/// What a press on a zone takes hold of: one corner, the middle of one edge (a
478/// drag there puts a new corner in), or the whole zone.
479#[derive(Clone, Copy, PartialEq, Eq, Debug)]
480enum ZoneGrip {
481    Corner(usize),
482    Edge(usize),
483    Body,
484}
485
486/// The middle of each edge of a zone's outline, edge `i` running from corner `i`.
487fn edge_middles(outline: &[Point]) -> Vec<Point> {
488    let n = outline.len();
489    (0..n)
490        .map(|i| {
491            let (a, b) = (outline[i], outline[(i + 1) % n]);
492            Point::new(
493                ((i64::from(a.x) + i64::from(b.x)) / 2) as i32,
494                ((i64::from(a.y) + i64::from(b.y)) / 2) as i32,
495            )
496        })
497        .collect()
498}
499
500/// A zone's outline after a drag of `grip` by `delta`, from the outline it had.
501fn dragged_outline(outline: &[Point], grip: ZoneGrip, delta: Point) -> Vec<Point> {
502    let mut out = outline.to_vec();
503    match grip {
504        ZoneGrip::Corner(i) => {
505            if let Some(p) = out.get_mut(i) {
506                *p = p.offset(delta);
507            }
508        }
509        ZoneGrip::Edge(i) => {
510            if let Some(&middle) = edge_middles(outline).get(i) {
511                out.insert(i + 1, middle.offset(delta));
512            }
513        }
514        ZoneGrip::Body => {
515            for p in &mut out {
516                *p = p.offset(delta);
517            }
518        }
519    }
520    out
521}
522
523/// The board with every zone's fill left out: what a fill is made FROM, compared
524/// to say whether the fill on show is still the one the copper asks for.
525fn fill_inputs_match(a: &Board, b: &Board) -> bool {
526    a.outline == b.outline
527        && a.cutouts == b.cutouts
528        && a.layer_count == b.layer_count
529        && a.placements == b.placements
530        && a.tracks == b.tracks
531        && a.vias == b.vias
532        && a.rules == b.rules
533        && a.zones.len() == b.zones.len()
534        && a.zones.iter().zip(&b.zones).all(|(x, y)| {
535            x.id == y.id
536                && x.net == y.net
537                && x.layer == y.layer
538                && x.outline == y.outline
539                && x.thermal_gap == y.thermal_gap
540                && x.spoke_width == y.spoke_width
541                && x.min_width == y.min_width
542        })
543}
544
545/// What the canvas says of a stale fill: zones never filled are "not filled",
546/// a fill that no longer matches the copper is "out of date".
547fn stale_words(board: &Board) -> &'static str {
548    if board.zones.iter().all(|z| z.fill.is_empty()) {
549        "zones not filled · B fills them"
550    } else {
551        "fill out of date · B refills"
552    }
553}
554
555/// A zone fill's report in one line: "GND on B.Cu: 1107.8 mm² in 1 piece; J1.1 3
556/// spokes, J2.1 3 spokes".
557fn zone_words(zone: &Zone, report: &ZoneReport, layer_count: u8, pads: &dyn Fn(CopperRef) -> String) -> String {
558    let head = zones::describe(zone, layer_count);
559    // A netless via this zone left alone because another net's zone holds it
560    // too: the fill keeps clear of it rather than short the two nets through it.
561    let unstitched: String = report
562        .unstitched
563        .iter()
564        .map(|(at, others)| {
565            format!(
566                " The via at {:.2}, {:.2} mm has no net and a {} zone holds it too, so it is stitched to neither.",
567                mm(at.x),
568                mm(at.y),
569                others.join(" and ")
570            )
571        })
572        .collect();
573    if let Some(why) = &report.empty_because {
574        return format!("{head}: nothing filled, because {why}.{unstitched}");
575    }
576    let pieces = match report.pieces {
577        1 => "1 piece".to_owned(),
578        n => format!("{n} pieces"),
579    };
580    let mut words = format!("{head}: {:.1} mm² in {pieces}", report.area / 1e6);
581    if report.islands_removed > 0 {
582        words += &format!(", {} unconnected island(s) removed", report.islands_removed);
583    }
584    let thermals: Vec<String> = report
585        .thermals
586        .iter()
587        .map(|t| match t.spokes {
588            0 => format!("{} not reached", pads(t.owner)),
589            1 => format!("{} 1 spoke", pads(t.owner)),
590            n => format!("{} {n} spokes", pads(t.owner)),
591        })
592        .collect();
593    if !thermals.is_empty() {
594        words += &format!("; thermal reliefs: {}", thermals.join(", "));
595    }
596    words + "." + &unstitched
597}
598
599/// What a routing click landed on.
600#[derive(Clone, Copy, PartialEq)]
601enum Anchor {
602    Pad { layers: (u8, u8), width: i32 },
603    /// A via, and the copper layers it joins.
604    Via { layers: (u8, u8) },
605    Track { layer: u8, width: i32 },
606}
607
608pub(crate) struct BoardView {
609    pub tool: BoardTool,
610    pub selected: Option<BoardSelection>,
611    /// The other selected items, oldest first (owner 2026-11-27: one shared
612    /// multi-selection, a set plus its primary `selected`). They count only
613    /// while `selected` is still `also_primary`, so whatever sets `selected`
614    /// itself selects that alone.
615    also: Vec<BoardSelection>,
616    also_primary: Option<BoardSelection>,
617    /// A box selection being dragged: where it started and what it does.
618    boxing: Option<(Pos2, crate::footprint_editor::BoxMode)>,
619    pan: Vec2,
620    zoom: f32,
621    fitted: bool,
622    pub active_layer: u8,
623    hidden: BTreeSet<u8>,
624    show_ratsnest: bool,
625    /// A move in progress: the document it started from, where the pointer pressed,
626    /// where the dragged thing was, and which thing it is.
627    drag: Option<(Document, Point, Point, Subject)>,
628    /// The pad a dragged free track end is over this frame, if any: drawn as a
629    /// ring while the drag lasts, and named on release when it was refused.
630    landing: Option<Landing>,
631    /// While a PART is dragged: the copper of the board as it was when the drag
632    /// began, whose islands name the net each piece of other copper is on, and
633    /// what the part would come down on where it is now ([`Editor::landfall`]).
634    placing: Option<(Connectivity, Landfall)>,
635    draft: Option<Draft>,
636    diagonal_first: bool,
637    job: Option<RouteJob>,
638    pub message: String,
639    pub(crate) violations: Option<Vec<Violation>>,
640    /// Set when the check ran, for the host to take ([`Editor::take_drc_run`])
641    /// and answer with what only it can measure ([`Editor::add_board_findings`]).
642    pub(crate) drc_ran: bool,
643    /// The finding last clicked in the list, by its index in [`Self::violations`]:
644    /// its row stays selected and its mark on the board is drawn larger.
645    focused_violation: Option<usize>,
646    rules: Option<DesignRules>,
647    outline: Option<(f32, f32)>,
648    net_width: (String, f32),
649    /// The net the Net classes section reads out and assigns when nothing on the
650    /// board with a net is selected, chosen from its own picker.
651    class_net: String,
652    /// A net class name or pattern list being typed that is not (yet) valid, by
653    /// the class's place in the list and the field; the model keeps the last
654    /// valid one, and the Inspector says why this one is not.
655    class_text: BTreeMap<(usize, &'static str), (String, String)>,
656    unrouted: usize,
657    canvas: Rect,
658    /// The Inspector's widgets, `inspector:<thing>`, where [`Editor::board_inspector`]
659    /// last drew them, published with the canvas's hits ([`Editor::board_hits`]).
660    inspector: InspectorHits,
661    toolbar_hits: InspectorHits,
662    /// The canvas's right-click menu's entries, `menuitem:<entry>`, while it is open.
663    menu: Vec<(String, Rect)>,
664    /// The pass the canvas was last drawn in.
665    canvas_pass: u64,
666    /// The corners of a zone being drawn with the Zone tool.
667    zone_draft: Vec<Point>,
668    /// The corners of a line being drawn with the Draw tool.
669    drawing_draft: Vec<Point>,
670    /// The corners of the cutout being drawn with the Cutout tool.
671    cutout_draft: Vec<Point>,
672    /// The layer the Draw and Text tools draw on, and their pen (`None`: the
673    /// layer's standard one).
674    pub(crate) draw_layer: GraphicLayer,
675    pub(crate) draw_width: Option<i32>,
676    /// The net a zone drawn next pours: chosen in the Inspector, GND until then.
677    pub(crate) zone_net: String,
678    /// What each zone's last fill in this session did, by zone.
679    zone_reports: BTreeMap<Uuid, ZoneReport>,
680    /// The board the zones were last filled from, fills left out of the
681    /// comparison ([`fill_inputs_match`]): a board that no longer matches it is
682    /// showing a stale fill. Taken from the first board seen when nothing has
683    /// been filled yet ([`Editor::seed_fill_baseline`]).
684    filled_from: Option<Board>,
685    /// Whether the fill the document was OPENED with already differed from what
686    /// a fill of its copper makes — saved stale, a track drawn after the pour —
687    /// which a comparison with the board as opened cannot see. Cleared by the
688    /// next fill.
689    opened_stale: bool,
690}
691impl Default for BoardView {
692    fn default() -> Self {
693        Self {
694            tool: BoardTool::Select,
695            selected: None,
696            also: vec![],
697            also_primary: None,
698            boxing: None,
699            pan: Vec2::ZERO,
700            zoom: 0.012,
701            fitted: false,
702            active_layer: 0,
703            hidden: BTreeSet::new(),
704            show_ratsnest: true,
705            drag: None,
706            landing: None,
707            placing: None,
708            draft: None,
709            diagonal_first: false,
710            job: None,
711            message: String::new(),
712            violations: None,
713            drc_ran: false,
714            focused_violation: None,
715            rules: None,
716            outline: None,
717            net_width: (String::new(), 0.4),
718            class_net: String::new(),
719            class_text: BTreeMap::new(),
720            unrouted: 0,
721            canvas: Rect::from_min_size(Pos2::ZERO, Vec2::new(800., 600.)),
722            inspector: InspectorHits::default(),
723            toolbar_hits: InspectorHits::default(),
724            menu: vec![],
725            canvas_pass: 0,
726            zone_draft: vec![],
727            drawing_draft: vec![],
728            cutout_draft: vec![],
729            draw_layer: GraphicLayer::FrontSilk,
730            draw_width: None,
731            zone_net: String::new(),
732            zone_reports: BTreeMap::new(),
733            filled_from: None,
734            opened_stale: false,
735        }
736    }
737}
738impl BoardView {
739    /// The board's pan and zoom, as [`crate::Editor::pan_zoom`] reports them.
740    pub(crate) fn pan_zoom(&self) -> (Vec2, f32) {
741        (self.pan, self.zoom)
742    }
743    fn screen(&self, p: Point) -> Pos2 {
744        self.canvas.center() + self.pan + Vec2::new(p.x as f32, p.y as f32) * self.zoom
745    }
746    /// Every selected item, oldest first and the primary last.
747    pub(crate) fn members(&self) -> Vec<BoardSelection> {
748        let mut all = if self.selected.is_some() && self.selected == self.also_primary { self.also.clone() } else { vec![] };
749        all.extend(self.selected);
750        all
751    }
752    pub(crate) fn count(&self) -> usize {
753        self.members().len()
754    }
755    fn is_member(&self, item: BoardSelection) -> bool {
756        self.selected == Some(item) || self.selected == self.also_primary && self.also.contains(&item)
757    }
758    fn set_members(&mut self, mut items: Vec<BoardSelection>) {
759        self.selected = items.pop();
760        self.also = items;
761        self.also_primary = self.selected;
762    }
763    fn add_member(&mut self, item: BoardSelection) {
764        let mut items = self.members();
765        items.retain(|i| *i != item);
766        items.push(item);
767        self.set_members(items);
768    }
769    fn toggle_member(&mut self, item: BoardSelection) {
770        let mut items = self.members();
771        if items.contains(&item) {
772            items.retain(|i| *i != item);
773        } else {
774            items.push(item);
775        }
776        self.set_members(items);
777    }
778    fn world(&self, p: Pos2) -> Point {
779        let v = (p - self.canvas.center() - self.pan) / self.zoom;
780        Point::new(v.x.round() as i32, v.y.round() as i32)
781    }
782    fn px(&self, micrometres: i32) -> f32 {
783        micrometres as f32 * self.zoom
784    }
785    /// Pointer tolerance in micrometres.
786    fn tolerance(&self) -> f64 {
787        f64::from(6. / self.zoom)
788    }
789    fn visible(&self, layer: u8) -> bool {
790        !self.hidden.contains(&layer)
791    }
792    fn fit(&mut self, board: &Board) {
793        let (min, max) = board.outline_bounds();
794        let size = Vec2::new(
795            (max.x - min.x).max(1000) as f32,
796            (max.y - min.y).max(1000) as f32,
797        );
798        let available = self.canvas.size() - Vec2::splat(60.);
799        self.zoom = crate::valid_zoom(
800            (available.x / size.x).min(available.y / size.y).min(0.2),
801            self.zoom,
802        );
803        self.pan = -Vec2::new((min.x + max.x) as f32 / 2., (min.y + max.y) as f32 / 2.) * self.zoom;
804        self.fitted = true;
805    }
806    fn zoom_about(&mut self, factor: f32, anchor: Pos2) {
807        crate::zoom_at(&mut self.zoom, &mut self.pan, factor, anchor - self.canvas.center());
808    }
809    fn centre_on(&mut self, p: Point) {
810        self.pan = -Vec2::new(p.x as f32, p.y as f32) * self.zoom;
811    }
812    /// Centre on a finding at `p` that spans `extent` µm (0 for one at a point),
813    /// zoomed in far enough that [`FOCUS_SPAN`] fills the canvas's shorter side —
814    /// near enough to see the two things a finding is between — and never zoomed
815    /// out for that; but out as far as it takes to show the whole of a finding that
816    /// is longer, such as an unrouted connection's two pads, with 2 mm to spare.
817    fn focus_on(&mut self, p: Point, extent: i32) {
818        let side = self.canvas.size().min_elem();
819        let near = crate::valid_zoom(side / FOCUS_SPAN, self.zoom);
820        let whole = crate::valid_zoom(side / (extent as f32 + 4000.), self.zoom);
821        self.zoom = self.zoom.max(near).min(whole);
822        self.centre_on(p);
823    }
824}
825
826/// How much board, in µm, a click on a design rule finding shows across the canvas's
827/// shorter side ([`BoardView::focus_on`]): 8 mm, a pad pitch or two either side.
828const FOCUS_SPAN: f32 = 8000.;
829
830/// A design rule finding's row in the list: in body text, the kind in its colour and
831/// the message in the text colour. The list is read line by line, and it was 9 pt
832/// red (the eCAD workflow audit's item 16).
833fn finding_row(style: &egui::Style, v: &Violation) -> egui::text::LayoutJob {
834    let body = egui::TextStyle::Body.resolve(style);
835    let color = if matches!(v.kind, ViolationKind::Unrouted | ViolationKind::Stitching | ViolationKind::PinSeat) {
836        style.visuals.warn_fg_color
837    } else {
838        style.visuals.error_fg_color
839    };
840    let mut row = egui::text::LayoutJob::default();
841    row.append(violation_kind(v.kind), 0., egui::TextFormat::simple(body.clone(), color));
842    row.append(&v.message, 8., egui::TextFormat::simple(body, style.visuals.text_color()));
843    row
844}
845
846/// The word a design rule finding's kind is listed under.
847fn violation_kind(kind: ViolationKind) -> &'static str {
848    match kind {
849        ViolationKind::Short => "Short",
850        ViolationKind::Clearance => "Clearance",
851        ViolationKind::TrackWidth => "Width",
852        ViolationKind::BoardEdge => "Edge",
853        ViolationKind::MissingPad => "Pad",
854        ViolationKind::Courtyard => "Courtyard",
855        ViolationKind::AnnularRing => "Ring",
856        ViolationKind::Hole => "Hole",
857        ViolationKind::Stitching => "Stitching",
858        ViolationKind::Unrouted => "Unrouted",
859        ViolationKind::PinSeat => "Seat",
860    }
861}
862
863/// The margin, in µm, that the Fit outline to parts button leaves round the
864/// courtyards.
865const FIT_MARGIN: i32 = 3000;
866
867/// A line for the outline section while the board is still the stock 60 × 40 mm
868/// rectangle every new board starts with and parts are on it: how much of it they
869/// use, beside the button that fits it. `None` for an empty board and for an
870/// outline anyone has changed.
871///
872/// A line rather than a fit of its own: a board that fits itself on the first
873/// placement is too tight for the layout that follows — parts dragged apart land off
874/// it — so the fit stays the user's to ask for once the parts are where they go.
875fn stock_board_note(board: &Board) -> Option<String> {
876    if board.outline != Board::default().outline {
877        return None;
878    }
879    let (min, max) = board
880        .placements
881        .iter()
882        .map(Placement::courtyard)
883        .reduce(|(a, b), (c, d)| {
884            (Point::new(a.x.min(c.x), a.y.min(c.y)), Point::new(b.x.max(d.x), b.y.max(d.y)))
885        })?;
886    Some(format!(
887        "The stock 60 × 40 mm board. Its parts span {:.1} × {:.1} mm: Fit outline to parts sizes it round them.",
888        mm(max.x - min.x),
889        mm(max.y - min.y)
890    ))
891}
892
893/// A board size as it is said: `40 × 21`, in millimetres, to 0.1 mm.
894fn size_words(size: Point) -> String {
895    let words = |v: i32| {
896        let text = format!("{:.1}", mm(v));
897        text.strip_suffix(".0").map_or(text.clone(), str::to_owned)
898    };
899    format!("{} × {}", words(size.x), words(size.y))
900}
901
902fn snap(p: Point, step: i32) -> Point {
903    let round = |v: i32| ((f64::from(v) / f64::from(step)).round() * f64::from(step)) as i32;
904    Point::new(round(p.x), round(p.y))
905}
906pub(crate) fn mm(micrometres: i32) -> f32 {
907    micrometres as f32 / 1000.
908}
909pub(crate) fn um(millimetres: f32) -> i32 {
910    (millimetres * 1000.).round() as i32
911}
912/// Font height for a pad's number, or `None` while the pad is too small on screen to
913/// hold one. The number grows with the pad, as it does in the footprint editor.
914fn pad_number_height(size: Point, zoom: f32) -> Option<f32> {
915    let smallest = size.x.min(size.y) as f32 * zoom;
916    (smallest >= 6.).then(|| (smallest * 0.75).clamp(6., 14.))
917}
918/// How a pad is named in a sentence: `Pad R1.2`, or a mechanical pad, which has
919/// no number to be named by.
920fn pad_title(reference: &str, pad: &Pad) -> String {
921    if pad.number.is_empty() {
922        format!("A mechanical pad of {reference}")
923    } else {
924        format!("Pad {reference}.{}", pad.number)
925    }
926}
927fn via_policy_name(policy: ViaPolicy) -> &'static str {
928    match policy {
929        ViaPolicy::Allow => "Allow",
930        ViaPolicy::Avoid => "Avoid when possible",
931        ViaPolicy::Never => "Never",
932    }
933}
934pub(crate) fn layer_color(layer: u8, count: u8) -> Color32 {
935    if layer == 0 {
936        Color32::from_rgb(214, 64, 64)
937    } else if layer + 1 >= count {
938        Color32::from_rgb(64, 118, 226)
939    } else {
940        [
941            Color32::from_rgb(204, 190, 62),
942            Color32::from_rgb(196, 82, 196),
943            Color32::from_rgb(70, 196, 190),
944            Color32::from_rgb(132, 202, 92),
945        ][usize::from(layer - 1) % 4]
946    }
947}
948/// Move the via `id` by `delta`, taking with it every track end that lands on it.
949///
950/// A via exists to carry one net between layers, so the copper that meets it has to
951/// arrive at wherever it goes; a via that moved alone would leave its own connection
952/// broken. An end counts as meeting the via when its end cap touches or overlaps the
953/// via's land, which is [`Board::connectivity`]'s own join test with its 0.5 µm of
954/// slack dropped: the ends that follow are the ends the board calls connected, give or
955/// take that half micrometre, and routing snaps a click on a via to its centre exactly
956/// so the difference is not reachable by hand.
957///
958/// Only the two ENDS of a track follow. A track that crosses the via has no vertex
959/// there for `simplify_path` to have kept, and bending it at the crossing would deform
960/// a run the user never touched; that crossing shows up as an airwire and, if it is a
961/// different net, as a clearance finding.
962fn move_via(board: &mut Board, id: Uuid, delta: Point) {
963    let count = board.layer_count;
964    let Some((land, (from, to))) = board
965        .vias
966        .iter()
967        .find(|v| v.id == id)
968        .map(|v| (Shape::circle(v.at, v.diameter / 2), v.layers(count)))
969    else {
970        return;
971    };
972    for track in &mut board.tracks {
973        // Only a track on a layer the via joins rests on it.
974        if track.points.is_empty() || !(from..=to).contains(&track.layer) {
975            continue;
976        }
977        let last = track.points.len() - 1;
978        for i in [Some(0), (last > 0).then_some(last)].into_iter().flatten() {
979            if rests_on(&land, track.points[i], track.width) {
980                track.points[i] = track.points[i].offset(delta);
981            }
982        }
983    }
984    if let Some(via) = board.vias.iter_mut().find(|v| v.id == id) {
985        via.at = via.at.offset(delta);
986    }
987}
988
989/// Whether a track end at `end`, `width` wide, rests on `copper`: its end cap and
990/// the copper touch or overlap. This is the one land rule — [`move_via`] asks it of a
991/// via's land, and a track drag asks it of every pad, via and other track — and it is
992/// [`Board::connectivity`]'s join test with the 0.5 µm of slack dropped, so it never
993/// holds an end the board does not already call connected.
994fn rests_on(copper: &Shape, end: Point, width: i32) -> bool {
995    // The cap's own radius is the reach: the copper and the cap touch at that gap.
996    copper.distance_to_point(end) <= f64::from(width / 2)
997}
998
999/// Whether the end of `track` at `end` is HELD: it rests on a pad on the track's
1000/// layer, on a via that reaches the track's layer, or on another track of the same
1001/// layer. A held end is where the run is connected to something, and no track
1002/// gesture moves it.
1003fn held(board: &Board, track: &Track, end: Point) -> bool {
1004    let count = board.layer_count;
1005    let width = track.width;
1006    board
1007        .vias
1008        .iter()
1009        .filter(|v| {
1010            let (from, to) = v.layers(count);
1011            (from..=to).contains(&track.layer)
1012        })
1013        .any(|v| rests_on(&Shape::circle(v.at, v.diameter / 2), end, width))
1014        || board.placements.iter().any(|p| {
1015            p.footprint.pads.iter().any(|pad| {
1016                let layers = p.pad_layers(pad, count);
1017                (layers.0..=layers.1).contains(&track.layer)
1018                    && rests_on(&p.pad_shape(pad), end, width)
1019            })
1020        })
1021        || board
1022            .tracks
1023            .iter()
1024            .filter(|t| t.id != track.id && t.layer == track.layer)
1025            .any(|t| t.segments().any(|s| rests_on(&s, end, width)))
1026}
1027
1028/// What a press grabs of a track: one corner, or one straight segment.
1029#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1030enum Grip {
1031    /// Point `i` of the track: an interior corner, or an end that is not held.
1032    Vertex(usize),
1033    /// The segment from point `k` to point `k + 1`.
1034    Segment(usize),
1035}
1036
1037/// What a press at `q` grabs of `track`. A corner wins within reach of it — the
1038/// pointer tolerance, or the track's own half width when that is larger, so a fat
1039/// track's corner is grabbed anywhere on its rounded join. A HELD end is never a
1040/// corner to grab: a press there takes the segment it ends, which slides without
1041/// letting go of it.
1042fn grip(board: &Board, track: &Track, q: Point, tolerance: f64) -> Option<Grip> {
1043    let points = &track.points;
1044    let last = points.len().checked_sub(1)?;
1045    let reach = tolerance.max(f64::from(track.width / 2));
1046    let gap = |p: Point| f64::from(p.x - q.x).hypot(f64::from(p.y - q.y));
1047    let corner = (0..=last)
1048        .filter(|&i| (i != 0 && i != last) || !held(board, track, points[i]))
1049        .map(|i| (i, gap(points[i])))
1050        .filter(|(_, d)| *d <= reach)
1051        .min_by(|a, b| a.1.total_cmp(&b.1));
1052    if let Some((i, _)) = corner {
1053        return Some(Grip::Vertex(i));
1054    }
1055    track
1056        .segments()
1057        .enumerate()
1058        .map(|(k, s)| (k, s.distance_to_point(q)))
1059        .filter(|(_, d)| *d <= tolerance)
1060        .min_by(|a, b| a.1.total_cmp(&b.1))
1061        .map(|(k, _)| Grip::Segment(k))
1062}
1063
1064/// Where the line through `p` along `e` crosses the line through `q` along `f`, as
1065/// the parameter along `e` (1 is at `p + e`) and the point; `None` when the lines
1066/// meet at less than about 15°. A shallow crossing is not a corner to keep: a slide
1067/// of `s` moves it `s / sin θ` along the neighbour — a 1 mm slide beside a 1°
1068/// neighbour, which an imported arc's facets are, would throw the corner 57 mm.
1069fn meet(p: Point, e: (f64, f64), q: Point, f: (f64, f64)) -> Option<(f64, Point)> {
1070    let cross = e.0 * f.1 - e.1 * f.0;
1071    let lengths = e.0.hypot(e.1) * f.0.hypot(f.1);
1072    if lengths == 0. || (cross / lengths).abs() < 0.25 {
1073        return None;
1074    }
1075    let (wx, wy) = (f64::from(q.x - p.x), f64::from(q.y - p.y));
1076    let u = (wx * f.1 - wy * f.0) / cross;
1077    let at = Point::new(
1078        (f64::from(p.x) + u * e.0).round() as i32,
1079        (f64::from(p.y) + u * e.1).round() as i32,
1080    );
1081    Some((u, at))
1082}
1083
1084/// Edit one track in place and tidy it: a gesture may fold a corner flat or onto its
1085/// neighbour, and a zero-length segment is not a valid track.
1086fn edit_track(board: &mut Board, id: Uuid, edit: impl FnOnce(&Board, &[Point]) -> Vec<Point>) {
1087    let Some(i) = board.tracks.iter().position(|t| t.id == id) else {
1088        return;
1089    };
1090    let points = edit(board, &board.tracks[i].points);
1091    let points = brep_ecad_core::board::simplify_path(points);
1092    if points.len() >= 2 {
1093        board.tracks[i].points = points;
1094    }
1095}
1096
1097/// Slide segment `k` of track `id` sideways by `delta`'s component across it.
1098///
1099/// The segment keeps its direction and its neighbours keep theirs: each end of it
1100/// moves along the neighbouring segment's own line to wherever that line meets the
1101/// moved one, so a run of 90° and 45° corners stays a run of 90° and 45° corners.
1102/// Where a neighbour would have to turn back on itself to do so, that end moves
1103/// straight across instead and the neighbour rubber-bands.
1104///
1105/// An end of the TRACK is different. If it is held — on a pad, a via, or another
1106/// track — it stays exactly where it is and a new corner is added: a 45° leg from
1107/// the held end to the moved segment, or a square one when the segment is too short
1108/// to take the 45°. A free end simply travels with the segment.
1109fn slide_segment(board: &mut Board, id: Uuid, k: usize, delta: Point) {
1110    edit_track(board, id, |board, points| {
1111        let Some(track) = board.tracks.iter().find(|t| t.id == id) else {
1112            return points.to_vec();
1113        };
1114        if k + 1 >= points.len() {
1115            return points.to_vec();
1116        }
1117        let last = points.len() - 1;
1118        let (a, b) = (points[k], points[k + 1]);
1119        let (dx, dy) = (f64::from(b.x - a.x), f64::from(b.y - a.y));
1120        let length = dx.hypot(dy);
1121        if length == 0. {
1122            return points.to_vec();
1123        }
1124        let d = (dx / length, dy / length);
1125        let n = (-d.1, d.0);
1126        let s = f64::from(delta.x) * n.0 + f64::from(delta.y) * n.1;
1127        let m = Point::new((s * n.0).round() as i32, (s * n.1).round() as i32);
1128        if m == Point::new(0, 0) {
1129            return points.to_vec();
1130        }
1131        let hold_a = k == 0 && held(board, track, a);
1132        let hold_b = k + 1 == last && held(board, track, b);
1133        let along = |p: Point, by: f64| {
1134            Point::new(
1135                (f64::from(p.x) + by * d.0).round() as i32,
1136                (f64::from(p.y) + by * d.1).round() as i32,
1137            )
1138        };
1139        let dir = |from: Point, to: Point| (f64::from(to.x - from.x), f64::from(to.y - from.y));
1140        let forward =
1141            |p: Point, q: Point| f64::from(q.x - p.x) * d.0 + f64::from(q.y - p.y) * d.1 > 0.;
1142        let (a_moved, b_moved) = (a.offset(m), b.offset(m));
1143        // Each end of the segment, keeping its neighbour's direction where it can.
1144        let mut start = if hold_a {
1145            along(a_moved, s.abs())
1146        } else if k > 0 {
1147            meet(points[k - 1], dir(points[k - 1], a), a_moved, d)
1148                .filter(|(u, _)| *u > 0.)
1149                .map_or(a_moved, |(_, at)| at)
1150        } else {
1151            a_moved
1152        };
1153        let mut end = if hold_b {
1154            along(b_moved, -s.abs())
1155        } else if k + 1 < last {
1156            meet(points[k + 2], dir(points[k + 2], b), a_moved, d)
1157                .filter(|(u, _)| *u > 0.)
1158                .map_or(b_moved, |(_, at)| at)
1159        } else {
1160            b_moved
1161        };
1162        // A segment that would come out reversed or folded to nothing is moved
1163        // square across instead, which keeps its own length.
1164        if !forward(start, end) {
1165            (start, end) = (a_moved, b_moved);
1166        }
1167        let mut out = points[..k].to_vec();
1168        if hold_a {
1169            out.push(a);
1170        }
1171        out.extend([start, end]);
1172        if hold_b {
1173            out.push(b);
1174        }
1175        out.extend_from_slice(&points[k + 2..]);
1176        out
1177    });
1178}
1179
1180/// Move point `i` of track `id` by `delta`; the two segments meeting it rubber-band.
1181/// Every other track on the same layer whose END rests on that corner comes along, as
1182/// a track's ends come along with a via: a branch joined at a corner stays joined.
1183fn move_vertex(board: &mut Board, id: Uuid, i: usize, delta: Point) {
1184    let Some(track) = board.tracks.iter().find(|t| t.id == id) else {
1185        return;
1186    };
1187    let Some(&corner) = track.points.get(i) else {
1188        return;
1189    };
1190    let (layer, cap) = (track.layer, Shape::circle(corner, track.width / 2));
1191    for other in board
1192        .tracks
1193        .iter_mut()
1194        .filter(|t| t.id != id && t.layer == layer && !t.points.is_empty())
1195    {
1196        let last = other.points.len() - 1;
1197        let mut points = other.points.clone();
1198        for j in [Some(0), (last > 0).then_some(last)].into_iter().flatten() {
1199            if rests_on(&cap, points[j], other.width) {
1200                points[j] = points[j].offset(delta);
1201            }
1202        }
1203        let points = brep_ecad_core::board::simplify_path(points);
1204        if points.len() >= 2 {
1205            other.points = points;
1206        }
1207    }
1208    edit_track(board, id, |_, points| {
1209        let mut points = points.to_vec();
1210        points[i] = points[i].offset(delta);
1211        points
1212    });
1213}
1214
1215/// Where a dragged free END of a track comes down on a pad: which pad, the
1216/// offset that puts the end on that pad's centre, and whether it may go there.
1217#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1218struct Landing {
1219    component: Uuid,
1220    index: usize,
1221    /// From the end's place before the drag to the pad's centre.
1222    delta: Point,
1223    /// The pad is on the track's net, or the track is on no net yet: the end
1224    /// snaps to its centre. `false` is a pad of ANOTHER net (or of none, for a
1225    /// track that has one): the end is not snapped, it keeps its grid step,
1226    /// and whatever it touches there is a short the design rule check reports.
1227    joins: bool,
1228}
1229
1230/// The pad a dragged free end of track `id` is over, when point `i` is an end:
1231/// `moved` is where the pointer has taken the end, BEFORE the grid — a pad
1232/// smaller than a grid step is still caught when the pointer is on it. Only a
1233/// pad on the track's layer counts, the topmost part's first, as `hit_board`
1234/// picks pads. The track's net is read from `document` as it was before the
1235/// drag, where the free end is on nothing and so says nothing about it.
1236fn land_end(document: &Document, id: Uuid, i: usize, moved: Point) -> Option<Landing> {
1237    let board = &document.board;
1238    let track = board.tracks.iter().find(|t| t.id == id)?;
1239    let last = track.points.len().checked_sub(1)?;
1240    if i != 0 && i != last {
1241        return None;
1242    }
1243    let end = track.points[i];
1244    let (placement, index, pad) = board.placements.iter().rev().find_map(|placement| {
1245        placement
1246            .footprint
1247            .pads
1248            .iter()
1249            .enumerate()
1250            .find(|(_, pad)| {
1251                let layers = placement.pad_layers(pad, board.layer_count);
1252                (layers.0..=layers.1).contains(&track.layer)
1253                    && placement.pad_shape(pad).contains(moved)
1254            })
1255            .map(|(index, pad)| (placement, index, pad))
1256    })?;
1257    let centre = placement.transform(pad.at);
1258    let netlist = document.netlist();
1259    let pad_net = brep_ecad_core::board::pin_nets(&netlist)
1260        .get(&(placement.component, pad.number.clone()))
1261        .cloned()
1262        .filter(|_| !pad.number.is_empty());
1263    let joins = match (document.track_nets().get(&id), pad_net) {
1264        (None, _) => true,
1265        (Some(net), Some(pad_net)) => *net == pad_net,
1266        (Some(_), None) => false,
1267    };
1268    Some(Landing {
1269        component: placement.component,
1270        index,
1271        delta: Point::new(centre.x - end.x, centre.y - end.y),
1272        joins,
1273    })
1274}
1275
1276/// Two segments from `a` to `b`: one straight and one at 45°.
1277fn corner(a: Point, b: Point, diagonal_first: bool) -> Vec<Point> {
1278    let (dx, dy) = (b.x - a.x, b.y - a.y);
1279    let d = dx.abs().min(dy.abs());
1280    let bend = if diagonal_first {
1281        Point::new(a.x + d * dx.signum(), a.y + d * dy.signum())
1282    } else {
1283        Point::new(b.x - d * dx.signum(), b.y - d * dy.signum())
1284    };
1285    vec![a, bend, b]
1286}
1287
1288impl Editor {
1289    /// Run the design rule check, as its button does: the zones refilled first
1290    /// (the check is of the copper the board would be made with, and that is a
1291    /// fresh fill), then the board's findings listed. The host adds its own on
1292    /// the next frame ([`Self::take_drc_run`]).
1293    pub fn run_design_rule_check(&mut self) {
1294        if !self.document.board.zones.is_empty() {
1295            let mut reports = vec![];
1296            self.transaction(|d| reports = d.fill_zones());
1297            self.note_filled();
1298            self.zone_reports_words(&reports);
1299        }
1300        self.board_view.violations = Some(self.document.board_drc());
1301        self.board_view.focused_violation = None;
1302        self.board_view.drc_ran = true;
1303    }
1304
1305    /// Whether the design rule check ran since the host last asked. The host
1306    /// answers with the findings it measures itself ([`Self::add_board_findings`]),
1307    /// such as where a placed part's pins land on its pads.
1308    pub fn take_drc_run(&mut self) -> bool {
1309        std::mem::take(&mut self.board_view.drc_ran)
1310    }
1311
1312    /// Add the host's findings to the check's list, after the board's own. Nothing
1313    /// happens while no check has run: a finding is only shown in its list.
1314    pub fn add_board_findings(&mut self, findings: Vec<Violation>) {
1315        if let Some(violations) = self.board_view.violations.as_mut() {
1316            violations.extend(findings);
1317        }
1318    }
1319
1320    pub fn set_view(&mut self, view: View) {
1321        // A wiring diagram has no nets, so it has no board.
1322        if self.view == view || view == View::Board && self.boardless() {
1323            return;
1324        }
1325        self.cancel();
1326        self.view = view;
1327        if view == View::Board {
1328            self.sync_board();
1329        }
1330    }
1331    /// Bring the board in line with the parts and the sheet, the FORCED way: every
1332    /// pads-bearing device the host offers is seated whether or not the offer moved,
1333    /// and the whole standing state is restated, including the components that have no
1334    /// pads and were named once already. What the "Update from parts" button does.
1335    pub fn sync_board(&mut self) {
1336        self.reported_without_pads.clear();
1337        let (sync, refused) = self.follow(true);
1338        self.announce(&sync, &refused);
1339        self.announce_without_pads();
1340    }
1341    /// Bring the board in line with the parts and the sheet, automatically, whenever
1342    /// either could have moved. Called at the top of every frame
1343    /// ([`Editor::show`]) and after every edit ([`Editor::commit`], which runs the
1344    /// second gate alone).
1345    ///
1346    /// # The two gates, and why the sweep is behind them
1347    ///
1348    /// [`brep_ecad_core::Document::sync_board`] walks every component AND every
1349    /// placement, looks each component up in the placements (which is quadratic in a
1350    /// dense board), and repacks whatever it adds. It is not a thing to run sixty
1351    /// times a second, so a frame on which nothing moved pays only the two gates:
1352    ///
1353    /// - [`Editor::offered_mark`], one hash over the host's `parts`, which moves when
1354    ///   the ASSEMBLY gained, lost or re-versioned a device. No edit in this editor
1355    ///   can move it, so an undo cannot make this gate fire and put back what the undo
1356    ///   took away;
1357    /// - [`Editor::board_is_stale`], two id sets over the components and the
1358    ///   placements. No track, no via, no courtyard and no netlist.
1359    ///
1360    /// A pass of its own is one undo step, and correctly not coalesced with anything:
1361    /// the edit it follows is the host's Add Component, which is in the host's history
1362    /// and not in this one.
1363    pub(crate) fn follow_parts(&mut self) {
1364        if self.boardless() {
1365            return;
1366        }
1367        let mark = self.offered_mark();
1368        // A sheet's harness tools seat nothing: a part the user adds there is
1369        // placed by hand, off the board. The offer is read again once the board's
1370        // tools are up, so a part left unplaced is seated then.
1371        let seat = !(self.document.kind == DocumentKind::Sheet && self.harness_tools);
1372        let offer_moved = seat && self.followed_parts != Some(mark);
1373        if seat {
1374            self.followed_parts = Some(mark);
1375        }
1376        // A state already healed once is not healed again, and that is what keeps this
1377        // out of BREP's undo. Undo in the app is `pull` → `set_document` → `show`, not a
1378        // key this editor sees, so an undo that lands on a stale board arrives here as a
1379        // stale board — and a heal that ran again would become a fresh undo entry, and
1380        // the user could never step past the edit that made it stale. So the pass
1381        // remembers the rosters it healed FROM and lets that state alone. The board then
1382        // stays stale until the next edit, which heals it inside its own step
1383        // ([`Editor::commit`]) and is undoable with it.
1384        let stale = self.stale_mark().filter(|m| self.healed_stale != Some(*m));
1385        if offer_moved || stale.is_some() {
1386            if stale.is_some() {
1387                self.healed_stale = stale;
1388            }
1389            let (sync, refused) = self.follow(offer_moved);
1390            self.announce(&sync, &refused);
1391        }
1392        self.announce_without_pads();
1393        // Here and not only in the board view, so a board opened on its sheet
1394        // already says its fill is stale.
1395        self.seed_fill_baseline();
1396    }
1397    /// One pass: seat the offered devices the sheet has not got, if asked, then let the
1398    /// board follow the sheet. Returns what the sweep did and the parts it refused.
1399    fn follow(&mut self, seat: bool) -> (BoardSync, Vec<String>) {
1400        let mut sync = BoardSync::default();
1401        let mut refused = vec![];
1402        let parts = if seat { self.parts.clone() } else { vec![] };
1403        self.transaction(|d| {
1404            for part in parts.into_iter().filter(|p| p.pads.is_some()) {
1405                // A part with neither an occurrence nor a label cannot be told from the
1406                // copy already on the sheet, so it is not seated automatically: every
1407                // pass would put down another one.
1408                if part.source.instance.is_none() && part.reference.is_none() {
1409                    continue;
1410                }
1411                // By occurrence where BOTH sides have one; else by label. A
1412                // component placed before occurrences existed has none, and
1413                // comparing it with the offered one (Some against None) called
1414                // every such part missing and tried to seat it again under the
1415                // label it already has: "J1 is already used by another part",
1416                // on opening the committed ecad-assembly (the eCAD third
1417                // audit's B9).
1418                let present = d.components.iter().any(|c| {
1419                    match (c.part.as_ref().and_then(|s| s.instance.as_ref()), &part.source.instance) {
1420                        (Some(have), Some(offered)) => have == offered,
1421                        _ => part.reference.as_ref() == Some(&c.reference),
1422                    }
1423                });
1424                // Seated where the sheet has room for it, as a part the host seats
1425                // with no pointer is (`Document::open_spot`): parts all put at the
1426                // origin covered one another, and only the one drawn last could be
1427                // clicked. Each part seated here is on the sheet before the next
1428                // asks, so a batch spreads out too.
1429                if present {
1430                    continue;
1431                }
1432                // The host offers occurrences; a card without one is nothing a
1433                // sheet seats (see `Editor::place_here`).
1434                let Some(occurrence) = part.source.instance.clone() else { continue };
1435                let at = d.open_spot(&part.symbol);
1436                if let Err(refusal) = d.place_assembly_component(
1437                    &occurrence, part.source, part.symbol, part.pads, part.reference, at, 0,
1438                ) {
1439                    refused.push(refusal);
1440                }
1441            }
1442            sync = d.sync_board();
1443        });
1444        (sync, refused)
1445    }
1446    /// Whether the host's offer of devices has moved since the last pass: one hash over
1447    /// what a pass reads of each part — which device it is, the version it carries, the
1448    /// label it takes and whether it brings pads. Not the symbol or the footprint: a
1449    /// device whose geometry changed under the same version is the part refresh's
1450    /// business, and hashing it would put every pad of every device on every frame.
1451    ///
1452    /// A hash, not the list, because the list is compared sixty times a second and
1453    /// holding a copy of it would hold a copy of every symbol. Two offers that collide
1454    /// in 64 bits leave the board waiting for the next change or for the button.
1455    fn offered_mark(&self) -> u64 {
1456        use std::hash::{Hash, Hasher};
1457        let mut hasher = std::hash::DefaultHasher::new();
1458        for part in &self.parts {
1459            part.source.instance.hash(&mut hasher);
1460            part.source.key.hash(&mut hasher);
1461            part.source.signature.hash(&mut hasher);
1462            part.reference.hash(&mut hasher);
1463            part.pads.is_some().hash(&mut hasher);
1464        }
1465        hasher.finish()
1466    }
1467    /// Whether the board has fallen behind the sheet — a component wants a placement it
1468    /// has not got, or a placement belongs to a component that is gone — and, when it
1469    /// has, one hash over the two rosters, so a state that has been healed once can be
1470    /// recognised if it comes back.
1471    ///
1472    /// The one question the sweep answers, asked without running it. `None` again the
1473    /// moment a pass has run, which is what keeps the pass inside [`Editor::commit`]
1474    /// from running a second sweep inside the first.
1475    fn stale_mark(&self) -> Option<u64> {
1476        use std::hash::{Hash, Hasher};
1477        if self.boardless() {
1478            return None;
1479        }
1480        let mut wanted: Vec<Uuid> = self
1481            .document
1482            .components
1483            .iter()
1484            .filter(|c| c.pads.is_some() && needs_footprint(c))
1485            .map(|c| c.id)
1486            .collect();
1487        let mut placed: Vec<Uuid> = self
1488            .document
1489            .board
1490            .placements
1491            .iter()
1492            .map(|p| p.component)
1493            .collect();
1494        wanted.sort();
1495        placed.sort();
1496        if wanted == placed {
1497            return None;
1498        }
1499        let mut hasher = std::hash::DefaultHasher::new();
1500        wanted.hash(&mut hasher);
1501        placed.hash(&mut hasher);
1502        Some(hasher.finish())
1503    }
1504    pub(crate) fn board_is_stale(&self) -> bool {
1505        self.stale_mark().is_some()
1506    }
1507    /// Put a pass of the sync to the user, in the board view where the board is.
1508    pub(crate) fn announce(&mut self, sync: &BoardSync, refused: &[String]) {
1509        let mut message = String::new();
1510        if sync.added > 0 || sync.removed > 0 {
1511            message = format!(
1512                "Board updated from parts: {} added, {} removed.",
1513                sync.added, sync.removed
1514            );
1515            self.board_view.fitted = false;
1516        }
1517        // A pass that had to grow the outline says so: the board's size is what a
1518        // fabricator is quoted, and a fitted board that grew in silence was news only
1519        // in the Gerbers (the eCAD re-audit's B10).
1520        // On the sheet too, where a part is usually added and the board's line
1521        // cannot be seen, as the parts with no pads are named there.
1522        if let Some((from, to)) = sync.outline_grew {
1523            let grew = format!(
1524                "No free room was left on the board, so its outline grew from {} to {} mm.",
1525                size_words(from),
1526                size_words(to)
1527            );
1528            message = format!("{message} {grew}").trim_start().to_owned();
1529            self.notice = Some(grew);
1530            self.board_view.outline = None;
1531        }
1532        // Each refusal a sentence of its own: two ran together with no stop
1533        // read as one garbled line.
1534        for refusal in refused {
1535            let stop = if refusal.ends_with(['.', '!', '?']) { "" } else { "." };
1536            message = format!("{message} {refusal}{stop}").trim_start().to_owned();
1537        }
1538        if !message.is_empty() {
1539            self.board_view.message = message;
1540        }
1541    }
1542    /// The components that want a place on the board and have no pads to take one with,
1543    /// in natural order — [`BoardSync::without_pads`], computed here rather than taken
1544    /// from the sweep, because a component with no pads never makes the board STALE and
1545    /// so never runs one.
1546    fn without_pads(&self) -> Vec<String> {
1547        let mut refs: Vec<String> = self
1548            .document
1549            .components
1550            .iter()
1551            .filter(|c| c.pads.is_none() && needs_footprint(c))
1552            .map(|c| c.reference.clone())
1553            .collect();
1554        refs.sort_by(|a, b| footprint::natural_cmp(a, b));
1555        refs
1556    }
1557    /// Name the components that cannot be placed, ONCE each, wherever the user is
1558    /// looking: in the board view's own line, and on the sheet, where the automatic
1559    /// pass usually runs and where the board's line cannot be seen.
1560    ///
1561    /// Once, not once per edit: a part with no pads is a standing state and the sheet
1562    /// is edited all day — the rule `BlockSync::unreported` keeps for an UNLINKED
1563    /// component. A component that gains pads and loses them again is named again,
1564    /// which is right: it is news both times. The forced pass restates the lot.
1565    fn announce_without_pads(&mut self) {
1566        let standing = self.without_pads();
1567        if standing == self.reported_without_pads {
1568            return;
1569        }
1570        let fresh: Vec<&String> = standing
1571            .iter()
1572            .filter(|r| !self.reported_without_pads.contains(r))
1573            .collect();
1574        self.reported_without_pads = standing.clone();
1575        if fresh.is_empty() {
1576            return;
1577        }
1578        let line = format!(
1579            "Not on the board, because their parts have no pads: {}.",
1580            fresh
1581                .iter()
1582                .map(|r| r.as_str())
1583                .collect::<Vec<_>>()
1584                .join(", ")
1585        );
1586        // Once: the forced pass restates the lot over a message that may already
1587        // hold this very line (the third eCAD audit, B9: it read twice).
1588        if !self.board_view.message.contains(&line) {
1589            self.board_view.message = match self.board_view.message.is_empty() {
1590                true => line.clone(),
1591                false => format!("{} {line}", self.board_view.message),
1592            };
1593        }
1594        // A standing state, not a refusal: the sheet's line in the text colour, not
1595        // the warning red a refused edit gets.
1596        self.note = Some(line);
1597    }
1598    /// True while the autorouter is running; the host should avoid replacing documents.
1599    pub fn routing(&self) -> bool {
1600        self.board_view.job.is_some()
1601    }
1602    fn set_board_tool(&mut self, tool: BoardTool) {
1603        if self.board_view.tool != tool {
1604            self.board_view.draft = None;
1605            self.board_view.zone_draft.clear();
1606            self.board_view.drawing_draft.clear();
1607            self.board_view.cutout_draft.clear();
1608            // The drawing tools start from nothing selected, so the Inspector
1609            // shows the layer and pen they draw with.
1610            if matches!(tool, BoardTool::Draw | BoardTool::Text) {
1611                self.board_view.selected = None;
1612            }
1613        }
1614        self.board_view.tool = tool;
1615        if tool == BoardTool::Route && self.board_view.draft.is_none() {
1616            self.route_from_selection();
1617        }
1618    }
1619    /// Arm a track at the selected pad or via, as a Route click on it would: the
1620    /// selection is where the user has said the copper starts. The selection is
1621    /// spent doing so — a Route click never selects, so a pad left selected would
1622    /// arm a second track from the same place the next time Route is chosen.
1623    fn route_from_selection(&mut self) {
1624        let start = match self.board_view.selected {
1625            Some(BoardSelection::Pad(id, index)) => self.pad_anchor(id, index),
1626            Some(BoardSelection::Via(id)) => self
1627                .document
1628                .board
1629                .vias
1630                .iter()
1631                .find(|v| v.id == id)
1632                .map(|v| (v.at, Anchor::Via { layers: v.layers(self.document.board.layer_count) })),
1633            _ => None,
1634        };
1635        if let Some((at, anchor)) = start {
1636            self.board_view.tool = BoardTool::Route;
1637            self.start_draft(at, Some(anchor));
1638            self.board_view.selected = None;
1639        }
1640    }
1641    /// Where a track from pad `index` of `component` starts, and what it starts on.
1642    fn pad_anchor(&self, component: Uuid, index: usize) -> Option<(Point, Anchor)> {
1643        let board = &self.document.board;
1644        let placement = board.placement(component)?;
1645        let pad = placement.footprint.pads.get(index)?;
1646        Some((
1647            placement.transform(pad.at),
1648            Anchor::Pad {
1649                layers: placement.pad_layers(pad, board.layer_count),
1650                width: self.pad_width(component, &pad.number),
1651            },
1652        ))
1653    }
1654    /// The track width a route from a pad starts with: its net's width rule, or the
1655    /// board's default for a pad no net reaches.
1656    fn pad_width(&self, component: Uuid, number: &str) -> i32 {
1657        let board = &self.document.board;
1658        self.document
1659            .netlist()
1660            .nets
1661            .iter()
1662            .find(|n| {
1663                n.pins
1664                    .iter()
1665                    .any(|pin| pin.component_id == component && pin.number == number)
1666            })
1667            .map_or(board.rules.track_width, |n| board.rules.width_for(&n.name))
1668    }
1669    fn choose_layer(&mut self, layer: u8) {
1670        if layer != self.board_view.active_layer {
1671            self.switch_layer(layer);
1672        }
1673    }
1674    pub(crate) fn zoom_board(&mut self, factor: f32) {
1675        let centre = self.board_view.canvas.center();
1676        self.board_view.zoom_about(factor, centre);
1677    }
1678    pub(crate) fn fit_board(&mut self) {
1679        self.board_view.fit(&self.document.board);
1680    }
1681    /// Forget everything in progress on the board, including an autoroute run, for a
1682    /// document loaded by the host.
1683    pub(crate) fn reset_board_gestures(&mut self) {
1684        self.cancel_board();
1685        self.board_view.job = None;
1686        self.board_view.selected = None;
1687        self.board_view.filled_from = None;
1688        self.board_view.opened_stale = false;
1689        self.board_view.zone_reports.clear();
1690    }
1691    pub(crate) fn cancel_board(&mut self) {
1692        let view = &mut self.board_view;
1693        if let Some((before, ..)) = view.drag.take() {
1694            self.document = before;
1695        }
1696        view.placing = None;
1697        view.draft = None;
1698        view.zone_draft.clear();
1699        view.drawing_draft.clear();
1700        view.cutout_draft.clear();
1701        view.rules = None;
1702        view.outline = None;
1703        view.violations = None;
1704        view.tool = BoardTool::Select;
1705    }
1706    /// The reference the schematic gives a placed component, or `?` for a
1707    /// placement whose component the schematic no longer has.
1708    fn reference_of(&self, component: Uuid) -> &str {
1709        self.document
1710            .components
1711            .iter()
1712            .find(|c| c.id == component)
1713            .map_or("?", |c| c.reference.as_str())
1714    }
1715    /// One pad of a placed part, with the part's reference. Every read of a
1716    /// [`BoardSelection::Pad`] comes through here, so an index left behind by a
1717    /// footprint the host has since refreshed answers `None` — the view draws
1718    /// nothing for it and the inspector says the pad is gone, rather than
1719    /// indexing off the end.
1720    fn pad_at(&self, component: Uuid, index: usize) -> Option<(&str, &Pad)> {
1721        let pad = self
1722            .document
1723            .board
1724            .placement(component)?
1725            .footprint
1726            .pads
1727            .get(index)?;
1728        Some((self.reference_of(component), pad))
1729    }
1730    /// One drawn item of a placed part — a silkscreen line, then its graphics,
1731    /// in [`brep_ecad_core::board::Footprint::drawing`]'s order — in BOARD
1732    /// coordinates, its strokes joined, with the part's reference:
1733    /// [`Self::pad_at`]'s twin, and for the same reason — an index left behind
1734    /// by a refreshed footprint answers `None`.
1735    fn silk_at(&self, component: Uuid, index: usize) -> Option<(&str, Vec<Point>)> {
1736        let placement = self.document.board.placement(component)?;
1737        let drawn = placement.footprint.drawing().nth(index)?;
1738        Some((
1739            self.reference_of(component),
1740            drawn.strokes.iter().flatten().map(|p| placement.transform(*p)).collect(),
1741        ))
1742    }
1743    /// What a part's drawn item `index` is called: "silkscreen line 2" for one
1744    /// of its silkscreen lines, "B.Fab drawing 3" for one of its graphics.
1745    fn drawing_name(&self, component: Uuid, index: usize) -> String {
1746        let placement = self.document.board.placement(component);
1747        let silk = placement.map_or(0, |p| p.footprint.silk.len());
1748        match placement.and_then(|p| p.footprint.drawing().nth(index)) {
1749            Some(d) if index >= silk => format!("{} drawing {index}", d.layer.name()),
1750            _ => format!("silkscreen line {index}"),
1751        }
1752    }
1753    /// The net the schematic puts on each of one component's pins, by pin
1754    /// number — the join eCAD makes everywhere: a pad matches the pin of the
1755    /// same number. Built once for a list of pads rather than once per pad,
1756    /// because a netlist is derived from the whole sheet.
1757    fn nets_of(&self, component: Uuid) -> BTreeMap<String, String> {
1758        let mut out = BTreeMap::new();
1759        for net in self.document.netlist().nets {
1760            for pin in net.pins.iter().filter(|pin| pin.component_id == component) {
1761                out.insert(pin.number.clone(), net.name.clone());
1762            }
1763        }
1764        out
1765    }
1766    /// The net on one pad: `None` for a mechanical pad, and for a numbered pad
1767    /// that no net on the sheet reaches.
1768    fn pad_net(&self, component: Uuid, number: &str) -> Option<String> {
1769        if number.is_empty() {
1770            return None;
1771        }
1772        self.nets_of(component).remove(number)
1773    }
1774    /// The selected pad as `(its part, the pad NUMBER)`, or `None` when the
1775    /// selection is not a pad. The board's twin of
1776    /// [`crate::FootprintEditor::selected_pad`]: the number is the identity a
1777    /// pad shares with its pin and with a part's connection point, so it is the
1778    /// whole answer. A MECHANICAL pad answers with an empty number, which is
1779    /// what it has.
1780    /// Every selected board item, oldest first and the primary last, by kind
1781    /// and identity: `("part", reference)`, `("pad", "J1.2")`, `("silk", "J1.0")`,
1782    /// and a track, via, zone, drawing or cutout by its index on the board.
1783    pub fn selected_board_items(&self) -> Vec<(&'static str, String)> {
1784        let b = &self.document.board;
1785        let index = |found: Option<usize>| found.map(|i| i.to_string());
1786        self.board_view.members().into_iter().filter_map(|m| match m {
1787            BoardSelection::Part(id) => Some(("part", self.reference_of(id).to_owned())),
1788            BoardSelection::Pad(id, i) => self.pad_at(id, i).map(|(r, pad)| ("pad", format!("{r}.{}", pad.number))),
1789            BoardSelection::Silk(id, i) => Some(("silk", format!("{}.{i}", self.reference_of(id)))),
1790            BoardSelection::Track(id) => index(b.tracks.iter().position(|t| t.id == id)).map(|i| ("track", i)),
1791            BoardSelection::Via(id) => index(b.vias.iter().position(|v| v.id == id)).map(|i| ("via", i)),
1792            BoardSelection::Zone(id) => index(b.zones.iter().position(|z| z.id == id)).map(|i| ("zone", i)),
1793            BoardSelection::Drawing(id) => index(b.graphics.iter().position(|g| g.id == id)).map(|i| ("drawing", i)),
1794            BoardSelection::Cutout(id) => index(b.cutouts.iter().position(|c| c.id == id)).map(|i| ("cutout", i)),
1795        }).collect()
1796    }
1797    pub fn selected_board_pad(&self) -> Option<(Uuid, &str)> {
1798        match self.board_view.selected {
1799            Some(BoardSelection::Pad(id, index)) => self
1800                .pad_at(id, index)
1801                .map(|(_, pad)| (id, pad.number.as_str())),
1802            _ => None,
1803        }
1804    }
1805    pub fn selected_board_silk(&self) -> Option<(Uuid, usize)> {
1806        match self.board_view.selected {
1807            Some(BoardSelection::Silk(id, index)) => Some((id, index)),
1808            _ => None,
1809        }
1810    }
1811    /// The selected board drawing's index in [`Board::graphics`], or `None`
1812    /// when the selection is not one.
1813    pub fn selected_board_drawing(&self) -> Option<usize> {
1814        match self.board_view.selected {
1815            Some(BoardSelection::Drawing(id)) => self.document.board.graphics.iter().position(|g| g.id == id),
1816            _ => None,
1817        }
1818    }
1819    /// Put `graphic` on the board as one undo step and select it, unless the
1820    /// board would refuse it.
1821    fn add_drawing(&mut self, mut graphic: LayerGraphic) {
1822        graphic.width = self.board_view.draw_width;
1823        if let Some(problem) = graphic.problem() {
1824            self.board_view.message = format!("That {} {problem}.", graphic_kind(&graphic).to_lowercase());
1825            return;
1826        }
1827        let item = BoardGraphic::new(graphic);
1828        let id = item.id;
1829        self.transaction(|d| d.board.graphics.push(item));
1830        self.board_view.selected = Some(BoardSelection::Drawing(id));
1831    }
1832    /// End the line being drawn with the Draw tool: open, or closed when its last
1833    /// corner is its first.
1834    fn finish_drawing(&mut self) {
1835        let points = std::mem::take(&mut self.board_view.drawing_draft);
1836        if points.len() < 2 {
1837            return;
1838        }
1839        let layer = self.board_view.draw_layer;
1840        self.add_drawing(LayerGraphic::new(layer, GraphicShape::Polyline { points }));
1841    }
1842    /// A Draw-tool click: a corner at the grid point under the pointer, or, on
1843    /// the first corner with two already down, the shape closed and finished.
1844    fn drawing_click(&mut self, p: Pos2) {
1845        let q = snap(self.board_view.world(p), PLACE_GRID);
1846        // A new line's first corner lets go of the last thing drawn, so the
1847        // Inspector shows the layer and pen this one is drawn with.
1848        if self.board_view.drawing_draft.is_empty() {
1849            self.board_view.selected = None;
1850        }
1851        let draft = &self.board_view.drawing_draft;
1852        if draft.len() >= 3 && self.board_view.screen(draft[0]).distance(p) <= 8. {
1853            let first = draft[0];
1854            self.board_view.drawing_draft.push(first);
1855            self.finish_drawing();
1856            return;
1857        }
1858        if draft.last() != Some(&q) {
1859            self.board_view.drawing_draft.push(q);
1860        }
1861    }
1862    /// A Text-tool click: "TEXT", 1.5 mm tall, centred on the grid point under
1863    /// the pointer, selected so its words can be typed in the Inspector.
1864    fn text_click(&mut self, p: Pos2) {
1865        let at = snap(self.board_view.world(p), PLACE_GRID);
1866        let layer = self.board_view.draw_layer;
1867        self.add_drawing(LayerGraphic::new(layer, GraphicShape::Text { at, text: "TEXT".into(), height: 1500, angle: 0 }));
1868    }
1869    /// What a board drawing is called where the board names it: "silkscreen
1870    /// text 2" (its place among the board's drawn items).
1871    fn board_drawing_name(&self, id: Uuid) -> String {
1872        let board = &self.document.board;
1873        let Some(n) = board.graphics.iter().position(|g| g.id == id) else {
1874            return "drawing".into();
1875        };
1876        let g = &board.graphics[n].graphic;
1877        format!("{} {} {}", g.layer.name(), graphic_kind(g).to_lowercase(), n + 1)
1878    }
1879    /// The selected cutout's index in [`Board::cutouts`], or `None` when the
1880    /// selection is not one.
1881    pub fn selected_board_cutout(&self) -> Option<usize> {
1882        match self.board_view.selected {
1883            Some(BoardSelection::Cutout(id)) => self.document.board.cutouts.iter().position(|c| c.id == id),
1884            _ => None,
1885        }
1886    }
1887    /// Close the cutout being drawn, as one undo step that refills the zones
1888    /// round it, and select it; unless the board would refuse it, which is said.
1889    fn finish_cutout(&mut self) {
1890        let corners = std::mem::take(&mut self.board_view.cutout_draft);
1891        if corners.len() < 3 {
1892            return;
1893        }
1894        if self.document.board.cutouts.len() >= MAX_CUTOUTS {
1895            self.board_view.message = format!("A board holds at most {MAX_CUTOUTS} cutouts.");
1896            return;
1897        }
1898        if let Some(problem) = self.document.board.cutout_problem(&corners, None) {
1899            self.board_view.message = format!("That cutout {problem}.");
1900            return;
1901        }
1902        let cutout = BoardCutout::new(corners);
1903        let id = cutout.id;
1904        let refill = !self.document.board.zones.is_empty();
1905        self.transaction(|d| {
1906            d.board.cutouts.push(cutout);
1907            if refill {
1908                d.fill_zones();
1909            }
1910        });
1911        if refill {
1912            self.note_filled();
1913        }
1914        self.board_view.tool = BoardTool::Select;
1915        self.board_view.selected = Some(BoardSelection::Cutout(id));
1916    }
1917    /// A Cutout-tool click: a corner at the grid point under the pointer, or, on
1918    /// the first corner with three already down, the cutout closed.
1919    fn cutout_click(&mut self, p: Pos2) {
1920        let q = snap(self.board_view.world(p), PLACE_GRID);
1921        if self.board_view.cutout_draft.is_empty() {
1922            self.board_view.selected = None;
1923        }
1924        let draft = &self.board_view.cutout_draft;
1925        if draft.len() >= 3 && self.board_view.screen(draft[0]).distance(p) <= 8. {
1926            self.finish_cutout();
1927            return;
1928        }
1929        if draft.last() != Some(&q) {
1930            self.board_view.cutout_draft.push(q);
1931        }
1932    }
1933    /// What a cutout is called where the board names it: "cutout 2".
1934    fn board_cutout_name(&self, id: Uuid) -> String {
1935        match self.document.board.cutouts.iter().position(|c| c.id == id) {
1936            Some(n) => format!("cutout {}", n + 1),
1937            None => "cutout".into(),
1938        }
1939    }
1940    /// The selected zone's index on the board, or `None` when the selection is not a zone.
1941    pub fn selected_board_zone(&self) -> Option<usize> {
1942        match self.board_view.selected {
1943            Some(BoardSelection::Zone(id)) => self.document.board.zones.iter().position(|z| z.id == id),
1944            _ => None,
1945        }
1946    }
1947    /// The spokes each relieved pad got in zone `id`'s last fill this session, in
1948    /// the fill's order, with the pad's name: `None` until it has been filled here.
1949    pub fn zone_spokes(&self, id: Uuid) -> Option<Vec<(String, u8)>> {
1950        let report = self.board_view.zone_reports.get(&id)?;
1951        Some(report.thermals.iter().map(|t| (self.copper_name(t.owner), t.spokes)).collect())
1952    }
1953    /// The board's Inspector message, "" when there is none: what the last board action said.
1954    pub fn board_message(&self) -> &str { &self.board_view.message }
1955    /// Select pad `number` of the placed component `component`, and say whether
1956    /// there was one. The [`crate::FootprintEditor::select_pad`] twin, for a
1957    /// host lighting one connection point up on every surface it appears on. A
1958    /// pad outside the canvas is brought into view, because a highlight nobody
1959    /// can see is not one; a pad already on screen does not move the board.
1960    /// Selecting is not an edit: [`Editor::take_change`] reports nothing.
1961    pub fn select_board_pad(&mut self, component: Uuid, number: &str) -> bool {
1962        // A mechanical pad has no name, so nothing can ask for it by one. It is
1963        // still selected by a click, and still says what it is.
1964        if number.is_empty() {
1965            return false;
1966        }
1967        let Some(placement) = self.document.board.placement(component) else {
1968            return false;
1969        };
1970        let Some(index) = placement
1971            .footprint
1972            .pads
1973            .iter()
1974            .position(|pad| pad.number == number)
1975        else {
1976            return false;
1977        };
1978        let at = placement.transform(placement.footprint.pads[index].at);
1979        self.board_view.selected = Some(BoardSelection::Pad(component, index));
1980        if !self
1981            .board_view
1982            .canvas
1983            .shrink(12.)
1984            .contains(self.board_view.screen(at))
1985        {
1986            self.board_view.centre_on(at);
1987        }
1988        true
1989    }
1990    fn edit_part(&mut self, id: Uuid, edit: impl FnOnce(&mut Placement)) {
1991        self.transaction(|d| {
1992            if let Some(p) = d.board.placements.iter_mut().find(|p| p.component == id) {
1993                edit(p);
1994            }
1995        });
1996    }
1997    /// Every item a box can take: parts, tracks, vias, zones, drawings, cutouts.
1998    fn board_items(&self) -> Vec<BoardSelection> {
1999        let b = &self.document.board;
2000        b.placements.iter().map(|p| BoardSelection::Part(p.component))
2001            .chain(b.tracks.iter().map(|t| BoardSelection::Track(t.id)))
2002            .chain(b.vias.iter().map(|v| BoardSelection::Via(v.id)))
2003            .chain(b.zones.iter().map(|z| BoardSelection::Zone(z.id)))
2004            .chain(b.graphics.iter().map(|g| BoardSelection::Drawing(g.id)))
2005            .chain(b.cutouts.iter().map(|c| BoardSelection::Cutout(c.id)))
2006            .collect()
2007    }
2008    /// The board points an item covers: a part's origin and pads, a track's
2009    /// corners, a via, a zone's or cutout's corners, a drawing's points.
2010    fn board_item_points(&self, item: BoardSelection) -> Vec<Point> {
2011        let b = &self.document.board;
2012        match item {
2013            BoardSelection::Part(id) | BoardSelection::Pad(id, _) | BoardSelection::Silk(id, _) => b.placement(id).map(|p| {
2014                p.footprint.pads.iter().map(|pad| p.transform(pad.at)).chain(std::iter::once(p.at)).collect()
2015            }).unwrap_or_default(),
2016            BoardSelection::Track(id) => b.tracks.iter().find(|t| t.id == id).map(|t| t.points.clone()).unwrap_or_default(),
2017            BoardSelection::Via(id) => b.vias.iter().find(|v| v.id == id).map(|v| vec![v.at]).unwrap_or_default(),
2018            BoardSelection::Zone(id) => b.zones.iter().find(|z| z.id == id).map(|z| z.outline.clone()).unwrap_or_default(),
2019            BoardSelection::Drawing(id) => b.graphics.iter().find(|g| g.id == id).map(|g| grips::graphic_points(&g.graphic.shape)).unwrap_or_default(),
2020            BoardSelection::Cutout(id) => b.cutouts.iter().find(|c| c.id == id).map(|c| c.points.clone()).unwrap_or_default(),
2021        }
2022    }
2023    /// Apply a box drawn over `area` (screen): left to right takes the items
2024    /// wholly inside it, right to left those it touches.
2025    fn board_box_select(&mut self, area: Rect, crossing: bool, mode: crate::footprint_editor::BoxMode) {
2026        use crate::footprint_editor::BoxMode;
2027        let caught: Vec<BoardSelection> = self.board_items().into_iter().filter(|item| {
2028            let points: Vec<Pos2> = self.board_item_points(*item).into_iter().map(|p| self.board_view.screen(p)).collect();
2029            !points.is_empty() && if crossing {
2030                area.intersects(Rect::from_points(&points).expand(1.))
2031            } else {
2032                points.iter().all(|p| area.contains(*p))
2033            }
2034        }).collect();
2035        let mut items = if mode == BoxMode::Replace { vec![] } else { self.board_view.members() };
2036        for item in caught {
2037            items.retain(|i| *i != item);
2038            if mode != BoxMode::Remove {
2039                items.push(item);
2040            }
2041        }
2042        self.board_view.set_members(items);
2043    }
2044    /// The distinct parts of a multi-selection (a pad or a silk line counts as its part).
2045    fn group_parts(members: &[BoardSelection]) -> Vec<Uuid> {
2046        let mut parts: Vec<Uuid> = members.iter().filter_map(|m| part_of(Some(*m))).collect();
2047        parts.dedup();
2048        parts.sort();
2049        parts.dedup();
2050        parts
2051    }
2052    /// Move every selected item by `delta`: tracks first, then vias (whose
2053    /// track ends follow, as a via's do), parts, zones, drawings, cutouts.
2054    fn move_board_group(board: &mut Board, members: &[BoardSelection], delta: Point) {
2055        for m in members {
2056            if let BoardSelection::Track(id) = m
2057                && let Some(t) = board.tracks.iter_mut().find(|t| t.id == *id)
2058            {
2059                t.points.iter_mut().for_each(|p| *p = p.offset(delta));
2060            }
2061        }
2062        for m in members {
2063            match *m {
2064                BoardSelection::Via(id) => move_via(board, id, delta),
2065                BoardSelection::Zone(id) => {
2066                    if let Some(z) = board.zones.iter_mut().find(|z| z.id == id) {
2067                        z.outline.iter_mut().for_each(|p| *p = p.offset(delta));
2068                        z.fill.clear();
2069                    }
2070                }
2071                BoardSelection::Drawing(id) => {
2072                    if let Some(g) = board.graphics.iter_mut().find(|g| g.id == id) {
2073                        move_graphic(&mut g.graphic, delta);
2074                    }
2075                }
2076                BoardSelection::Cutout(id) => {
2077                    if let Some(c) = board.cutouts.iter_mut().find(|c| c.id == id) {
2078                        c.points.iter_mut().for_each(|p| *p = p.offset(delta));
2079                    }
2080                }
2081                _ => {}
2082            }
2083        }
2084        for id in Self::group_parts(members) {
2085            if let Some(p) = board.placements.iter_mut().find(|p| p.component == id) {
2086                p.at = p.at.offset(delta);
2087            }
2088        }
2089    }
2090    /// The placement-grid point nearest the middle of the selection's extent.
2091    fn group_centre(&self) -> Option<Point> {
2092        let points: Vec<Point> = self.board_view.members().into_iter().flat_map(|m| self.board_item_points(m)).collect();
2093        let lo = Point::new(points.iter().map(|p| p.x).min()?, points.iter().map(|p| p.y).min()?);
2094        let hi = Point::new(points.iter().map(|p| p.x).max()?, points.iter().map(|p| p.y).max()?);
2095        Some(snap(Point::new(((i64::from(lo.x) + i64::from(hi.x)) / 2) as i32, ((i64::from(lo.y) + i64::from(hi.y)) / 2) as i32), PLACE_GRID))
2096    }
2097    /// R with several items selected: turn them all a quarter turn about the
2098    /// group's middle, one undo step: parts go round it and turn, tracks, vias,
2099    /// zones, drawings and cutouts go round it. Not made, and said, when a
2100    /// cutout would leave the board or meet another.
2101    fn rotate_board_group(&mut self) {
2102        let members = self.board_view.members();
2103        let Some(about) = self.group_centre() else { return };
2104        let turn = |p: Point| Point::new(p.x - about.x, p.y - about.y).rotate(1).offset(about);
2105        let before = self.document.clone();
2106        let board = &mut self.document.board;
2107        for m in &members {
2108            match *m {
2109                BoardSelection::Track(id) => if let Some(t) = board.tracks.iter_mut().find(|t| t.id == id) {
2110                    t.points.iter_mut().for_each(|p| *p = turn(*p));
2111                },
2112                BoardSelection::Via(id) => if let Some(v) = board.vias.iter_mut().find(|v| v.id == id) {
2113                    v.at = turn(v.at);
2114                },
2115                BoardSelection::Zone(id) => if let Some(z) = board.zones.iter_mut().find(|z| z.id == id) {
2116                    z.outline.iter_mut().for_each(|p| *p = turn(*p));
2117                    z.fill.clear();
2118                },
2119                BoardSelection::Drawing(id) => if let Some(g) = board.graphics.iter_mut().find(|g| g.id == id) {
2120                    match &mut g.graphic.shape {
2121                        GraphicShape::Circle { center, .. } => *center = turn(*center),
2122                        shape => {
2123                            grips::turn_graphic(shape, about);
2124                        }
2125                    }
2126                },
2127                BoardSelection::Cutout(id) => if let Some(c) = board.cutouts.iter_mut().find(|c| c.id == id) {
2128                    c.points.iter_mut().for_each(|p| *p = turn(*p));
2129                },
2130                _ => {}
2131            }
2132        }
2133        for id in Self::group_parts(&members) {
2134            if let Some(p) = board.placements.iter_mut().find(|p| p.component == id) {
2135                p.at = turn(p.at);
2136                p.rotation = (p.rotation + 1) % 4;
2137            }
2138        }
2139        if let Some(words) = self.group_cutout_refusal("turned") {
2140            self.document = before;
2141            self.board_view.message = words;
2142            return;
2143        }
2144        self.refill_after_group(&before, &members);
2145        self.commit(before, None);
2146        self.board_view.set_members(members);
2147    }
2148    /// A cutout the group edit left off the board or on another, in words.
2149    fn group_cutout_refusal(&self, what: &str) -> Option<String> {
2150        let board = &self.document.board;
2151        board.cutouts.iter().enumerate().find_map(|(n, c)| {
2152            board.cutout_problem(&c.points, Some(n)).map(|why| format!("Not {what}: cutout {} {why}.", n + 1))
2153        })
2154    }
2155    /// Refill the zones, inside the same undo step, when a zone or cutout of the group moved.
2156    fn refill_after_group(&mut self, before: &Document, members: &[BoardSelection]) {
2157        let moved = members.iter().any(|m| matches!(m, BoardSelection::Zone(_) | BoardSelection::Cutout(_)));
2158        if moved && !self.document.board.zones.is_empty() && before.board != self.document.board {
2159            let reports = self.document.fill_zones();
2160            self.note_filled();
2161            self.zone_reports_words(&reports);
2162        }
2163    }
2164    /// F with several items selected: every selected part turns over to the
2165    /// other side, mirrored across the group's middle, one undo step. Tracks,
2166    /// vias and drawings stay where they are, and the status says so.
2167    fn flip_group(&mut self) {
2168        let members = self.board_view.members();
2169        let parts = Self::group_parts(&members);
2170        if parts.is_empty() {
2171            self.board_view.message = "Flip side turns parts over: select a part.".into();
2172            return;
2173        }
2174        if self.document.board.layer_count < 2 {
2175            self.board_view.message = "Add a second copper layer to mount parts on the bottom.".into();
2176            return;
2177        }
2178        let Some(about) = self.group_centre() else { return };
2179        self.transaction(|d| {
2180            for id in &parts {
2181                if let Some(p) = d.board.placements.iter_mut().find(|p| p.component == *id) {
2182                    // A pad lies at R(rotation)·mirror?·local + at; mirrored across
2183                    // the line x = about.x that is R(-rotation)·(other side)·local
2184                    // + the mirrored origin, so the turn reverses with the side.
2185                    p.bottom = !p.bottom;
2186                    p.rotation = (4 - p.rotation % 4) % 4;
2187                    p.at = Point::new(2 * about.x - p.at.x, p.at.y);
2188                }
2189            }
2190        });
2191        if parts.len() < members.len() {
2192            self.board_view.message = format!(
2193                "{} turned over; the tracks, vias, zones and drawings selected with them stay where they are.",
2194                crate::count(parts.len(), "part", "parts")
2195            );
2196        }
2197        self.board_view.set_members(members);
2198    }
2199    /// Delete with several items selected: every track, via, zone, drawing,
2200    /// cutout and part of it, one undo step. A selected pad or silk line is its
2201    /// part's footprint's and is left.
2202    fn delete_group(&mut self) {
2203        let members = self.board_view.members();
2204        let refill = members.iter().any(|m| matches!(m, BoardSelection::Zone(_) | BoardSelection::Cutout(_)))
2205            && !self.document.board.zones.is_empty();
2206        self.transaction(|d| {
2207            for m in &members {
2208                match *m {
2209                    BoardSelection::Track(id) => d.board.tracks.retain(|t| t.id != id),
2210                    BoardSelection::Via(id) => d.board.vias.retain(|v| v.id != id),
2211                    BoardSelection::Zone(id) => d.board.zones.retain(|z| z.id != id),
2212                    BoardSelection::Drawing(id) => d.board.graphics.retain(|g| g.id != id),
2213                    BoardSelection::Cutout(id) => d.board.cutouts.retain(|c| c.id != id),
2214                    BoardSelection::Part(id) => d.delete_component(id),
2215                    BoardSelection::Pad(..) | BoardSelection::Silk(..) => {}
2216                }
2217            }
2218            if refill {
2219                d.fill_zones();
2220            }
2221        });
2222        if refill {
2223            self.note_filled();
2224        }
2225        self.board_view.selected = None;
2226        self.board_view.also.clear();
2227    }
2228    /// Ctrl/Cmd+A on the board: select every part, track, via, zone, drawing and cutout.
2229    pub(crate) fn select_all_board(&mut self) {
2230        let all = self.board_items();
2231        self.board_view.set_members(all);
2232    }
2233    fn rotate_part(&mut self) {
2234        if let Some(id) = part_of(self.board_view.selected) {
2235            self.edit_part(id, |p| p.rotation = (p.rotation + 1) % 4);
2236        }
2237    }
2238    /// Whether the selection is a cutout, or a drawing that looks different
2239    /// turned (text turns its letters; a circle looks the same turned).
2240    fn turnable_drawing_or_cutout(&self) -> bool {
2241        let board = &self.document.board;
2242        match self.board_view.selected {
2243            Some(BoardSelection::Cutout(id)) => board.cutouts.iter().any(|c| c.id == id),
2244            Some(BoardSelection::Drawing(id)) => board.graphics.iter().any(|g| {
2245                g.id == id && !matches!(g.graphic.shape, GraphicShape::Circle { .. })
2246            }),
2247            _ => false,
2248        }
2249    }
2250    /// R: a part turns as it always has; a drawing or a cutout turns a quarter
2251    /// turn in place, about [`grips::pivot`] (its middle). A
2252    /// cutout that would leave the board or meet another is not turned, and
2253    /// says so, as a moved one is put back.
2254    fn rotate_selection(&mut self) {
2255        if self.board_view.count() > 1 {
2256            return self.rotate_board_group();
2257        }
2258        let board = &self.document.board;
2259        match self.board_view.selected {
2260            Some(BoardSelection::Drawing(id)) => {
2261                let Some(k) = board.graphics.iter().position(|g| g.id == id) else { return };
2262                let mut graphic = board.graphics[k].graphic.clone();
2263                let Some(about) = grips::pivot(&grips::graphic_points(&graphic.shape)) else { return };
2264                if !grips::turn_graphic(&mut graphic.shape, about) {
2265                    return;
2266                }
2267                if let Some(problem) = graphic.problem() {
2268                    self.board_view.message =
2269                        format!("Not turned: that {} {problem}.", graphic_kind(&graphic).to_lowercase());
2270                    return;
2271                }
2272                self.transaction(|d| d.board.graphics[k].graphic = graphic);
2273            }
2274            Some(BoardSelection::Cutout(id)) => {
2275                let Some(k) = board.cutouts.iter().position(|c| c.id == id) else { return };
2276                let mut points = board.cutouts[k].points.clone();
2277                let Some(about) = grips::pivot(&points) else { return };
2278                if !grips::turn_points(&mut points, about) {
2279                    self.board_view.message = format!("Not turned: cutout {} would leave the drawing area.", k + 1);
2280                    return;
2281                }
2282                if let Some(why) = board.cutout_problem(&points, Some(k)) {
2283                    self.board_view.message = format!("Not turned: cutout {} {why}.", k + 1);
2284                    return;
2285                }
2286                let before = self.document.clone();
2287                self.document.board.cutouts[k].points = points;
2288                // Copper keeps clear of the cutout where it now is, inside the
2289                // same undo step, as after a move.
2290                if !self.document.board.zones.is_empty() {
2291                    self.document.fill_zones();
2292                    self.note_filled();
2293                }
2294                self.commit(before, None);
2295            }
2296            _ => self.rotate_part(),
2297        }
2298    }
2299    fn flip_part(&mut self) {
2300        if self.board_view.count() > 1 {
2301            return self.flip_group();
2302        }
2303        if let Some(id) = part_of(self.board_view.selected) {
2304            if self.document.board.layer_count < 2 {
2305                self.board_view.message =
2306                    "Add a second copper layer to mount parts on the bottom.".into();
2307                return;
2308            }
2309            self.edit_part(id, |p| p.bottom = !p.bottom);
2310        }
2311    }
2312    fn delete_board_selection(&mut self) {
2313        if self.board_view.count() > 1 {
2314            return self.delete_group();
2315        }
2316        match self.board_view.selected {
2317            Some(BoardSelection::Track(id)) => {
2318                self.transaction(|d| d.board.tracks.retain(|t| t.id != id));
2319                self.board_view.selected = None;
2320            }
2321            Some(BoardSelection::Via(id)) => {
2322                self.transaction(|d| d.board.vias.retain(|v| v.id != id));
2323                self.board_view.selected = None;
2324            }
2325            Some(BoardSelection::Zone(id)) => {
2326                self.transaction(|d| {
2327                    d.board.zones.retain(|z| z.id != id);
2328                    d.fill_zones();
2329                });
2330                self.note_filled();
2331                self.board_view.selected = None;
2332            }
2333            Some(BoardSelection::Part(id)) => {
2334                self.transaction(|d| d.delete_component(id));
2335                self.board_view.selected = None;
2336            }
2337            Some(BoardSelection::Drawing(id)) => {
2338                self.transaction(|d| d.board.graphics.retain(|g| g.id != id));
2339                self.board_view.selected = None;
2340            }
2341            Some(BoardSelection::Cutout(id)) => {
2342                let refill = !self.document.board.zones.is_empty();
2343                self.transaction(|d| {
2344                    d.board.cutouts.retain(|c| c.id != id);
2345                    if refill {
2346                        d.fill_zones();
2347                    }
2348                });
2349                if refill {
2350                    self.note_filled();
2351                }
2352                self.board_view.selected = None;
2353            }
2354            // A pad is a copy of its part's footprint, refreshed from the part:
2355            // deleting it here would come back at the next refresh, and deleting
2356            // the whole part is not what a click on one pad asked for.
2357            Some(BoardSelection::Pad(id, index)) => {
2358                let what = self
2359                    .pad_at(id, index)
2360                    .map_or_else(|| "That pad".to_owned(), |(r, pad)| pad_title(r, pad));
2361                self.board_view.message = format!(
2362                    "{what} belongs to its part's footprint. Edit the pads on the part, in the Pads workbench; Delete here removes a track, a via or a whole part."
2363                );
2364            }
2365            // The same for a silkscreen line, for the same reason.
2366            Some(BoardSelection::Silk(id, index)) => {
2367                let reference = self.reference_of(id).to_owned();
2368                let name = self.drawing_name(id, index);
2369                self.board_view.message = format!(
2370                    "That {name} belongs to {reference}'s footprint. Edit it on the part, in the Pads workbench; Delete here removes a track, a via or a whole part."
2371                );
2372            }
2373            None => {}
2374        }
2375    }
2376    /// The pad a thermal relief is on, as the Inspector names it: "J1.1".
2377    fn copper_name(&self, owner: CopperRef) -> String {
2378        match owner {
2379            CopperRef::Pad { placement, pad } => {
2380                let Some(placement) = self.document.board.placements.get(placement) else {
2381                    return "?".into();
2382                };
2383                let number = placement.footprint.pads.get(pad).map_or("?", |p| p.number.as_str());
2384                format!("{}.{number}", self.reference_of(placement.component))
2385            }
2386            CopperRef::Via(_) => "via".into(),
2387            CopperRef::Track { .. } => "track".into(),
2388        }
2389    }
2390    /// Remember the board the zones were just filled from.
2391    fn note_filled(&mut self) {
2392        self.board_view.filled_from = Some(self.document.board.clone());
2393        self.board_view.opened_stale = false;
2394    }
2395    /// The first sight of a board with zones since it was loaded: take it as the
2396    /// baseline later edits are compared with, and ask ONCE whether the fill it
2397    /// came with is what its copper asks for ([`Board::zones_stale`], a refill of
2398    /// a copy: about a tenth of a second on a 40 × 30 mm board). A fill saved
2399    /// stale is marked stale on open, with no edit made and nothing written.
2400    pub(crate) fn seed_fill_baseline(&mut self) {
2401        if self.board_view.filled_from.is_some() || self.document.board.zones.is_empty() {
2402            return;
2403        }
2404        self.note_filled();
2405        self.board_view.opened_stale = self.document.board.zones_stale(&self.document.netlist());
2406        if self.board_view.opened_stale {
2407            // Said where the board's line is read, not only drawn on the canvas.
2408            let line = if self.document.board.zones.iter().all(|z| z.fill.is_empty()) {
2409                "The zones are not filled yet. Fill zones (B) pours them."
2410            } else {
2411                "The zones' fill was saved out of date: copper changed after it was filled, so it may cross a track \
2412                 or leave a pad cut off. Fill zones (B) refills it; the fabrication and STEP exports refill a copy."
2413            };
2414            self.board_view.message = match self.board_view.message.is_empty() {
2415                true => line.to_owned(),
2416                false => format!("{} {line}", self.board_view.message),
2417            };
2418        }
2419    }
2420    /// Whether the zones' fill on show is not the one the copper asks for: it was
2421    /// opened so, or copper has moved since it was made, and the fill may cross it
2422    /// or leave a pad cut off.
2423    /// The design rule check's findings as the Inspector lists them, each by the
2424    /// word it is listed under, its message and where on the board it is (what a
2425    /// click on its row zooms to); `None` until the check has run (and again once
2426    /// an edit has hidden them).
2427    pub fn board_findings(&self) -> Option<Vec<(&'static str, String, Point)>> {
2428        self.board_view
2429            .violations
2430            .as_ref()
2431            .map(|v| v.iter().map(|v| (violation_kind(v.kind), v.message.clone(), v.at)).collect())
2432    }
2433    pub fn zones_stale(&self) -> bool {
2434        !self.document.board.zones.is_empty()
2435            && (self.board_view.opened_stale
2436                || self
2437                    .board_view
2438                    .filled_from
2439                    .as_ref()
2440                    .is_some_and(|b| !fill_inputs_match(b, &self.document.board)))
2441    }
2442    /// Refill every zone, as one undo step, and say what each fill did.
2443    pub(crate) fn fill_zones(&mut self) {
2444        let mut reports = vec![];
2445        self.transaction(|d| reports = d.fill_zones());
2446        self.note_filled();
2447        let words = self.zone_reports_words(&reports);
2448        self.board_view.message = match words.len() {
2449            0 => "There are no zones to fill.".into(),
2450            _ => format!("Zones filled. {}", words.join(" ")),
2451        };
2452    }
2453    /// Each report in a line, remembered for the Inspector.
2454    fn zone_reports_words(&mut self, reports: &[ZoneReport]) -> Vec<String> {
2455        let count = self.document.board.layer_count;
2456        let mut words = vec![];
2457        for report in reports {
2458            if let Some(zone) = self.document.board.zones.iter().find(|z| z.id == report.zone) {
2459                words.push(zone_words(zone, report, count, &|owner| self.copper_name(owner)));
2460            }
2461        }
2462        for report in reports {
2463            self.board_view.zone_reports.insert(report.zone, report.clone());
2464        }
2465        words
2466    }
2467    /// The nets a zone can pour, in the netlist's order.
2468    fn net_names(&self) -> Vec<String> {
2469        self.document.netlist().nets.into_iter().map(|n| n.name).collect()
2470    }
2471    /// The net the next zone pours: the one chosen, else GND, else the first net.
2472    fn zone_net(&self) -> Option<String> {
2473        let nets = self.net_names();
2474        if nets.contains(&self.board_view.zone_net) {
2475            return Some(self.board_view.zone_net.clone());
2476        }
2477        nets.iter()
2478            .find(|n| n.eq_ignore_ascii_case("GND"))
2479            .or(nets.first())
2480            .cloned()
2481    }
2482    /// Close the zone being drawn, on the active layer, pouring the chosen net;
2483    /// fill it; and select it, so its corners can be dragged straight away.
2484    fn finish_zone(&mut self) {
2485        let corners = std::mem::take(&mut self.board_view.zone_draft);
2486        if corners.len() < 3 {
2487            return;
2488        }
2489        let Some(net) = self.zone_net() else {
2490            self.board_view.message =
2491                "A zone pours a net, and the schematic has none yet: connect some pins first.".into();
2492            return;
2493        };
2494        let layer = self.board_view.active_layer.min(self.document.board.layer_count - 1);
2495        let zone = Zone::new(&net, layer, corners);
2496        if zones::ring_area(&zone.outline) == 0. {
2497            self.board_view.message = "A zone needs corners that enclose an area.".into();
2498            return;
2499        }
2500        let id = zone.id;
2501        let mut reports = vec![];
2502        self.transaction(|d| {
2503            d.board.zones.push(zone);
2504            reports = d.fill_zones();
2505        });
2506        self.note_filled();
2507        let words = self.zone_reports_words(&reports);
2508        self.board_view.tool = BoardTool::Select;
2509        self.board_view.selected = Some(BoardSelection::Zone(id));
2510        let index = self.document.board.zones.iter().position(|z| z.id == id);
2511        self.board_view.message = index
2512            .and_then(|k| words.get(k).cloned())
2513            .unwrap_or_default();
2514    }
2515    /// A Zone-tool click: a corner at the grid point under the pointer, or, on the
2516    /// first corner with three already down, the zone closed.
2517    fn zone_click(&mut self, p: Pos2) {
2518        let q = snap(self.board_view.world(p), PLACE_GRID);
2519        let draft = &self.board_view.zone_draft;
2520        if draft.len() >= 3 && self.board_view.screen(draft[0]).distance(p) <= 8. {
2521            self.finish_zone();
2522            return;
2523        }
2524        if draft.last() != Some(&q) {
2525            self.board_view.zone_draft.push(q);
2526        }
2527    }
2528    /// What a press at `q` takes of the SELECTED zone: a corner, an edge's middle,
2529    /// or the zone.
2530    fn zone_grip(&self, id: Uuid, p: Pos2) -> Option<ZoneGrip> {
2531        let zone = self.document.board.zones.iter().find(|z| z.id == id)?;
2532        let view = &self.board_view;
2533        let near = |q: Point| view.screen(q).distance(p) <= 7.;
2534        if let Some(i) = zone.outline.iter().position(|&q| near(q)) {
2535            return Some(ZoneGrip::Corner(i));
2536        }
2537        if view.selected == Some(BoardSelection::Zone(id))
2538            && let Some(i) = edge_middles(&zone.outline).into_iter().position(near)
2539        {
2540            return Some(ZoneGrip::Edge(i));
2541        }
2542        Some(ZoneGrip::Body)
2543    }
2544    fn start_autoroute(&mut self) {
2545        let netlist = self.document.netlist();
2546        self.cancel_board();
2547        self.board_view.job = Some(RouteJob::new(&self.document.board, &netlist));
2548    }
2549    fn poll_autoroute(&mut self, ctx: &egui::Context) {
2550        let Some(mut job) = self.board_view.job.take() else {
2551            return;
2552        };
2553        let progress = job.step(ROUTE_BUDGET);
2554        ctx.request_repaint();
2555        let mut cancel = false;
2556        egui::Modal::new(egui::Id::new("autoroute-progress")).show(ctx, |ui| {
2557            ui.set_min_width(320.);
2558            ui.heading("Autorouting");
2559            let settled = progress.completed_nets + progress.failed_nets;
2560            let fraction = if progress.total_nets == 0 {
2561                1.
2562            } else {
2563                settled as f32 / progress.total_nets as f32
2564            };
2565            ui.add(egui::ProgressBar::new(fraction).show_percentage());
2566            ui.label(format!(
2567                "{settled} of {} · {} · {:.2} mm grid",
2568                crate::count(progress.total_nets, "net", "nets"),
2569                crate::count(progress.rip_ups, "rip-up", "rip-ups"),
2570                mm(job.pitch())
2571            ));
2572            if progress.removing_vias {
2573                ui.label("Rerouting nets to remove vias they no longer need…");
2574            }
2575            if ui.button("Cancel autoroute").clicked() {
2576                cancel = true;
2577            }
2578        });
2579        if cancel {
2580            self.board_view.message = "Autoroute cancelled; no copper was added.".into();
2581        } else if progress.done {
2582            let outcome = job.outcome();
2583            let (tracks, vias) = (outcome.tracks.len(), outcome.vias.len());
2584            self.board_view.message = if outcome.unrouted.is_empty() {
2585                format!("Autoroute complete: {tracks} tracks and {vias} vias added.")
2586            } else {
2587                format!(
2588                    "Autoroute added {tracks} tracks and {vias} vias. Unrouted nets: {}. Try moving parts apart, a finer grid, or narrower tracks.",
2589                    outcome.unrouted.join(", ")
2590                )
2591            };
2592            self.transaction(|d| outcome.apply(&mut d.board));
2593        } else {
2594            self.board_view.job = Some(job);
2595        }
2596    }
2597
2598    pub(crate) fn board_toolbar(&mut self, ui: &mut egui::Ui) {
2599        ui.horizontal_wrapped(|ui| {
2600            self.view_switch(ui);
2601            self.action_buttons(ui, ActionGroup::Tool);
2602            ui.separator();
2603            self.action_buttons(ui, ActionGroup::History);
2604            ui.separator();
2605            self.action_buttons(ui, ActionGroup::Zoom);
2606            ui.separator();
2607            let count = self.document.board.layer_count;
2608            let mut layer = self.board_view.active_layer.min(count - 1);
2609            let layers: Vec<&'static Action<Editor>> = crate::actions::actions()
2610                .filter(|a| a.group == ActionGroup::Layer && a.offered(self))
2611                .collect();
2612            let labels: Vec<_> = layers.iter().map(|action| action.caption(self)).collect();
2613            let choices: Vec<_> = layers.iter().zip(&labels).enumerate()
2614                .map(|(l, (action, label))| (l as u8, action.id, label.as_str())).collect();
2615            self.board_view.toolbar_hits.begin(ui.ctx());
2616            self.board_view.toolbar_hits.enum_dropdown(ui, "active_layer", &choices, &mut layer);
2617            if layer != self.board_view.active_layer {
2618                self.run_action(layers[usize::from(layer)].id);
2619            }
2620        });
2621        ui.horizontal_wrapped(|ui| {
2622            match self.board_view.tool {
2623                BoardTool::Select => {
2624                    ui.label("Drag parts and vias to place them, and a track by a corner or a segment to reshape it — its ends stay on the pads and vias they meet, and a free end dropped on a pad of its net snaps to the pad's centre. Select a pad and press X to route from it. A selected drawing or cutout is sized by its handles (Shift keeps proportions). R rotates, right-drag pans.");
2625                }
2626                BoardTool::Route => {
2627                    ui.label(if self.board_view.draft.is_some() {
2628                        "Click to add corners; click a pad or copper to finish."
2629                    } else {
2630                        "Click a pad to start a track."
2631                    });
2632                }
2633                BoardTool::Zone => {
2634                    ui.label("Click the zone's corners; click the first again, double-click or press Enter to close it. It pours the net chosen in the Inspector.");
2635                }
2636                BoardTool::Draw => {
2637                    ui.label("Click the line's corners on the layer chosen in the Inspector; double-click or press Enter to end it, or click the first corner to close it.");
2638                }
2639                BoardTool::Text => {
2640                    ui.label("Click where the text goes, on the layer chosen in the Inspector; then type its words there.");
2641                }
2642                BoardTool::Cutout => {
2643                    ui.label("Click the cutout's corners inside the board outline; click the first again, double-click or press Enter to close it. It is milled through the board.");
2644                }
2645            }
2646            self.action_buttons(ui, ActionGroup::Context);
2647        });
2648    }
2649
2650    pub(crate) fn board_panel(&mut self, ui: &mut egui::Ui) {
2651        ui.add_space(8.);
2652        ui.heading("Assembly parts");
2653        if ui.button("Update from parts").clicked() {
2654            self.sync_board();
2655        }
2656        let references: BTreeMap<Uuid, (String, String)> = self
2657            .document
2658            .components
2659            .iter()
2660            .map(|c| (c.id, (c.reference.clone(), c.value.clone())))
2661            .collect();
2662        let mut parts: Vec<(String, Uuid, String)> = self
2663            .document
2664            .board
2665            .placements
2666            .iter()
2667            .map(|p| {
2668                let reference = references.get(&p.component).map_or("?", |r| r.0.as_str());
2669                let package = p.footprint.name.rsplit(':').next().unwrap_or("");
2670                (reference.to_owned(), p.component, package.to_owned())
2671            })
2672            .collect();
2673        parts.sort_by(|a, b| footprint::natural_cmp(&a.0, &b.0));
2674        let mut chosen = None;
2675        egui::ScrollArea::vertical()
2676            .id_salt("board-parts")
2677            .max_height((ui.available_height() * 0.55).max(80.))
2678            .show(ui, |ui| {
2679                if parts.is_empty() {
2680                    ui.small("Add native parts with pads to the assembly, then update the board.");
2681                }
2682                for (reference, id, package) in &parts {
2683                    // A pad's part is lit here too: the selection is one thing seen
2684                    // from two distances, and a list that went blank when a pad was
2685                    // picked would read as having lost it.
2686                    let selected = part_of(self.board_view.selected) == Some(*id);
2687                    let response =
2688                        ui.selectable_label(selected, format!("{reference}  ·  {package}"));
2689                    if response.clicked() {
2690                        chosen = Some(*id);
2691                    }
2692                }
2693            });
2694        if let Some(id) = chosen {
2695            self.board_view.selected = Some(BoardSelection::Part(id));
2696            if let Some(p) = self.document.board.placement(id) {
2697                let at = p.at;
2698                self.board_view.centre_on(at);
2699            }
2700        }
2701        ui.separator();
2702        ui.heading("Layers");
2703        let count = self.document.board.layer_count;
2704        for layer in 0..count {
2705            ui.horizontal(|ui| {
2706                let (swatch, _) = ui.allocate_exact_size(Vec2::splat(12.), Sense::hover());
2707                ui.painter()
2708                    .rect_filled(swatch, 2., layer_color(layer, count));
2709                let mut visible = self.board_view.visible(layer);
2710                if ui
2711                    .checkbox(&mut visible, layer_name(layer, count))
2712                    .changed()
2713                {
2714                    if visible {
2715                        self.board_view.hidden.remove(&layer);
2716                    } else {
2717                        self.board_view.hidden.insert(layer);
2718                    }
2719                }
2720                if self.board_view.active_layer == layer {
2721                    ui.small(egui::RichText::new("active").color(accent(ui)));
2722                }
2723            });
2724        }
2725        ui.checkbox(&mut self.board_view.show_ratsnest, "Ratsnest");
2726    }
2727
2728    pub(crate) fn board_inspector(&mut self, ui: &mut egui::Ui) {
2729        self.board_view.inspector.begin(ui.ctx());
2730        ui.add_space(12.);
2731        ui.heading("Properties");
2732        ui.add_space(8.);
2733        if self.board_view.count() > 1 {
2734            let words = ui.small(format!(
2735                "{} items selected: R turns them about their middle, F turns their parts over, Delete removes them, a drag moves them. These are the last one picked's.",
2736                self.board_view.count()
2737            ));
2738            self.board_view.inspector.mark("group", &words);
2739        }
2740        match self.board_view.selected {
2741            Some(BoardSelection::Part(id)) => self.part_inspector(ui, id),
2742            Some(BoardSelection::Pad(id, index)) => self.pad_inspector(ui, id, index),
2743            Some(BoardSelection::Silk(id, index)) => self.silk_inspector(ui, id, index),
2744            Some(BoardSelection::Track(id)) => {
2745                if let Some(t) = self
2746                    .document
2747                    .board
2748                    .tracks
2749                    .iter()
2750                    .find(|t| t.id == id)
2751                    .cloned()
2752                {
2753                    let length: f64 = t
2754                        .points
2755                        .windows(2)
2756                        .map(|s| f64::from(s[1].x - s[0].x).hypot(f64::from(s[1].y - s[0].y)))
2757                        .sum();
2758                    let net = self.document.track_nets().get(&id).cloned();
2759                    ui.label(egui::RichText::new("Track").color(accent(ui)));
2760                    ui.small(format!(
2761                        "{} · {:.2} mm long · {}",
2762                        layer_name(t.layer, self.document.board.layer_count),
2763                        length / 1000.,
2764                        net.as_deref().map_or_else(
2765                            || "no net".to_owned(),
2766                            |n| format!("{n} ({})", self.document.board.rules.class_of(Some(n)).name)
2767                        )
2768                    ));
2769                    ui.horizontal(|ui| {
2770                        ui.label("Width");
2771                        let mut width = mm(t.width);
2772                        let field = ui
2773                            .add(
2774                                egui::DragValue::new(&mut width)
2775                                    .speed(0.01)
2776                                    .range(0.05..=5.0)
2777                                    .fixed_decimals(3)
2778                                    .suffix(" mm"),
2779                            )
2780                            .on_hover_text("Run the design rule check after widening copper.");
2781                        self.board_view.inspector.mark("track_width", &field);
2782                        if field.changed() {
2783                            self.transaction_as(Some(format!("track:{id}:width")), |d| {
2784                                let _ = d.set_track_width(id, um(width));
2785                            });
2786                        }
2787                        if t.fixed_width {
2788                            ui.small(egui::RichText::new("set here").color(accent(ui)));
2789                        }
2790                    });
2791                    if t.fixed_width {
2792                        let follow = ui
2793                            .button(match &net {
2794                                Some(net) => format!("Follow {net}'s width"),
2795                                None => "Follow the default width".into(),
2796                            })
2797                            .on_hover_text("Hand this track back to its net's width rule.");
2798                        self.board_view.inspector.mark("follow_net_width", &follow);
2799                        if follow.clicked() {
2800                            self.transaction(|d| d.follow_net_width(id));
2801                        }
2802                    }
2803                    let for_net = net.as_ref().map(|net| {
2804                        ui.button(format!("Use this width for {net}")).on_hover_text(
2805                            "Set the net's width rule and give every track on it this width.",
2806                        )
2807                    });
2808                    if let Some(button) = &for_net {
2809                        self.board_view.inspector.mark("width_for_net", button);
2810                    }
2811                    if let Some(net) = net
2812                        && for_net.is_some_and(|b| b.clicked())
2813                    {
2814                        let width = t.width;
2815                        let mut changed = 0;
2816                        self.transaction(|d| {
2817                            d.board.rules.net_widths.insert(net.clone(), width);
2818                            changed = d.apply_net_widths();
2819                        });
2820                        self.board_view.message = format!(
2821                            "{net} is {:.3} mm wide: {changed} tracks changed.",
2822                            mm(width)
2823                        );
2824                    }
2825                    let delete = ui.button("Delete track");
2826                    self.board_view.inspector.mark("delete", &delete);
2827                    if delete.clicked() {
2828                        self.delete_board_selection();
2829                    }
2830                }
2831            }
2832            Some(BoardSelection::Via(id)) => {
2833                let count = self.document.board.layer_count;
2834                if let Some(v) = self.document.board.vias.iter().find(|v| v.id == id).cloned() {
2835                    let kind = match v.kind(count) {
2836                        ViaKind::Through => "Through via",
2837                        ViaKind::Blind => "Blind via",
2838                        ViaKind::Buried => "Buried via",
2839                    };
2840                    ui.label(egui::RichText::new(kind).color(accent(ui)));
2841                    ui.small(format!(
2842                        "{:.2} mm pad · {:.2} mm drill at {:.2}, {:.2} mm",
2843                        mm(v.diameter),
2844                        mm(v.drill),
2845                        mm(v.at.x),
2846                        mm(v.at.y)
2847                    ));
2848                    // The layers it joins: every layer for a through via; a blind
2849                    // via reaches one outer layer, a buried one neither. Offered
2850                    // only where there is an inner layer to stop at.
2851                    if count > 2 {
2852                        let (mut from, mut to) = v.layers(count);
2853                        let ids: Vec<_> = (0..count).map(|l| l.to_string()).collect();
2854                        let labels: Vec<_> = (0..count).map(|l| layer_name(l, count)).collect();
2855                        let choices = |range: std::ops::Range<u8>| -> Vec<(u8, &str, &str)> {
2856                            range.map(|l| (l, ids[l as usize].as_str(), labels[l as usize].as_str())).collect()
2857                        };
2858                        ui.horizontal(|ui| {
2859                            ui.label("From");
2860                            self.board_view.inspector.enum_dropdown(ui, "via_from", &choices(0..to), &mut from);
2861                        });
2862                        ui.horizontal(|ui| {
2863                            ui.label("To");
2864                            self.board_view.inspector.enum_dropdown(ui, "via_to", &choices(from + 1..count), &mut to);
2865                        });
2866                        if (from, to) != v.layers(count) {
2867                            let span = (from, to);
2868                            self.transaction(|d| {
2869                                if let Some(via) = d.board.vias.iter_mut().find(|via| via.id == id) {
2870                                    via.span = (span != (0, count - 1)).then_some(span);
2871                                }
2872                            });
2873                        }
2874                    }
2875                    let delete = ui.button("Delete via");
2876                    self.board_view.inspector.mark("delete", &delete);
2877                    if delete.clicked() {
2878                        self.delete_board_selection();
2879                    }
2880                }
2881            }
2882            Some(BoardSelection::Zone(id)) => self.zone_inspector(ui, id),
2883            Some(BoardSelection::Drawing(id)) => self.drawing_inspector(ui, id),
2884            Some(BoardSelection::Cutout(id)) => self.cutout_inspector(ui, id),
2885            None if self.board_view.tool == BoardTool::Zone => self.new_zone_inspector(ui),
2886            None if self.board_view.tool == BoardTool::Cutout => self.new_cutout_inspector(ui),
2887            None if matches!(self.board_view.tool, BoardTool::Draw | BoardTool::Text) => self.new_drawing_inspector(ui),
2888            None => {
2889                ui.label(
2890                    "Select a part, a pad, a silkscreen line, a track, a via, a zone, a drawn item or a cutout to see it here.",
2891                );
2892            }
2893        }
2894        if !self.board_view.message.is_empty() {
2895            ui.add_space(6.);
2896            ui.label(
2897                egui::RichText::new(&self.board_view.message)
2898                    .small()
2899                    .color(accent(ui)),
2900            );
2901        }
2902        ui.add_space(10.);
2903        ui.separator();
2904        egui::ScrollArea::vertical()
2905            .id_salt("board-setup")
2906            .show(ui, |ui| {
2907                self.routing_section(ui);
2908                ui.separator();
2909                self.drc_section(ui);
2910                ui.separator();
2911                let outline = egui::CollapsingHeader::new("Board outline and layers")
2912                    .default_open(true)
2913                    .show(ui, |ui| self.outline_section(ui));
2914                self.board_view.inspector.mark("outline_section", &outline.header_response);
2915                let rules = egui::CollapsingHeader::new("Design rules")
2916                    .default_open(false)
2917                    .show(ui, |ui| self.rules_section(ui));
2918                self.board_view.inspector.mark("rules_section", &rules.header_response);
2919                let classes = egui::CollapsingHeader::new("Net classes")
2920                    .default_open(false)
2921                    .show(ui, |ui| self.net_classes_section(ui));
2922                self.board_view.inspector.mark("net_classes_section", &classes.header_response);
2923            });
2924    }
2925    /// The net picker a zone is given its net with: every net on the sheet.
2926    fn net_combo(&mut self, ui: &mut egui::Ui, salt: &str, current: &str) -> Option<String> {
2927        let mut chosen = None;
2928        let combo = egui::ComboBox::from_id_salt(salt)
2929            .selected_text(if current.is_empty() { "no net" } else { current })
2930            .show_ui(ui, |ui| {
2931                for net in self.net_names() {
2932                    if ui.selectable_label(net == current, &net).clicked() {
2933                        chosen = Some(net);
2934                    }
2935                }
2936            });
2937        self.board_view.inspector.mark(salt, &combo.response);
2938        chosen.filter(|n| n != current)
2939    }
2940    /// The Inspector while the Zone tool is in hand and nothing is selected: the
2941    /// net the zone will pour and the layer it goes on, before its first corner.
2942    fn new_zone_inspector(&mut self, ui: &mut egui::Ui) {
2943        ui.label(egui::RichText::new("New zone").color(accent(ui)));
2944        let count = self.document.board.layer_count;
2945        let layer = layer_name(self.board_view.active_layer.min(count - 1), count);
2946        let Some(net) = self.zone_net() else {
2947            ui.small("The schematic has no nets yet: connect some pins, then draw the zone.");
2948            return;
2949        };
2950        ui.horizontal(|ui| {
2951            ui.label("Net");
2952            if let Some(net) = self.net_combo(ui, "zone_net", &net) {
2953                self.board_view.zone_net = net;
2954            }
2955        });
2956        ui.small(format!(
2957            "On {layer}, the active copper layer. {} corner(s) placed; the zone is filled as soon as it is closed.",
2958            self.board_view.zone_draft.len()
2959        ));
2960        if self.board_view.zone_draft.len() >= 3 {
2961            let close = ui.button("Close zone");
2962            self.board_view.inspector.mark("close_zone", &close);
2963            if close.clicked() {
2964                self.finish_zone();
2965            }
2966        }
2967    }
2968    /// The Inspector while the Draw or Text tool is in hand and nothing is
2969    /// selected: the layer it draws on and its pen.
2970    fn new_drawing_inspector(&mut self, ui: &mut egui::Ui) {
2971        let text = self.board_view.tool == BoardTool::Text;
2972        ui.label(egui::RichText::new(if text { "New text" } else { "New line" }).color(accent(ui)));
2973        let mut layer = self.board_view.draw_layer;
2974        ui.horizontal(|ui| {
2975            self.board_view.inspector.enum_dropdown(ui, "draw_layer", &board_layers(), &mut layer);
2976            ui.label("Draw on");
2977        });
2978        if layer != self.board_view.draw_layer {
2979            self.board_view.draw_layer = layer;
2980            self.board_view.draw_width = None;
2981        }
2982        let mut width = mm(self.board_view.draw_width.unwrap_or(layer.default_width()));
2983        ui.horizontal(|ui| {
2984            ui.label("Pen width");
2985            let field = ui.add(egui::DragValue::new(&mut width).speed(0.01).range(0.001..=10.0).max_decimals(3).suffix(" mm"));
2986            self.board_view.inspector.mark("pen_width", &field);
2987        });
2988        let width = um(width);
2989        self.board_view.draw_width = (width != layer.default_width()).then_some(width);
2990        ui.small(match layer {
2991            GraphicLayer::FrontSilk | GraphicLayer::BackSilk => "Silkscreen: printed on its side's legend film, back text mirrored so it reads from the back.",
2992            _ => "Fabrication drawing: shown in the editors, never manufactured.",
2993        });
2994        if !text {
2995            let n = self.board_view.drawing_draft.len();
2996            ui.small(format!("{n} corner(s) placed."));
2997            if n >= 2 {
2998                let finish = ui.button("Finish line");
2999                self.board_view.inspector.mark("finish_line", &finish);
3000                if finish.clicked() {
3001                    self.finish_drawing();
3002                }
3003            }
3004        }
3005    }
3006    /// The Inspector while the Cutout tool is in hand: the corners placed so
3007    /// far, and the button that closes the cutout.
3008    fn new_cutout_inspector(&mut self, ui: &mut egui::Ui) {
3009        ui.label(egui::RichText::new("New cutout").color(accent(ui)));
3010        let n = self.board_view.cutout_draft.len();
3011        ui.small(format!(
3012            "A hole milled through the board (Edge.Cuts), wholly inside its outline. {n} corner(s) placed."
3013        ));
3014        if n >= 3 {
3015            let close = ui.button("Close cutout");
3016            self.board_view.inspector.mark("close_cutout", &close);
3017            if close.clicked() {
3018                self.finish_cutout();
3019            }
3020        }
3021    }
3022    /// A selected cutout: its size and corners, and Delete. Drag it on the
3023    /// canvas to move it.
3024    fn cutout_inspector(&mut self, ui: &mut egui::Ui, id: Uuid) {
3025        let Some(cutout) = self.document.board.cutouts.iter().find(|c| c.id == id).cloned() else {
3026            return;
3027        };
3028        let mut name = self.board_cutout_name(id);
3029        name[..1].make_ascii_uppercase();
3030        ui.label(egui::RichText::new(name).color(accent(ui)));
3031        let area = zones::ring_area(&cutout.points).abs() / 1e6;
3032        ui.small(format!(
3033            "Milled through the board · {} corners · {area:.2} mm². Copper keeps {:.2} mm from it, as from the outline; drag it to move it.",
3034            cutout.points.len(),
3035            mm(self.document.board.rules.edge_clearance)
3036        ));
3037        let delete = ui.button("Delete cutout");
3038        self.board_view.inspector.mark("delete", &delete);
3039        if delete.clicked() {
3040            self.delete_board_selection();
3041        }
3042    }
3043    /// A selected board drawing: the shared drawn-item fields, each change one
3044    /// undo step (a field held under drag is one step).
3045    fn drawing_inspector(&mut self, ui: &mut egui::Ui, id: Uuid) {
3046        let Some(item) = self.document.board.graphics.iter().find(|g| g.id == id).cloned() else {
3047            return;
3048        };
3049        ui.label(egui::RichText::new(self.board_drawing_name(id)).color(accent(ui)));
3050        ui.small("Drawn on the board itself, owned by no part.");
3051        let mut graphic = item.graphic.clone();
3052        edit_graphic(ui, &mut self.board_view.inspector, &mut graphic, &board_layers());
3053        if graphic != item.graphic {
3054            if let Some(problem) = graphic.problem() {
3055                self.board_view.message = format!("Not changed: the {} {problem}.", graphic_kind(&graphic).to_lowercase());
3056            } else {
3057                self.transaction_as(Some(format!("drawing:{id}:edit")), |d| {
3058                    if let Some(g) = d.board.graphics.iter_mut().find(|g| g.id == id) {
3059                        g.graphic = graphic;
3060                    }
3061                });
3062            }
3063        }
3064        let delete = ui.button("Delete");
3065        self.board_view.inspector.mark("delete", &delete);
3066        if delete.clicked() {
3067            self.delete_board_selection();
3068        }
3069    }
3070    /// A selected zone: what its fill did, its net, its layer and its fill rules,
3071    /// each change refilled at once.
3072    fn zone_inspector(&mut self, ui: &mut egui::Ui, id: Uuid) {
3073        let Some(zone) = self.document.board.zones.iter().find(|z| z.id == id).cloned() else {
3074            return;
3075        };
3076        let count = self.document.board.layer_count;
3077        ui.label(egui::RichText::new("Zone").color(accent(ui)));
3078        let holes: usize = zone.fill.iter().map(|p| p.holes.len()).sum();
3079        // An empty fill is "no fill", not "-0.0 mm² filled in 0 piece(s)".
3080        let fill = if zone.fill.is_empty() {
3081            "no fill".to_owned()
3082        } else {
3083            format!("{:.1} mm² filled in {} piece(s), {holes} hole(s)", zone.fill_area() / 1e6, zone.fill.len())
3084        };
3085        ui.small(format!("{} · {} corners · {fill}", zones::describe(&zone, count), zone.outline.len()));
3086        // The last fill's thermal reliefs, unless the line under the Inspector
3087        // is saying exactly that already.
3088        if let Some(report) = self.board_view.zone_reports.get(&id).cloned() {
3089            let words = zone_words(&zone, &report, count, &|owner| self.copper_name(owner));
3090            if !self.board_view.message.contains(&words) {
3091                ui.small(words);
3092            }
3093        }
3094        if self.zones_stale() {
3095            ui.label(
3096                egui::RichText::new(
3097                    "The fill is out of date: copper has changed since it was filled. Fill zones (B) refills it; so does the design rule check.",
3098                )
3099                .small()
3100                .color(WARNING),
3101            );
3102        }
3103        let mut edit: Option<Box<dyn FnOnce(&mut Zone)>> = None;
3104        let mut settle = false;
3105        ui.horizontal(|ui| {
3106            ui.label("Net");
3107            if let Some(net) = self.net_combo(ui, "zone_net", &zone.net) {
3108                edit = Some(Box::new(move |z| z.net = net));
3109                settle = true;
3110            }
3111        });
3112        ui.horizontal(|ui| {
3113            ui.label("Layer");
3114            let mut layer = zone.layer;
3115            let ids: Vec<_> = (0..count).map(|l| l.to_string()).collect();
3116            let labels: Vec<_> = (0..count).map(|l| layer_name(l, count)).collect();
3117            let choices: Vec<_> = ids.iter().zip(&labels).enumerate()
3118                .map(|(l, (id, label))| (l as u8, id.as_str(), label.as_str())).collect();
3119            self.board_view.inspector.enum_dropdown(ui, "zone_layer", &choices, &mut layer);
3120            if layer != zone.layer {
3121                edit = Some(Box::new(move |z| z.layer = layer));
3122                settle = true;
3123            }
3124        });
3125        for (key, label, value, hint) in [
3126            ("thermal_gap", "Thermal gap", zone.thermal_gap, "The gap round a through-hole pad of the zone's net, bridged by spokes. At least the clearance of the net's class."),
3127            ("spoke_width", "Spoke width", zone.spoke_width, "The width of each thermal spoke."),
3128            ("min_width", "Minimum width", zone.min_width, "Fill narrower than this is left out."),
3129        ] {
3130            ui.horizontal(|ui| {
3131                ui.label(label);
3132                let mut v = mm(value);
3133                let field = ui
3134                    .add(
3135                        egui::DragValue::new(&mut v)
3136                            .speed(0.01)
3137                            .range(0.05..=10.0)
3138                            .fixed_decimals(3)
3139                            .suffix(" mm"),
3140                    )
3141                    .on_hover_text(hint);
3142                self.board_view.inspector.mark(key, &field);
3143                if field.changed() && um(v) != value {
3144                    let v = um(v);
3145                    edit = Some(Box::new(move |z| match key {
3146                        "thermal_gap" => z.thermal_gap = v,
3147                        "spoke_width" => z.spoke_width = v,
3148                        _ => z.min_width = v,
3149                    }));
3150                    // A drag refills once, when it is let go; a typed value or an
3151                    // arrow key at once.
3152                    settle = !field.dragged();
3153                }
3154                if field.drag_stopped() {
3155                    settle = true;
3156                }
3157            });
3158        }
3159        if let Some(edit) = edit {
3160            self.transaction_as(Some(format!("zone:{id}:settings")), |d| {
3161                if let Some(z) = d.board.zones.iter_mut().find(|z| z.id == id) {
3162                    edit(z);
3163                }
3164            });
3165        }
3166        if settle {
3167            self.fill_zones();
3168        }
3169        ui.horizontal(|ui| {
3170            let fill = ui
3171                .button("Fill zones")
3172                .on_hover_text("Refill every zone against the copper as it is now (B).");
3173            self.board_view.inspector.mark("fill_zones", &fill);
3174            if fill.clicked() {
3175                self.fill_zones();
3176            }
3177            let delete = ui.button("Delete zone");
3178            self.board_view.inspector.mark("delete", &delete);
3179            if delete.clicked() {
3180                self.delete_board_selection();
3181            }
3182        });
3183    }
3184    fn part_inspector(&mut self, ui: &mut egui::Ui, id: Uuid) {
3185        let Some(placement) = self.document.board.placement(id).cloned() else {
3186            return;
3187        };
3188        let (reference, value) = self
3189            .document
3190            .components
3191            .iter()
3192            .find(|c| c.id == id)
3193            .map_or_else(Default::default, |c| (c.reference.clone(), c.value.clone()));
3194        ui.label(egui::RichText::new(format!("{reference} · {value}")).color(accent(ui)));
3195        ui.small(format!(
3196            "{} · {:.2}, {:.2} mm · {}° · {}",
3197            crate::count(placement.footprint.pads.len(), "pad", "pads"),
3198            mm(placement.at.x),
3199            mm(placement.at.y),
3200            u16::from(placement.rotation) * 90,
3201            if placement.bottom { "bottom" } else { "top" }
3202        ));
3203        ui.horizontal(|ui| {
3204            let rotate = ui.button("Rotate 90°");
3205            self.board_view.inspector.mark("rotate", &rotate);
3206            if rotate.clicked() {
3207                self.rotate_part();
3208            }
3209            let flip = ui.button(if placement.bottom {
3210                "Move to top"
3211            } else {
3212                "Move to bottom"
3213            });
3214            self.board_view.inspector.mark("flip", &flip);
3215            if flip.clicked() {
3216                self.flip_part();
3217            }
3218        });
3219        // A placement's pads are a copy of its part's, edited on the part.
3220        ui.label("Footprint");
3221        ui.small(if placement.footprint.name.is_empty() {
3222            "(unnamed)"
3223        } else {
3224            placement.footprint.name.as_str()
3225        });
3226        // Its pads, each with the net that reaches it. A pad is selectable here
3227        // as well as on the canvas, because a pad under a track, or smaller than
3228        // a pointer, is a poor target and is exactly the one a user wants when
3229        // they are chasing a connection.
3230        ui.add_space(6.);
3231        ui.label("Pads");
3232        let nets = self.nets_of(id);
3233        let selected = self.board_view.selected;
3234        let mut pick = None;
3235        egui::ScrollArea::vertical()
3236            .id_salt("board-part-pads")
3237            .max_height(180.)
3238            .show(ui, |ui| {
3239                for (index, pad) in placement.footprint.pads.iter().enumerate() {
3240                    let on = selected == Some(BoardSelection::Pad(id, index));
3241                    let text = match (pad.number.as_str(), nets.get(&pad.number)) {
3242                        ("", _) => "mechanical".to_owned(),
3243                        (number, Some(net)) => format!("{number}  ·  {net}"),
3244                        (number, None) => format!("{number}  ·  no net"),
3245                    };
3246                    let row = ui.selectable_label(on, text);
3247                    // By the key the pad has on the canvas; a mechanical pad, which
3248                    // has none there, by its index in the footprint.
3249                    match pad.number.as_str() {
3250                        "" => self.board_view.inspector.mark(format!("row:unnumbered-pad:{reference}.{index}"), &row),
3251                        number => self.board_view.inspector.mark(format!("row:pad:{reference}.{number}"), &row),
3252                    }
3253                    if row.clicked() {
3254                        pick = Some(index);
3255                    }
3256                }
3257            });
3258        if placement.footprint.pads.is_empty() {
3259            ui.small("This footprint has no pads.");
3260        }
3261        if let Some(index) = pick {
3262            self.board_view.selected = Some(BoardSelection::Pad(id, index));
3263        }
3264    }
3265    /// One PAD of a placed part: what it is, which net reaches it, where it sits,
3266    /// and where it is edited — which is the part it came from, never here.
3267    fn pad_inspector(&mut self, ui: &mut egui::Ui, id: Uuid, index: usize) {
3268        let Some(placement) = self.document.board.placement(id).cloned() else {
3269            return;
3270        };
3271        let reference = self.reference_of(id).to_owned();
3272        let Some(pad) = placement.footprint.pads.get(index).cloned() else {
3273            // The footprint was refreshed from the part under the selection.
3274            ui.small(format!("That pad is no longer in {reference}'s footprint."));
3275            let select = ui.button(format!("Select {reference}"));
3276            self.board_view.inspector.mark("select_part", &select);
3277            if select.clicked() {
3278                self.board_view.selected = Some(BoardSelection::Part(id));
3279            }
3280            return;
3281        };
3282        let count = self.document.board.layer_count;
3283        ui.label(egui::RichText::new(pad_title(&reference, &pad)).color(accent(ui)));
3284        match (pad.number.is_empty(), self.pad_net(id, &pad.number)) {
3285            (true, _) => {
3286                ui.small(
3287                    "No pin and no net: a mechanical pad reaches the copper and drill files and never the netlist.",
3288                );
3289            }
3290            (false, Some(net)) => {
3291                ui.small(format!("Net {net}, from pin {} on the sheet.", pad.number));
3292            }
3293            (false, None) => {
3294                ui.label(
3295                    egui::RichText::new(format!(
3296                        "No net reaches pin {}. Wire it on the sheet, or make the pad mechanical on the part.",
3297                        pad.number
3298                    ))
3299                    .small()
3300                    .color(ui.visuals().warn_fg_color),
3301                );
3302            }
3303        }
3304        let (first, last) = placement.pad_layers(&pad, count);
3305        let layers = if first == last {
3306            layer_name(first, count).to_owned()
3307        } else {
3308            format!(
3309                "{} to {}",
3310                layer_name(first, count),
3311                layer_name(last, count)
3312            )
3313        };
3314        let at = placement.transform(pad.at);
3315        ui.small(format!(
3316            "{} · {} · {:.2} × {:.2} mm · at {:.2}, {:.2} mm",
3317            match (pad.hole_size(), pad.drill_height.is_some()) {
3318                (None, _) => "Surface mount".to_owned(),
3319                (Some(hole), slot) => format!(
3320                    "{}, {}",
3321                    if pad.plated { "Plated through hole" } else { "Unplated hole" },
3322                    if slot {
3323                        format!("{:.2} × {:.2} mm slot", mm(hole.x), mm(hole.y))
3324                    } else {
3325                        format!("{:.2} mm drill", mm(hole.x))
3326                    }
3327                ),
3328            },
3329            layers,
3330            mm(pad.size.x),
3331            mm(pad.size.y),
3332            mm(at.x),
3333            mm(at.y),
3334        ));
3335        ui.add_space(6.);
3336        ui.horizontal_wrapped(|ui| {
3337            let select = ui.button(format!("Select {reference}"));
3338            self.board_view.inspector.mark("select_part", &select);
3339            if select.clicked() {
3340                self.board_view.selected = Some(BoardSelection::Part(id));
3341            }
3342            let rotate = ui.button("Rotate 90°").on_hover_text("Turns the whole part, which is what a pad turns with.");
3343            self.board_view.inspector.mark("rotate", &rotate);
3344            if rotate.clicked() {
3345                self.rotate_part();
3346            }
3347        });
3348        ui.small("A pad's size, number and drill belong to the part's footprint: edit them in the Pads workbench.");
3349    }
3350    /// One SILKSCREEN line of a placed part: which part's, how long, and where
3351    /// it is edited — the part's footprint, as for a pad.
3352    fn silk_inspector(&mut self, ui: &mut egui::Ui, id: Uuid, index: usize) {
3353        let reference = self.reference_of(id).to_owned();
3354        let Some((_, line)) = self.silk_at(id, index) else {
3355            ui.small(format!(
3356                "That silkscreen line is no longer in {reference}'s footprint."
3357            ));
3358            let select = ui.button(format!("Select {reference}"));
3359            self.board_view.inspector.mark("select_part", &select);
3360            if select.clicked() {
3361                self.board_view.selected = Some(BoardSelection::Part(id));
3362            }
3363            return;
3364        };
3365        let side = match self.document.board.placement(id) {
3366            Some(p) if p.bottom => "bottom",
3367            _ => "top",
3368        };
3369        let length: f64 = line
3370            .windows(2)
3371            .map(|s| f64::from(s[1].x - s[0].x).hypot(f64::from(s[1].y - s[0].y)))
3372            .sum();
3373        let name = self.drawing_name(id, index);
3374        ui.label(egui::RichText::new(format!("{reference} · {name}")).color(accent(ui)));
3375        // The board layer it lands on: a part on the bottom swaps the sides.
3376        let on = match self.document.board.placement(id).and_then(|p| Some((p.bottom, p.footprint.drawing().nth(index)?))) {
3377            Some((bottom, d)) => {
3378                let layer = if bottom { d.layer.flipped() } else { d.layer };
3379                match (layer.is_silk(), layer.front()) {
3380                    (true, true) => "top silkscreen".to_owned(),
3381                    (true, false) => "bottom silkscreen".to_owned(),
3382                    _ => layer.name().to_owned(),
3383                }
3384            }
3385            None => format!("{side} silkscreen"),
3386        };
3387        ui.small(format!("{} points · {:.2} mm long · {on}", line.len(), length / 1000.));
3388        ui.small("Decoration: it prints on the silkscreen film. It carries no pin and no net.");
3389        ui.add_space(6.);
3390        ui.horizontal_wrapped(|ui| {
3391            let select = ui.button(format!("Select {reference}"));
3392            self.board_view.inspector.mark("select_part", &select);
3393            if select.clicked() {
3394                self.board_view.selected = Some(BoardSelection::Part(id));
3395            }
3396            let rotate = ui.button("Rotate 90°").on_hover_text("Turns the whole part, which is what its silkscreen turns with.");
3397            self.board_view.inspector.mark("rotate", &rotate);
3398            if rotate.clicked() {
3399                self.rotate_part();
3400            }
3401        });
3402        ui.small("A footprint's silkscreen is edited on the part, in the Pads workbench. Dragging the line here moves the part.");
3403    }
3404    fn routing_section(&mut self, ui: &mut egui::Ui) {
3405        ui.heading("Routing");
3406        let board = &self.document.board;
3407        ui.small(format!(
3408            "{} parts · {} tracks · {} vias · {} unrouted connections",
3409            board.placements.len(),
3410            board.tracks.len(),
3411            board.vias.len(),
3412            self.board_view.unrouted
3413        ));
3414        let has_copper = !board.tracks.is_empty() || !board.vias.is_empty();
3415        let current = board.rules.autoroute_vias;
3416        let mut policy = current;
3417        ui.add_enabled_ui(!self.routing(), |ui| {
3418            ui.horizontal(|ui| {
3419                ui.label("Vias");
3420                let choices = [
3421                    (ViaPolicy::Avoid, "avoid", via_policy_name(ViaPolicy::Avoid)),
3422                    (ViaPolicy::Allow, "allow", via_policy_name(ViaPolicy::Allow)),
3423                    (ViaPolicy::Never, "never", via_policy_name(ViaPolicy::Never)),
3424                ];
3425                self.board_view.inspector.enum_dropdown(ui, "vias", &choices, &mut policy)
3426                    .on_hover_text("How the autorouter uses vias. Saved with the board.\nAvoid: route as Allow, then reroute nets to remove vias wherever possible.\nAllow: use vias for noticeably shorter routes.\nNever: keep each connection on one layer; connections that need vias stay unrouted.");
3427            });
3428        });
3429        if policy != current {
3430            self.transaction(|d| d.board.rules.autoroute_vias = policy);
3431            // An unapplied edit under Design rules would otherwise put the old choice back.
3432            if let Some(pending) = &mut self.board_view.rules {
3433                pending.autoroute_vias = policy;
3434            }
3435        }
3436        ui.horizontal_wrapped(|ui| {
3437            let autoroute = ui
3438                .add_enabled(
3439                    self.board_view.unrouted > 0 && !self.routing(),
3440                    egui::Button::new("Autoroute"),
3441                )
3442                .on_hover_text("Connect every unrouted connection. Existing copper is kept.");
3443            self.board_view.inspector.mark("autoroute", &autoroute);
3444            if autoroute.clicked() {
3445                self.start_autoroute();
3446            }
3447            let widths = ui
3448                .add_enabled(
3449                    has_copper
3450                        && (!self.document.board.rules.net_widths.is_empty()
3451                            || !self.document.board.rules.net_classes.is_empty()),
3452                    egui::Button::new("Apply net widths"),
3453                )
3454                .on_hover_text(
3455                    "Give every drawn track the width its net asks for: its own width rule, else its net class's. Run the design rule check afterwards.",
3456                );
3457            self.board_view.inspector.mark("apply_net_widths", &widths);
3458            if widths.clicked() {
3459                let mut changed = 0;
3460                self.transaction(|d| changed = d.apply_net_widths());
3461                self.board_view.message = format!("{changed} tracks took their net's width.");
3462            }
3463            let rip_up = ui.add_enabled(has_copper, egui::Button::new("Rip up all copper"));
3464            self.board_view.inspector.mark("rip_up", &rip_up);
3465            if rip_up.clicked() {
3466                self.transaction(|d| {
3467                    d.board.tracks.clear();
3468                    d.board.vias.clear();
3469                });
3470                self.board_view.selected = None;
3471            }
3472        });
3473    }
3474    fn drc_section(&mut self, ui: &mut egui::Ui) {
3475        ui.heading("Design rule check");
3476        let run = ui.button("Run design rule check");
3477        self.board_view.inspector.mark("run_drc", &run);
3478        if run.clicked() {
3479            self.run_design_rule_check();
3480        }
3481        let Some(violations) = &self.board_view.violations else {
3482            return;
3483        };
3484        if violations.is_empty() {
3485            ui.label(egui::RichText::new("No violations.").color(accent(ui)));
3486            return;
3487        }
3488        ui.label(match violations.len() {
3489            1 => "1 finding. Click it to zoom to it on the board.".to_owned(),
3490            n => format!("{n} findings. Click one to zoom to it on the board."),
3491        });
3492        let mut focus = None;
3493        let mut rows = vec![];
3494        ui.scope(|ui| {
3495            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
3496            for (i, v) in violations.iter().enumerate().take(200) {
3497                let row = finding_row(ui.style(), v);
3498                let focused = self.board_view.focused_violation == Some(i);
3499                let row = ui.selectable_label(focused, row).on_hover_text("Zoom to it on the board");
3500                if row.clicked() {
3501                    focus = Some((i, v.at));
3502                }
3503                rows.push(row);
3504            }
3505        });
3506        // Each finding by its place in the list, which is the order the check
3507        // returned them in.
3508        for (i, row) in rows.iter().enumerate() {
3509            self.board_view.inspector.mark(format!("row:finding:{i}"), row);
3510        }
3511        if let Some((i, at)) = focus {
3512            let extent = self.finding_extent(&self.board_view.violations.as_ref().unwrap()[i]);
3513            self.board_view.focused_violation = Some(i);
3514            self.board_view.focus_on(at, extent);
3515        }
3516    }
3517    /// How far a design rule finding reaches, in µm: an unrouted connection runs
3518    /// between its two pads, and is found again in the ratsnest by its net and its
3519    /// midpoint, which is where the check puts it. Every other finding is a point.
3520    fn finding_extent(&self, v: &Violation) -> i32 {
3521        if v.kind != ViolationKind::Unrouted {
3522            return 0;
3523        }
3524        let conn = self.document.board.connectivity(&self.document.netlist());
3525        self.document
3526            .board
3527            .ratsnest(&conn)
3528            .iter()
3529            .find(|w| {
3530                Point::new((w.a.x + w.b.x) / 2, (w.a.y + w.b.y) / 2) == v.at
3531                    && v.message.ends_with(&format!(" {}", w.net))
3532            })
3533            .map_or(0, |w| (w.b.x - w.a.x).abs().max((w.b.y - w.a.y).abs()))
3534    }
3535    fn outline_section(&mut self, ui: &mut egui::Ui) {
3536        let (min, max) = self.document.board.outline_bounds();
3537        let rectangle_outline = self.document.board.outline_is_rectangle();
3538        if rectangle_outline {
3539            let (w, h) = *self
3540                .board_view
3541                .outline
3542                .get_or_insert((mm(max.x - min.x), mm(max.y - min.y)));
3543            let (mut w, mut h) = (w, h);
3544            ui.horizontal(|ui| {
3545                ui.label("Width");
3546                let field = ui.add(
3547                    egui::DragValue::new(&mut w)
3548                        .speed(0.5)
3549                        .range(5.0..=1000.0)
3550                        .suffix(" mm"),
3551                );
3552                self.board_view.inspector.mark("outline_width", &field);
3553            });
3554            ui.horizontal(|ui| {
3555                ui.label("Height");
3556                let field = ui.add(
3557                    egui::DragValue::new(&mut h)
3558                        .speed(0.5)
3559                        .range(5.0..=1000.0)
3560                        .suffix(" mm"),
3561                );
3562                self.board_view.inspector.mark("outline_height", &field);
3563            });
3564            self.board_view.outline = Some((w, h));
3565            let changed = um(w) != max.x - min.x || um(h) != max.y - min.y;
3566            let apply = ui.add_enabled(changed, egui::Button::new("Apply size"));
3567            self.board_view.inspector.mark("apply_size", &apply);
3568            if apply.clicked() {
3569                let mut resized = self.document.board.clone();
3570                resized.outline = rectangle(min, Point::new(min.x + um(w), min.y + um(h)));
3571                // A cutout the smaller board would leave hanging off it says so.
3572                let stranded = resized.cutouts.iter().enumerate().find_map(|(n, c)| {
3573                    resized.cutout_problem(&c.points, Some(n)).map(|why| format!("Not resized: cutout {} would then be {}.", n + 1, why.trim_start_matches("is ")))
3574                });
3575                if let Some(words) = stranded {
3576                    self.board_view.message = words;
3577                } else {
3578                    self.transaction(|d| d.board.outline = resized.outline);
3579                }
3580                self.board_view.outline = None;
3581            }
3582        } else {
3583            ui.small("Custom outline");
3584        }
3585        if let Some(note) = stock_board_note(&self.document.board) {
3586            ui.label(egui::RichText::new(note).color(ui.visuals().warn_fg_color));
3587        }
3588        // Both say what they did: the board's message stayed on the last sync's line
3589        // for ten steps of the re-audit's walk while these two ran in silence.
3590        let size = |board: &Board| {
3591            let (min, max) = board.outline_bounds();
3592            Point::new(max.x - min.x, max.y - min.y)
3593        };
3594        let fit = ui.button("Fit outline to parts");
3595        self.board_view.inspector.mark("fit_outline", &fit);
3596        if fit.clicked() {
3597            let from = size(&self.document.board);
3598            self.transaction(|d| d.fit_board_outline(FIT_MARGIN));
3599            self.board_view.outline = None;
3600            // The view follows the outline it was fitted to, as it does a sync's.
3601            self.board_view.fitted = false;
3602            let to = size(&self.document.board);
3603            self.board_view.message = if self.document.board.placements.is_empty() {
3604                "There are no parts to fit the outline to.".into()
3605            } else if from == to {
3606                format!("The outline already fits the parts: {} mm.", size_words(to))
3607            } else {
3608                format!(
3609                    "Outline fitted to the parts, {:.0} mm clear of them: {} mm, from {} mm.",
3610                    mm(FIT_MARGIN),
3611                    size_words(to),
3612                    size_words(from)
3613                )
3614            };
3615        }
3616        let place = ui
3617            .button("Auto-place parts")
3618            .on_hover_text("Lay the parts out afresh: the part with the most pins in the middle, and each other part as near as there is room to the parts it shares a net with. Sides and rotations are kept.");
3619        self.board_view.inspector.mark("auto_place", &place);
3620        if place.clicked() {
3621            let from = size(&self.document.board);
3622            self.transaction(Document::place_by_nets);
3623            let to = size(&self.document.board);
3624            let count = self.document.board.placements.len();
3625            self.board_view.message = match count {
3626                0 => "There are no parts to place.".into(),
3627                _ if from != to => format!(
3628                    "{count} parts placed by their nets. They did not fit, so the board grew from {} to {} mm.",
3629                    size_words(from),
3630                    size_words(to)
3631                ),
3632                _ => format!("{count} parts placed by their nets, each beside the parts it connects to."),
3633            };
3634            self.board_view.outline = None;
3635        }
3636        ui.horizontal(|ui| {
3637            ui.label("Copper layers");
3638            let mut count = self.document.board.layer_count;
3639            let choices = [(1u8, "1", "1"), (2, "2", "2"), (4, "4", "4"), (6, "6", "6")];
3640            self.board_view.inspector.enum_dropdown(ui, "copper_layers", &choices, &mut count);
3641            if count != self.document.board.layer_count {
3642                let mut draft = self.document.board.clone();
3643                match draft.set_layer_count(count) {
3644                    Ok(()) => {
3645                        self.transaction(|d| d.board = draft);
3646                        self.board_view.active_layer = self.board_view.active_layer.min(count - 1);
3647                        self.board_view.hidden.clear();
3648                    }
3649                    Err(e) => self.board_view.message = e,
3650                }
3651            }
3652        });
3653    }
3654    fn rules_section(&mut self, ui: &mut egui::Ui) {
3655        let current = self.document.board.rules.clone();
3656        let mut rules = self
3657            .board_view
3658            .rules
3659            .take()
3660            .unwrap_or_else(|| current.clone());
3661        // The Net classes section edits the classes directly; a rules draft never
3662        // holds its own copy of them, so Apply cannot put back old ones.
3663        rules.net_classes = current.net_classes.clone();
3664        rules.net_class_of = current.net_class_of.clone();
3665        ui.label(
3666            egui::RichText::new("Track width, clearance and via are the Default net class.")
3667                .small()
3668                .color(ui.visuals().weak_text_color()),
3669        );
3670        for (label, value, max) in [
3671            ("Track width", &mut rules.track_width, 5.0),
3672            ("Clearance", &mut rules.clearance, 5.0),
3673            ("Via diameter", &mut rules.via_diameter, 5.0),
3674            ("Via drill", &mut rules.via_drill, 5.0),
3675            ("Edge clearance", &mut rules.edge_clearance, 10.0),
3676            ("Routing grid", &mut rules.routing_grid, 2.5),
3677        ] {
3678            ui.horizontal(|ui| {
3679                ui.label(label);
3680                let mut v = mm(*value);
3681                let field = ui.add(
3682                    egui::DragValue::new(&mut v)
3683                        .speed(0.005)
3684                        .range(0.025..=max)
3685                        .fixed_decimals(3)
3686                        .suffix(" mm"),
3687                );
3688                self.board_view.inspector.mark(format!("rule:{}", key_word(label)), &field);
3689                if field.changed() {
3690                    *value = um(v);
3691                }
3692            });
3693        }
3694        ui.horizontal(|ui| {
3695            ui.label("Solder mask expansion");
3696            let mut v = mm(rules.mask_expansion);
3697            let field = ui.add(
3698                egui::DragValue::new(&mut v)
3699                    .speed(0.005)
3700                    .range(0.0..=0.5)
3701                    .fixed_decimals(3)
3702                    .suffix(" mm"),
3703            );
3704            self.board_view.inspector.mark("rule:solder_mask_expansion", &field);
3705            if field.changed() {
3706                rules.mask_expansion = um(v);
3707            }
3708        });
3709        let tent = ui
3710            .checkbox(&mut rules.tent_vias, "Tent vias")
3711            .on_hover_text("On: the solder mask covers every via. Off: the mask opens over each via's ring on both sides.");
3712        self.board_view.inspector.mark("rule:tent_vias", &tent);
3713        ui.horizontal(|ui| {
3714            ui.label("Minimum annular ring");
3715            let mut v = mm(rules.min_annular_ring);
3716            let field = ui
3717                .add(
3718                    egui::DragValue::new(&mut v)
3719                        .speed(0.005)
3720                        .range(0.0..=1.0)
3721                        .fixed_decimals(3)
3722                        .suffix(" mm"),
3723                )
3724                .on_hover_text("The narrowest copper ring a plated pad or via may keep round its hole.");
3725            self.board_view.inspector.mark("rule:minimum_annular_ring", &field);
3726            if field.changed() {
3727                rules.min_annular_ring = um(v);
3728            }
3729        });
3730        ui.horizontal(|ui| {
3731            ui.label("Minimum hole spacing");
3732            let mut v = mm(rules.min_hole_spacing);
3733            let field = ui
3734                .add(
3735                    egui::DragValue::new(&mut v)
3736                        .speed(0.005)
3737                        .range(0.0..=10.0)
3738                        .fixed_decimals(3)
3739                        .suffix(" mm"),
3740                )
3741                .on_hover_text(
3742                    "The narrowest web of board left between two drilled holes, edge to edge. 0 turns the check off; holes that touch are still a finding.",
3743                );
3744            self.board_view.inspector.mark("rule:minimum_hole_spacing", &field);
3745            if field.changed() {
3746                rules.min_hole_spacing = um(v);
3747            }
3748        });
3749        ui.label("Net widths");
3750        let mut remove = None;
3751        for (net, width) in &rules.net_widths {
3752            ui.horizontal(|ui| {
3753                ui.small(format!("{net}: {:.3} mm", mm(*width)));
3754                let remove_button = ui.small_button("Remove");
3755                self.board_view.inspector.mark(format!("net_width:{net}:remove"), &remove_button);
3756                if remove_button.clicked() {
3757                    remove = Some(net.clone());
3758                }
3759            });
3760        }
3761        if let Some(net) = remove {
3762            rules.net_widths.remove(&net);
3763        }
3764        let names: BTreeSet<String> = self
3765            .document
3766            .netlist()
3767            .nets
3768            .into_iter()
3769            .filter(|n| !n.labels.is_empty() && n.pins.len() > 1)
3770            .map(|n| n.name)
3771            .collect();
3772        ui.horizontal(|ui| {
3773            let combo = egui::ComboBox::from_id_salt("net-width-net")
3774                .selected_text(if self.board_view.net_width.0.is_empty() {
3775                    "Net…"
3776                } else {
3777                    self.board_view.net_width.0.as_str()
3778                })
3779                .show_ui(ui, |ui| {
3780                    menu_ui(ui);
3781                    for name in &names {
3782                        let choice =
3783                            ui.selectable_value(&mut self.board_view.net_width.0, name.clone(), name);
3784                        self.board_view.inspector.mark(format!("net_width_net:{name}"), &choice);
3785                    }
3786                });
3787            self.board_view.inspector.mark("net_width_net", &combo.response);
3788            let field = ui.add(
3789                egui::DragValue::new(&mut self.board_view.net_width.1)
3790                    .speed(0.01)
3791                    .range(0.05..=5.0)
3792                    .suffix(" mm"),
3793            );
3794            self.board_view.inspector.mark("net_width", &field);
3795            let add = ui.add_enabled(
3796                !self.board_view.net_width.0.is_empty(),
3797                egui::Button::new("Add"),
3798            );
3799            self.board_view.inspector.mark("add_net_width", &add);
3800            if add.clicked() {
3801                rules.net_widths.insert(
3802                    self.board_view.net_width.0.clone(),
3803                    um(self.board_view.net_width.1),
3804                );
3805            }
3806        });
3807        let valid = rules.via_drill < rules.via_diameter;
3808        if !valid {
3809            ui.small(
3810                egui::RichText::new("The via drill must be smaller than the via.")
3811                    .color(ui.visuals().error_fg_color),
3812            );
3813        }
3814        let apply = ui.add_enabled(valid && rules != current, egui::Button::new("Apply rules"));
3815        self.board_view.inspector.mark("apply_rules", &apply);
3816        if apply.clicked() {
3817            self.transaction(|d| d.board.rules = rules.clone());
3818            self.board_view.rules = None;
3819        } else if rules != current {
3820            self.board_view.rules = Some(rules);
3821        }
3822    }
3823
3824    /// The net of what is selected on the board — a track's, a via's, a pad's or a
3825    /// zone's — if it has exactly one.
3826    pub fn selected_board_net(&self) -> Option<String> {
3827        let board = &self.document.board;
3828        match self.board_view.selected? {
3829            BoardSelection::Track(id) => self.document.track_nets().get(&id).cloned(),
3830            BoardSelection::Zone(id) => board.zones.iter().find(|z| z.id == id).map(|z| z.net.clone()),
3831            BoardSelection::Pad(component, index) => {
3832                let number = &board.placement(component)?.footprint.pads.get(index)?.number;
3833                self.document
3834                    .netlist()
3835                    .nets
3836                    .into_iter()
3837                    .find(|n| n.pins.iter().any(|p| p.component_id == component && &p.number == number))
3838                    .map(|n| n.name)
3839            }
3840            BoardSelection::Via(id) => {
3841                let conn = board.connectivity(&self.document.netlist());
3842                let i = conn.items.iter().position(|item| {
3843                    matches!(item.owner, CopperRef::Via(v) if board.vias.get(v).is_some_and(|via| via.id == id))
3844                })?;
3845                conn.island_net(conn.islands[i]).map(str::to_owned)
3846            }
3847            _ => None,
3848        }
3849    }
3850    /// The net the Net classes section is about: the selection's, else the one
3851    /// picked in the section.
3852    pub fn net_class_subject(&self) -> Option<String> {
3853        self.selected_board_net()
3854            .or_else(|| (!self.board_view.class_net.is_empty()).then(|| self.board_view.class_net.clone()))
3855    }
3856    /// Try `f` on a copy of the board's rules and keep it only if the classes are
3857    /// still valid; otherwise say why in the Inspector's message.
3858    fn edit_net_classes(&mut self, coalesce: Option<String>, f: impl FnOnce(&mut DesignRules)) -> Result<(), String> {
3859        let mut rules = self.document.board.rules.clone();
3860        f(&mut rules);
3861        rules.check_net_classes()?;
3862        if rules != self.document.board.rules {
3863            self.transaction_as(coalesce, |d| d.board.rules = rules);
3864        }
3865        Ok(())
3866    }
3867    /// Net classes: every class with its clearance, track width and via, the name
3868    /// patterns that put nets in it and the nets it holds; adding, editing and
3869    /// deleting one; and which class one net is in, why, and the class to put it in.
3870    fn net_classes_section(&mut self, ui: &mut egui::Ui) {
3871        let rules = self.document.board.rules.clone();
3872        let nets = self.net_names();
3873        let sub = |ui: &mut egui::Ui, text: String| {
3874            ui.label(egui::RichText::new(text).small().color(ui.visuals().weak_text_color()));
3875        };
3876        let size = |c: i32, w: i32, d: i32, h: i32| {
3877            format!("{:.3} clearance · {:.3} track · via {:.3}/{:.3} mm", mm(c), mm(w), mm(d), mm(h))
3878        };
3879
3880        // One net: its class, why, and what it asks for; and a class to put it in.
3881        let subject = self.net_class_subject();
3882        ui.horizontal(|ui| {
3883            ui.label("Net");
3884            let combo = egui::ComboBox::from_id_salt("net-class-net")
3885                .selected_text(subject.as_deref().unwrap_or("Net…"))
3886                .show_ui(ui, |ui| {
3887                    menu_ui(ui);
3888                    for name in &nets {
3889                        let choice = ui.selectable_label(subject.as_ref() == Some(name), name);
3890                        self.board_view.inspector.mark(format!("net_class:net:{name}"), &choice);
3891                        if choice.clicked() {
3892                            self.board_view.class_net = name.clone();
3893                            self.board_view.selected = None;
3894                        }
3895                    }
3896                });
3897            self.board_view.inspector.mark("net_class:net", &combo.response);
3898        });
3899        if let Some(net) = &subject {
3900            let (class, reason) = rules.class_reason(Some(net));
3901            let why = match &reason {
3902                ClassReason::Assigned => "assigned".to_owned(),
3903                ClassReason::Pattern(p) => format!("by the pattern {p}"),
3904                ClassReason::Default => "nothing puts it in another class".to_owned(),
3905            };
3906            let readout = ui.label(
3907                egui::RichText::new(format!("{net} is {} — {why}", class.name)).color(accent(ui)),
3908            );
3909            self.board_view.inspector.mark("net_class:readout", &readout);
3910            let width = rules.width_for(net);
3911            sub(
3912                ui,
3913                format!(
3914                    "{}{}",
3915                    size(class.clearance, width, class.via_diameter, class.via_drill),
3916                    if rules.net_widths.contains_key(net) { " (its own track width)" } else { "" }
3917                ),
3918            );
3919            let assigned = rules.net_class_of.get(net).filter(|_| reason == ClassReason::Assigned).cloned();
3920            let mut choice = assigned.clone();
3921            ui.horizontal(|ui| {
3922                ui.label("Put in");
3923                let combo = egui::ComboBox::from_id_salt("net-class-assign")
3924                    .selected_text(choice.clone().unwrap_or_else(|| "by pattern".into()))
3925                    .show_ui(ui, |ui| {
3926                        menu_ui(ui);
3927                        let auto = ui.selectable_value(&mut choice, None, "by pattern")
3928                            .on_hover_text("No assignment: the first class whose pattern matches, else Default.");
3929                        self.board_view.inspector.mark("net_class:assign:auto", &auto);
3930                        for c in &rules.net_classes {
3931                            let option = ui.selectable_value(&mut choice, Some(c.name.clone()), &c.name);
3932                            self.board_view.inspector.mark(format!("net_class:assign:{}", c.name), &option);
3933                        }
3934                    });
3935                self.board_view.inspector.mark("net_class:assign", &combo.response);
3936            });
3937            if choice != assigned {
3938                let net = net.clone();
3939                let _ = self.edit_net_classes(None, |r| match &choice {
3940                    Some(class) => {
3941                        r.net_class_of.insert(net.clone(), class.clone());
3942                    }
3943                    None => {
3944                        r.net_class_of.remove(&net);
3945                    }
3946                });
3947                self.board_view.message = match &choice {
3948                    Some(class) => format!("{net} is in {class}. Run the design rule check to see what it changes."),
3949                    None => format!("{net} follows the patterns: {}.", self.document.board.rules.class_of(Some(&net)).name),
3950                };
3951            }
3952        } else {
3953            sub(ui, "Select a track, pad, via or zone, or pick a net, to see its class.".into());
3954        }
3955        ui.add_space(6.);
3956
3957        // Which class each net is in, for the lists under each class.
3958        let mut members: BTreeMap<String, Vec<String>> = BTreeMap::new();
3959        for net in &nets {
3960            members.entry(rules.class_of(Some(net)).name).or_default().push(net.clone());
3961        }
3962        let listed = |names: Option<&Vec<String>>| match names {
3963            None => "no nets".to_owned(),
3964            Some(names) if names.len() > 8 => format!("{} nets: {}, …", names.len(), names[..8].join(", ")),
3965            Some(names) => format!("{} net{}: {}", names.len(), if names.len() == 1 { "" } else { "s" }, names.join(", ")),
3966        };
3967
3968        // Default: the board's own rules, edited under Design rules.
3969        let default = rules.default_class();
3970        let row = ui.label(egui::RichText::new(DEFAULT_CLASS).strong());
3971        self.board_view.inspector.mark(format!("net_class:{DEFAULT_CLASS}"), &row);
3972        sub(ui, size(default.clearance, default.track_width, default.via_diameter, default.via_drill));
3973        sub(ui, format!("{} — its sizes are the Design rules above", listed(members.get(DEFAULT_CLASS))));
3974
3975        let mut delete = None;
3976        for (i, class) in rules.net_classes.iter().enumerate() {
3977            ui.separator();
3978            let key = class.name.clone();
3979            ui.horizontal(|ui| {
3980                let (mut text, _) = self
3981                    .board_view
3982                    .class_text
3983                    .get(&(i, "name"))
3984                    .cloned()
3985                    .unwrap_or_else(|| (class.name.clone(), String::new()));
3986                let field = ui.add(egui::TextEdit::singleline(&mut text).id_salt(("net-class-name", i)).desired_width(110.));
3987                self.board_view.inspector.mark(format!("net_class:{key}:name"), &field);
3988                if field.changed() {
3989                    let old = class.name.clone();
3990                    let new = text.clone();
3991                    let result = self.edit_net_classes(Some(format!("net_class:{i}:name")), |r| {
3992                        r.net_classes[i].name = new.clone();
3993                        for assigned in r.net_class_of.values_mut() {
3994                            if *assigned == old {
3995                                *assigned = new.clone();
3996                            }
3997                        }
3998                    });
3999                    match result {
4000                        Ok(()) => {
4001                            self.board_view.class_text.remove(&(i, "name"));
4002                        }
4003                        Err(e) => {
4004                            self.board_view.class_text.insert((i, "name"), (text, e));
4005                        }
4006                    }
4007                } else if field.lost_focus() {
4008                    self.board_view.class_text.remove(&(i, "name"));
4009                }
4010                let remove = ui.small_button("Delete").on_hover_text("Its nets go back to the patterns, else Default.");
4011                self.board_view.inspector.mark(format!("net_class:{key}:delete"), &remove);
4012                if remove.clicked() {
4013                    delete = Some(i);
4014                }
4015            });
4016            if let Some((_, why)) = self.board_view.class_text.get(&(i, "name")) {
4017                ui.small(egui::RichText::new(why).color(ui.visuals().error_fg_color));
4018            }
4019            for (field_key, label, get, max) in [
4020                ("clearance", "Clearance", class.clearance, 5.0),
4021                ("track_width", "Track width", class.track_width, 5.0),
4022                ("via_diameter", "Via diameter", class.via_diameter, 5.0),
4023                ("via_drill", "Via drill", class.via_drill, 5.0),
4024            ] {
4025                ui.horizontal(|ui| {
4026                    ui.label(label);
4027                    let mut v = mm(get);
4028                    let field = ui.add(
4029                        egui::DragValue::new(&mut v)
4030                            .speed(0.005)
4031                            .range(if field_key == "clearance" { 0.0 } else { 0.025 }..=max)
4032                            .fixed_decimals(3)
4033                            .suffix(" mm"),
4034                    );
4035                    self.board_view.inspector.mark(format!("net_class:{key}:{field_key}"), &field);
4036                    if field.changed() {
4037                        let result = self.edit_net_classes(Some(format!("net_class:{i}:{field_key}")), |r| {
4038                            let c = &mut r.net_classes[i];
4039                            let value = um(v);
4040                            match field_key {
4041                                "clearance" => c.clearance = value,
4042                                "track_width" => c.track_width = value,
4043                                "via_diameter" => c.via_diameter = value,
4044                                _ => c.via_drill = value,
4045                            }
4046                        });
4047                        if let Err(e) = result {
4048                            self.board_view.message = format!("{e}: the via drill must be smaller than the via.");
4049                        }
4050                    }
4051                });
4052            }
4053            ui.horizontal(|ui| {
4054                ui.label("Patterns");
4055                let (mut text, _) = self
4056                    .board_view
4057                    .class_text
4058                    .get(&(i, "patterns"))
4059                    .cloned()
4060                    .unwrap_or_else(|| (class.patterns.join(", "), String::new()));
4061                let field = ui
4062                    .add(egui::TextEdit::singleline(&mut text).id_salt(("net-class-patterns", i)).hint_text("+*V*, GND"))
4063                    .on_hover_text("Net names this class takes, separated by commas: * is any run of characters, ? any one. An assignment beats a pattern; the first class whose pattern matches wins.");
4064                self.board_view.inspector.mark(format!("net_class:{key}:patterns"), &field);
4065                if field.changed() {
4066                    let patterns: Vec<String> =
4067                        text.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned).collect();
4068                    let _ = self.edit_net_classes(Some(format!("net_class:{i}:patterns")), |r| {
4069                        r.net_classes[i].patterns = patterns;
4070                    });
4071                    self.board_view.class_text.insert((i, "patterns"), (text, String::new()));
4072                } else if field.lost_focus() {
4073                    self.board_view.class_text.remove(&(i, "patterns"));
4074                }
4075            });
4076            sub(ui, listed(members.get(&class.name)));
4077        }
4078        if let Some(i) = delete {
4079            let name = rules.net_classes[i].name.clone();
4080            let _ = self.edit_net_classes(None, |r| {
4081                r.net_classes.remove(i);
4082                r.net_class_of.retain(|_, class| *class != name);
4083            });
4084            self.board_view.class_text.clear();
4085            self.board_view.message = format!("Deleted net class {name}: its nets follow the patterns, else Default.");
4086        }
4087        ui.add_space(4.);
4088        let add = ui.button("Add net class").on_hover_text("A new class with the Default class's sizes.");
4089        self.board_view.inspector.mark("net_class:add", &add);
4090        if add.clicked() {
4091            let taken: BTreeSet<String> = rules.classes().into_iter().map(|c| c.name).collect();
4092            let name = (1..).map(|n| format!("Class {n}")).find(|n| !taken.contains(n)).unwrap_or_default();
4093            let class = NetClass { name: name.clone(), ..rules.default_class() };
4094            let _ = self.edit_net_classes(None, |r| r.net_classes.push(class));
4095            self.board_view.message = format!("Added net class {name}: give it patterns, or put a net in it above.");
4096        }
4097    }
4098
4099    fn switch_layer(&mut self, layer: u8) {
4100        let count = self.document.board.layer_count;
4101        let layer = layer.min(count - 1);
4102        // The via is the size its net's class asks for, as the track's width is.
4103        let (diameter, drill) = {
4104            let net = self.board_view.draft.as_ref().and_then(|draft| self.draft_net(draft));
4105            self.document.board.rules.via_for(net.as_deref())
4106        };
4107        if let Some(draft) = &mut self.board_view.draft
4108            && draft.layer != layer
4109        {
4110            let at = *draft.points.last().unwrap();
4111            let points = std::mem::replace(&mut draft.points, vec![at]);
4112            let track = Track::new(draft.layer, draft.width, points);
4113            if track.points.len() >= 2 {
4114                draft.tracks.push(track);
4115            }
4116            draft.vias.push(Via {
4117                id: Uuid::new_v4(),
4118                at,
4119                diameter,
4120                drill,
4121                span: None,
4122            });
4123            draft.layer = layer;
4124        }
4125        self.board_view.active_layer = layer;
4126    }
4127    fn finish_draft(&mut self) {
4128        let Some(mut draft) = self.board_view.draft.take() else {
4129            return;
4130        };
4131        let track = Track::new(draft.layer, draft.width, draft.points);
4132        if track.points.len() >= 2 {
4133            draft.tracks.push(track);
4134        }
4135        if draft.tracks.is_empty() && draft.vias.is_empty() {
4136            return;
4137        }
4138        self.transaction(|d| {
4139            d.board.tracks.extend(draft.tracks);
4140            d.board.vias.extend(draft.vias);
4141        });
4142    }
4143    /// Snap a routing click to pads, vias, and tracks, or else to the placement grid.
4144    fn route_target(&self, p: Pos2) -> (Point, Option<Anchor>) {
4145        let view = &self.board_view;
4146        let board = &self.document.board;
4147        let q = view.world(p);
4148        let tolerance = view.tolerance();
4149        for placement in board.placements.iter().rev() {
4150            for pad in &placement.footprint.pads {
4151                let layers = placement.pad_layers(pad, board.layer_count);
4152                if (layers.0..=layers.1).any(|l| view.visible(l))
4153                    && placement.pad_shape(pad).distance_to_point(q) <= tolerance
4154                {
4155                    let width = self.pad_width(placement.component, &pad.number);
4156                    return (
4157                        placement.transform(pad.at),
4158                        Some(Anchor::Pad { layers, width }),
4159                    );
4160                }
4161            }
4162        }
4163        // A track ends on a via only where the via has copper: on the layer the
4164        // track being drawn is on (a blind or buried via reaches some layers only).
4165        let draft_layer = view.draft.as_ref().map(|d| d.layer);
4166        for via in &board.vias {
4167            let layers = via.layers(board.layer_count);
4168            if draft_layer.is_some_and(|l| !(layers.0..=layers.1).contains(&l)) {
4169                continue;
4170            }
4171            if Shape::circle(via.at, via.diameter / 2).distance_to_point(q) <= tolerance {
4172                return (via.at, Some(Anchor::Via { layers }));
4173            }
4174        }
4175        for track in board.tracks.iter().filter(|t| view.visible(t.layer)) {
4176            for s in track.points.windows(2) {
4177                if Shape::segment(s[0], s[1], track.width).distance_to_point(q) <= tolerance {
4178                    let (a, b) = (s[0], s[1]);
4179                    let (dx, dy) = (f64::from(b.x - a.x), f64::from(b.y - a.y));
4180                    let len2 = (dx * dx + dy * dy).max(1.);
4181                    let t = ((f64::from(q.x - a.x) * dx + f64::from(q.y - a.y) * dy) / len2)
4182                        .clamp(0., 1.);
4183                    let on =
4184                        Point::new(a.x + (t * dx).round() as i32, a.y + (t * dy).round() as i32);
4185                    let at = [a, b]
4186                        .into_iter()
4187                        .find(|v| f64::from(v.x - on.x).hypot(f64::from(v.y - on.y)) <= tolerance)
4188                        .unwrap_or(on);
4189                    return (
4190                        at,
4191                        Some(Anchor::Track {
4192                            layer: track.layer,
4193                            width: track.width,
4194                        }),
4195                    );
4196                }
4197            }
4198        }
4199        (snap(q, PLACE_GRID), None)
4200    }
4201    fn route_click(&mut self, p: Pos2) {
4202        let (at, anchor) = self.route_target(p);
4203        let Some(draft) = &self.board_view.draft else {
4204            self.start_draft(at, anchor);
4205            return;
4206        };
4207        if at == *draft.points.last().unwrap() {
4208            return;
4209        }
4210        // The click places exactly the leg the preview drew: the same corner, and
4211        // the same verdict on its clearance.
4212        let conn = self.document.board.connectivity(&self.document.netlist());
4213        let leg = self.draft_leg(&conn, draft, at, anchor.is_some());
4214        let message = match (&leg.clash, &leg.avoided) {
4215            (Some(clash), _) => Some(format!(
4216                "{}: this track passes {}{}. No corner keeps it clear, so it is drawn as you asked; Undo takes it back.",
4217                if clash.crosses() { "Short" } else { "Clearance" },
4218                clash.words(),
4219                if clash.crosses() {
4220                    String::new()
4221                } else {
4222                    format!(", and the board needs {:.3} mm ({} clearance)", f64::from(clash.needed) / 1000., clash.class)
4223                },
4224            )),
4225            (None, Some(avoided)) => Some(format!(
4226                "Bent the other way: the corner you asked for passed {}.",
4227                avoided.words()
4228            )),
4229            (None, None) => None,
4230        };
4231        if let Some(draft) = &mut self.board_view.draft {
4232            draft.points.extend(leg.points.into_iter().skip(1));
4233        }
4234        if anchor.is_some() {
4235            self.finish_draft();
4236        }
4237        if let Some(message) = message {
4238            self.board_view.message = message;
4239        }
4240    }
4241    /// The one net the copper the draft began on carries, if it carries exactly one.
4242    fn draft_net(&self, draft: &Draft) -> Option<String> {
4243        let origin = Self::draft_origin(draft);
4244        let conn = self.document.board.connectivity(&self.document.netlist());
4245        let nets: BTreeSet<&String> = conn
4246            .items
4247            .iter()
4248            .enumerate()
4249            .filter(|(_, item)| item.shape.distance_to_point(origin) <= 0.5)
4250            .flat_map(|(i, _)| &conn.island_nets[conn.islands[i]])
4251            .collect();
4252        let mut nets = nets.into_iter();
4253        match (nets.next(), nets.next()) {
4254            (Some(net), None) => Some(net.clone()),
4255            _ => None,
4256        }
4257    }
4258    /// The first point of the track being drawn, on whichever layer it began.
4259    fn draft_origin(draft: &Draft) -> Point {
4260        draft
4261            .tracks
4262            .first()
4263            .and_then(|t| t.points.first())
4264            .or(draft.points.first())
4265            .copied()
4266            .unwrap_or_default()
4267    }
4268    /// The closest copper of another net that `points`, drawn at `width` on
4269    /// `layer`, comes within the board's clearance of — the check DRC makes,
4270    /// made while the track is still a draft. Copper is the track's OWN when it
4271    /// touches the track's first point, or carries a net that copper does; and
4272    /// when the track ends on copper (`end`), that copper is its own too unless
4273    /// it carries only other nets, which would be a short, and is reported.
4274    fn route_clash(
4275        &self,
4276        conn: &Connectivity,
4277        (layer, width): (u8, i32),
4278        origin: Point,
4279        end: Option<Point>,
4280        points: &[Point],
4281    ) -> Option<Clash> {
4282        let touching = |p: Point| -> BTreeSet<usize> {
4283            conn.items
4284                .iter()
4285                .enumerate()
4286                .filter(|(_, item)| item.shape.distance_to_point(p) <= 0.5)
4287                .map(|(i, _)| conn.islands[i])
4288                .collect()
4289        };
4290        let mut own = touching(origin);
4291        let nets: BTreeSet<&String> = own.iter().flat_map(|&i| &conn.island_nets[i]).collect();
4292        for (island, carried) in conn.island_nets.iter().enumerate() {
4293            if carried.iter().any(|net| nets.contains(net)) {
4294                own.insert(island);
4295            }
4296        }
4297        if let Some(end) = end {
4298            for island in touching(end) {
4299                if nets.is_empty() || conn.island_nets[island].is_empty() {
4300                    own.insert(island);
4301                }
4302            }
4303        }
4304        let rules = &self.document.board.rules;
4305        let mut worst: Option<(f64, usize, i32, String)> = None;
4306        for leg in points.windows(2).filter(|leg| leg[0] != leg[1]) {
4307            let copper = Shape::segment(leg[0], leg[1], width);
4308            for (i, item) in conn.items.iter().enumerate() {
4309                if own.contains(&conn.islands[i]) || !(item.layers.0..=item.layers.1).contains(&layer) {
4310                    continue;
4311                }
4312                let (needed, class) = rules.clearance_between_nets(
4313                    nets.iter().map(|n| n.as_str()),
4314                    conn.island_nets[conn.islands[i]].iter().map(String::as_str),
4315                );
4316                let gap = copper.distance(&item.shape);
4317                if gap + 0.5 < f64::from(needed) && worst.as_ref().is_none_or(|w| gap < w.0) {
4318                    worst = Some((gap, i, needed, class.name));
4319                }
4320            }
4321        }
4322        let (gap, i, needed, class) = worst?;
4323        let item = &conn.items[i];
4324        let board = &self.document.board;
4325        let what = match item.owner {
4326            CopperRef::Pad { placement, pad } => board.placements.get(placement).map_or_else(
4327                || "a pad".to_owned(),
4328                |placement| {
4329                    let number = placement.footprint.pads.get(pad).map_or("", |p| p.number.as_str());
4330                    format!("{} pad {number}", self.reference_of(placement.component))
4331                },
4332            ),
4333            CopperRef::Track { track, .. } => board.tracks.get(track).map_or_else(
4334                || "a track".to_owned(),
4335                |t| format!("a track on {}", layer_name(t.layer, board.layer_count)),
4336            ),
4337            CopperRef::Via(_) => "a via".to_owned(),
4338        };
4339        let nets = &conn.island_nets[conn.islands[i]];
4340        let net = (!nets.is_empty()).then(|| nets.iter().cloned().collect::<Vec<_>>().join(", "));
4341        Some(Clash { gap: gap.max(0.), what, net, at: item.shape.center(), needed, class })
4342    }
4343    /// What part `id`, where it is now, would come down on: its pads against the
4344    /// copper of the board as it was when the drag began (`before`, whose islands
4345    /// carry the nets that copper was on, and which holds the part's own pads where
4346    /// they were), the test DRC makes, made while the part is still moving. A pad
4347    /// is clear of copper on its own net; one that touches copper of another net
4348    /// is a short; and one that joins copper that carries no net yet, or carries
4349    /// none itself, joins it, as DRC will read it. Courtyards are compared on the
4350    /// part's own side, as DRC compares them.
4351    fn landfall(&self, id: Uuid, before: &Connectivity) -> Landfall {
4352        let board = &self.document.board;
4353        let Some(index) = board.placements.iter().position(|p| p.component == id) else {
4354            return Landfall::default();
4355        };
4356        let placement = &board.placements[index];
4357        let reference = self.reference_of(id);
4358        let mut pad_nets = BTreeMap::new();
4359        for (i, item) in before.items.iter().enumerate() {
4360            if let CopperRef::Pad { placement, pad } = item.owner
4361                && placement == index
4362            {
4363                pad_nets.insert(pad, before.item_nets[i].clone());
4364            }
4365        }
4366        let mut copper = vec![];
4367        for (k, pad) in placement.footprint.pads.iter().enumerate() {
4368            let shape = placement.pad_shape(pad);
4369            let layers = placement.pad_layers(pad, board.layer_count);
4370            let net = pad_nets.get(&k).cloned().flatten();
4371            let mut worst: Option<(f64, usize, i32, String)> = None;
4372            for (i, item) in before.items.iter().enumerate() {
4373                if matches!(item.owner, CopperRef::Pad { placement, .. } if placement == index)
4374                    || layers.0 > item.layers.1
4375                    || item.layers.0 > layers.1
4376                {
4377                    continue;
4378                }
4379                let theirs = &before.island_nets[before.islands[i]];
4380                if net.as_ref().is_some_and(|net| theirs.contains(net)) {
4381                    continue;
4382                }
4383                let (needed, class) =
4384                    board.rules.clearance_between_nets(net.as_deref(), theirs.iter().map(String::as_str));
4385                let gap = shape.distance(&item.shape);
4386                let joins = gap <= 0.5 && (net.is_none() || theirs.is_empty());
4387                if gap + 0.5 < f64::from(needed) && !joins && worst.as_ref().is_none_or(|w| gap < w.0) {
4388                    worst = Some((gap, i, needed, class.name));
4389                }
4390            }
4391            if let Some((gap, i, needed, class)) = worst {
4392                let item = &before.items[i];
4393                let what = match item.owner {
4394                    CopperRef::Pad { placement, pad } => board.placements.get(placement).map_or_else(
4395                        || "a pad".to_owned(),
4396                        |other| {
4397                            let number = other.footprint.pads.get(pad).map_or("", |p| p.number.as_str());
4398                            format!("{} pad {number}", self.reference_of(other.component))
4399                        },
4400                    ),
4401                    CopperRef::Track { track, .. } => board.tracks.get(track).map_or_else(
4402                        || "a track".to_owned(),
4403                        |t| format!("a track on {}", layer_name(t.layer, board.layer_count)),
4404                    ),
4405                    CopperRef::Via(_) => "a via".to_owned(),
4406                };
4407                let nets = &before.island_nets[before.islands[i]];
4408                let on = (!nets.is_empty()).then(|| nets.iter().cloned().collect::<Vec<_>>().join(", "));
4409                let mine = if pad.number.is_empty() {
4410                    format!("a mechanical pad of {reference}")
4411                } else {
4412                    format!("{reference} pad {}", pad.number)
4413                };
4414                copper.push((mine, Clash { gap: gap.max(0.), what, net: on, at: item.shape.center(), needed, class }));
4415            }
4416        }
4417        copper.sort_by(|a, b| a.1.gap.total_cmp(&b.1.gap));
4418        let (a0, a1) = placement.courtyard();
4419        let courtyards = board
4420            .placements
4421            .iter()
4422            .enumerate()
4423            .filter(|(j, other)| *j != index && other.bottom == placement.bottom)
4424            .filter(|(_, other)| {
4425                let (b0, b1) = other.courtyard();
4426                a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y
4427            })
4428            .map(|(_, other)| (self.reference_of(other.component).to_owned(), other.at))
4429            .collect();
4430        Landfall { copper, courtyards }
4431    }
4432    /// The next leg of the draft, from its last point to `target`: the corner the
4433    /// user chose, or the other one when the chosen one comes within the
4434    /// clearance of another net's copper and the other does not. A leg that
4435    /// clears neither way is drawn as chosen, with its clash.
4436    fn draft_leg(&self, conn: &Connectivity, draft: &Draft, target: Point, ends_on_copper: bool) -> Leg {
4437        let last = *draft.points.last().unwrap();
4438        let origin = Self::draft_origin(draft);
4439        let end = ends_on_copper.then_some(target);
4440        let chosen = self.board_view.diagonal_first;
4441        let try_corner = |diagonal_first: bool| {
4442            let points = corner(last, target, diagonal_first);
4443            let clash = self.route_clash(conn, (draft.layer, draft.width), origin, end, &points);
4444            (points, clash)
4445        };
4446        let (points, clash) = try_corner(chosen);
4447        if let Some(avoided) = clash.clone() {
4448            let (other, other_clash) = try_corner(!chosen);
4449            if other != points && other_clash.is_none() {
4450                return Leg { points: other, clash: None, avoided: Some(avoided) };
4451            }
4452        }
4453        Leg { points, clash, avoided: None }
4454    }
4455    /// Begin a track at `at`: on a pad's layer (the active one when the pad reaches
4456    /// it) at its net's width, on a track's layer at its width, or else on the active
4457    /// layer at the board's default width.
4458    fn start_draft(&mut self, at: Point, anchor: Option<Anchor>) {
4459        let active = self.board_view.active_layer;
4460        let on = |layers: (u8, u8)| if (layers.0..=layers.1).contains(&active) { active } else { layers.0 };
4461        let (layer, width) = match anchor {
4462            Some(Anchor::Pad { layers, width }) => (on(layers), width),
4463            // From a via: on the active layer if the via reaches it, else its first.
4464            Some(Anchor::Via { layers }) => (on(layers), self.document.board.rules.track_width),
4465            Some(Anchor::Track { layer, width }) => (layer, width),
4466            _ => (active, self.document.board.rules.track_width),
4467        };
4468        self.board_view.active_layer = layer;
4469        self.board_view.draft = Some(Draft {
4470            layer,
4471            width,
4472            points: vec![at],
4473            tracks: vec![],
4474            vias: vec![],
4475        });
4476    }
4477    /// The board's clickable things for [`Editor::hits`], in the board's own
4478    /// canvas: each part's courtyard, its numbered pads and its silkscreen
4479    /// lines, each track's longest segment's middle and each of its interior
4480    /// corners, each via.
4481    pub(crate) fn board_hits(&self) -> Vec<(String, Rect)> {
4482        let view = &self.board_view;
4483        let board = &self.document.board;
4484        let (_, zoom) = view.pan_zoom();
4485        // The board canvas's empty corners, `canvas:corner` and `canvas:far`:
4486        // a drag from one to the other draws a box over everything Fit shows.
4487        let mut out = vec![
4488            ("canvas:corner".to_string(), Rect::from_min_size(view.canvas.min + Vec2::splat(4.), Vec2::splat(8.))),
4489            ("canvas:far".to_string(), Rect::from_min_size(view.canvas.max - Vec2::splat(12.), Vec2::splat(8.))),
4490        ];
4491        for p in &board.placements {
4492            let reference = self
4493                .document
4494                .components
4495                .iter()
4496                .find(|c| c.id == p.component)
4497                .map_or_else(|| p.component.to_string(), |c| c.reference.clone());
4498            let (min, max) = p.courtyard();
4499            out.push((
4500                format!("part:{reference}"),
4501                Rect::from_two_pos(view.screen(min), view.screen(max)),
4502            ));
4503            // A pad is keyed by its part and its number, as a sheet pin is
4504            // (`pin:R1.2`). A MECHANICAL pad has no number to be keyed by and
4505            // publishes none; it is clicked by its place on the canvas.
4506            for pad in p.footprint.pads.iter().filter(|pad| !pad.number.is_empty()) {
4507                let (min, max) = p.pad_shape(pad).bounds();
4508                let rect = Rect::from_two_pos(view.screen(min), view.screen(max));
4509                out.push((
4510                    format!("pad:{reference}.{}", pad.number),
4511                    Rect::from_center_size(rect.center(), rect.size().max(Vec2::splat(8.))),
4512                ));
4513            }
4514            // A silkscreen line is keyed by its part and its index, as the Pads
4515            // editor keys it by its index alone (`silk:0`): a small rect on the
4516            // middle of its longest segment. When a pad, a track or another line
4517            // covers that middle, the next longest segment whose middle the canvas
4518            // DOES answer with this line is used instead, so a click on the rect's
4519            // centre always selects what the key names.
4520            // A drawn item is keyed the same way, after the lines
4521            // (`Footprint::drawing`'s order).
4522            for (index, drawn) in p.footprint.drawing().enumerate() {
4523                let mut middles: Vec<(f32, Pos2)> = drawn
4524                    .strokes
4525                    .iter()
4526                    .flat_map(|line| line.windows(2))
4527                    .map(|s| {
4528                        (
4529                            view.screen(p.transform(s[0])),
4530                            view.screen(p.transform(s[1])),
4531                        )
4532                    })
4533                    .map(|(a, b)| (a.distance(b), a.lerp(b, 0.5)))
4534                    .collect();
4535                middles.sort_by(|a, b| b.0.total_cmp(&a.0));
4536                let Some(&(_, longest)) = middles.first() else {
4537                    continue;
4538                };
4539                let at = middles
4540                    .iter()
4541                    .map(|m| m.1)
4542                    .find(|&m| self.hit_board(m) == Some(BoardSelection::Silk(p.component, index)))
4543                    .unwrap_or(longest);
4544                out.push((
4545                    format!("silk:{reference}.{index}"),
4546                    Rect::from_center_size(at, Vec2::splat(8.)),
4547                ));
4548            }
4549        }
4550        for (i, t) in board.tracks.iter().enumerate() {
4551            let longest = t
4552                .points
4553                .windows(2)
4554                .map(|s| (view.screen(s[0]), view.screen(s[1])))
4555                .max_by(|a, b| a.0.distance(a.1).total_cmp(&b.0.distance(b.1)));
4556            if let Some((a, b)) = longest {
4557                out.push((
4558                    format!("track:{i}"),
4559                    Rect::from_center_size(a.lerp(b, 0.5), Vec2::splat(8.)),
4560                ));
4561            }
4562            // Each corner a drag can take, keyed by its point's index in the track.
4563            for j in 1..t.points.len().saturating_sub(1) {
4564                out.push((
4565                    format!("track:{i}.corner:{j}"),
4566                    Rect::from_center_size(view.screen(t.points[j]), Vec2::splat(8.)),
4567                ));
4568            }
4569        }
4570        for (i, v) in board.vias.iter().enumerate() {
4571            let size = (v.diameter as f32 * zoom).max(8.);
4572            out.push((
4573                format!("via:{i}"),
4574                Rect::from_center_size(view.screen(v.at), Vec2::splat(size)),
4575            ));
4576        }
4577        // A zone by its index: a small rect a quarter of the way along its longest
4578        // edge (the middle is the selected zone's new-corner handle), each corner
4579        // by its index, and, on the selected zone, each edge's middle.
4580        for (i, zone) in board.zones.iter().enumerate() {
4581            let n = zone.outline.len();
4582            let longest = (0..n).max_by_key(|&k| {
4583                let (a, b) = (zone.outline[k], zone.outline[(k + 1) % n]);
4584                i64::from(a.x - b.x).pow(2) + i64::from(a.y - b.y).pow(2)
4585            });
4586            if let Some(k) = longest {
4587                let (a, b) = (view.screen(zone.outline[k]), view.screen(zone.outline[(k + 1) % n]));
4588                out.push((format!("zone:{i}"), Rect::from_center_size(a.lerp(b, 0.25), Vec2::splat(8.))));
4589            }
4590            for (j, &c) in zone.outline.iter().enumerate() {
4591                out.push((format!("zone:{i}.corner:{j}"), Rect::from_center_size(view.screen(c), Vec2::splat(8.))));
4592            }
4593            if view.selected == Some(BoardSelection::Zone(zone.id)) {
4594                for (j, m) in edge_middles(&zone.outline).into_iter().enumerate() {
4595                    out.push((format!("zone:{i}.edge:{j}"), Rect::from_center_size(view.screen(m), Vec2::splat(8.))));
4596                }
4597            }
4598        }
4599        // A board drawing by its index, where a click selects it: text at the
4600        // middle of its letters' box; a line at the middle of its longest
4601        // segment, else at a quarter, three quarters, a tenth or nine tenths of
4602        // it, else along the next longest. A drawing that copper covers at every
4603        // one of those points publishes no key: a key that clicks the copper
4604        // instead would select, and let Delete remove, the wrong thing.
4605        for (i, g) in board.graphics.iter().enumerate() {
4606            let strokes = g.graphic.strokes(!g.graphic.layer.front());
4607            let candidates: Vec<Pos2> = if matches!(g.graphic.shape, GraphicShape::Text { .. }) {
4608                let all: Vec<Pos2> = strokes.iter().flatten().map(|p| view.screen(*p)).collect();
4609                (!all.is_empty()).then(|| Rect::from_points(&all).center()).into_iter().collect()
4610            } else {
4611                let mut segments: Vec<(Pos2, Pos2)> = strokes
4612                    .iter()
4613                    .flat_map(|line| line.windows(2))
4614                    .map(|s| (view.screen(s[0]), view.screen(s[1])))
4615                    .collect();
4616                segments.sort_by(|a, b| b.0.distance(b.1).total_cmp(&a.0.distance(a.1)));
4617                segments
4618                    .into_iter()
4619                    .flat_map(|(a, b)| [0.5, 0.25, 0.75, 0.1, 0.9].map(|t| a.lerp(b, t)))
4620                    .collect()
4621            };
4622            if let Some(at) = candidates.into_iter().find(|&m| self.hit_board(m) == Some(BoardSelection::Drawing(g.id))) {
4623                out.push((format!("drawing:{i}"), Rect::from_center_size(at, Vec2::splat(8.))));
4624            }
4625        }
4626        // A cutout by its index, where a click selects it: the middle of its
4627        // corners' box, else the middle of one of its edges. None where some
4628        // other item answers at every one of those points.
4629        for (i, c) in board.cutouts.iter().enumerate() {
4630            let corners: Vec<Pos2> = c.points.iter().map(|p| view.screen(*p)).collect();
4631            let n = corners.len();
4632            let candidates = std::iter::once(Rect::from_points(&corners).center())
4633                .chain((0..n).map(|k| corners[k].lerp(corners[(k + 1) % n], 0.5)));
4634            if let Some(at) = candidates.into_iter().find(|&m| self.hit_board(m) == Some(BoardSelection::Cutout(c.id))) {
4635                out.push((format!("cutout:{i}"), Rect::from_center_size(at, Vec2::splat(8.))));
4636            }
4637        }
4638        // The selected drawing's or cutout's grab handles, `handle:<name>`.
4639        for (h, at) in self.board_handles() {
4640            out.push((format!("handle:{}", h.name()), grips::handle_rect(h, view.screen(at))));
4641        }
4642        out.extend(view.menu.iter().cloned());
4643        out.extend(view.inspector.shown(view.canvas_pass));
4644        out.extend(view.toolbar_hits.shown(view.canvas_pass));
4645        out
4646    }
4647    /// Whether a Select-tool press at `p` would start a drag.
4648    fn grabbable(&self, p: Pos2) -> bool {
4649        match self.hit_board(p) {
4650            Some(BoardSelection::Track(_)) => self.grip_at(p).is_some(),
4651            other => other.is_some(),
4652        }
4653    }
4654    /// What a press at `p` would grab of the track it hits, if it hits one.
4655    fn grip_at(&self, p: Pos2) -> Option<Grip> {
4656        let board = &self.document.board;
4657        let Some(BoardSelection::Track(id)) = self.hit_board(p) else {
4658            return None;
4659        };
4660        let track = board.tracks.iter().find(|t| t.id == id)?;
4661        grip(
4662            board,
4663            track,
4664            self.board_view.world(p),
4665            self.board_view.tolerance(),
4666        )
4667    }
4668    /// The grab handles the selected board drawing or cutout wears, in board
4669    /// micrometres ([`grips`]); none for anything else.
4670    fn board_handles(&self) -> Vec<(Handle, Point)> {
4671        let board = &self.document.board;
4672        match self.board_view.selected {
4673            Some(BoardSelection::Drawing(id)) => board
4674                .graphics
4675                .iter()
4676                .find(|g| g.id == id)
4677                .map(|g| grips::graphic_handles(&g.graphic.shape))
4678                .unwrap_or_default(),
4679            Some(BoardSelection::Cutout(id)) => {
4680                board.cutouts.iter().find(|c| c.id == id).map(|c| grips::ring_handles(&c.points)).unwrap_or_default()
4681            }
4682            _ => vec![],
4683        }
4684    }
4685    /// The selected drawing's or cutout's handle under `p`, if any.
4686    fn board_handle_at(&self, p: Pos2) -> Option<Handle> {
4687        let view = &self.board_view;
4688        grips::handle_at(&self.board_handles(), |q| view.screen(q), p)
4689    }
4690    /// What a held handle has made of the selected drawing or cutout, for the
4691    /// words beside the pointer.
4692    fn board_grip_readout(&self, handle: Handle) -> Option<String> {
4693        let mm = grips::mm;
4694        let at = self.board_handles().into_iter().find(|(h, _)| *h == handle)?.1;
4695        let board = &self.document.board;
4696        let shape = match self.board_view.selected? {
4697            BoardSelection::Drawing(id) => Some(board.graphics.iter().find(|g| g.id == id)?.graphic.shape.clone()),
4698            _ => None,
4699        };
4700        Some(match (shape, handle) {
4701            (Some(GraphicShape::Circle { radius, .. }), _) => format!("r {} mm", mm(radius)),
4702            (Some(GraphicShape::Text { height, .. }), _) => format!("height {} mm", mm(height)),
4703            (_, Handle::Box(..)) => {
4704                let handles = self.board_handles();
4705                let xs = handles.iter().map(|(_, p)| p.x);
4706                let ys = handles.iter().map(|(_, p)| p.y);
4707                let w = xs.clone().max()? - xs.min()?;
4708                let h = ys.clone().max()? - ys.min()?;
4709                format!("{} × {} mm", mm(w), mm(h))
4710            }
4711            _ => format!("{}, {} mm", mm(at.x), mm(at.y)),
4712        })
4713    }
4714    fn hit_board(&self, p: Pos2) -> Option<BoardSelection> {
4715        let view = &self.board_view;
4716        let board = &self.document.board;
4717        let q = view.world(p);
4718        let tolerance = view.tolerance();
4719        // The SELECTED track's own handles come first, before vias and pads. A
4720        // corner a route bent beside a via or a pad is drawn over it, and with
4721        // either first that handle could be seen and never taken. Only its
4722        // handles — a corner, or a free end — and only once the track is
4723        // selected: with nothing selected the via or pad still wins, and a press
4724        // on a segment's body still reaches whatever is under it. So does a press
4725        // on a HELD end, which `grip` never offers: an end resting on a via is
4726        // joined to it, and dragging the via is how that join is kept.
4727        if let Some(BoardSelection::Track(id)) = view.selected
4728            && let Some(track) = board.tracks.iter().find(|t| t.id == id)
4729            && view.visible(track.layer)
4730            && let Some(Grip::Vertex(_)) = grip(board, track, q, tolerance)
4731        {
4732            return Some(BoardSelection::Track(id));
4733        }
4734        // The SELECTED drawing's or cutout's grab handles, for the same reason.
4735        if let Some(selected @ (BoardSelection::Drawing(_) | BoardSelection::Cutout(_))) = view.selected
4736            && self.board_handle_at(p).is_some()
4737        {
4738            return Some(selected);
4739        }
4740        // The SELECTED zone's corners and edge middles too, for the same reason:
4741        // a corner put down on a pad would otherwise be the pad's.
4742        if let Some(BoardSelection::Zone(id)) = view.selected
4743            && let Some(zone) = board.zones.iter().find(|z| z.id == id)
4744            && view.visible(zone.layer)
4745            && zone
4746                .outline
4747                .iter()
4748                .chain(&edge_middles(&zone.outline))
4749                .any(|&c| view.screen(c).distance(p) <= 7.)
4750        {
4751            return Some(BoardSelection::Zone(id));
4752        }
4753        if let Some(v) = board
4754            .vias
4755            .iter()
4756            .rev()
4757            .find(|v| Shape::circle(v.at, v.diameter / 2).distance_to_point(q) <= tolerance)
4758        {
4759            return Some(BoardSelection::Via(v.id));
4760        }
4761        // Pads come before TRACKS, because a routed pad wears a track's end in
4762        // the middle of it: with tracks first, the pad a user is aiming at is
4763        // exactly the part of it that is covered. A track is still selected
4764        // anywhere along its run.
4765        //
4766        // A pad is picked when the pointer is ON it, with NO slack at all — not
4767        // the tolerance the rest of this uses, and not the generous one ROUTING
4768        // snaps with. Slack only buys anything while a pad is small on screen,
4769        // and that is exactly when it would swallow the space between a part's
4770        // pads and leave no way to select the part itself. A pad too small to aim
4771        // at is reached from the part's own pad list instead.
4772        for placement in board.placements.iter().rev() {
4773            for (index, pad) in placement.footprint.pads.iter().enumerate() {
4774                let layers = placement.pad_layers(pad, board.layer_count);
4775                if (layers.0..=layers.1).any(|l| view.visible(l))
4776                    && placement.pad_shape(pad).contains(q)
4777                {
4778                    return Some(BoardSelection::Pad(placement.component, index));
4779                }
4780            }
4781        }
4782        let mut tracks: Vec<&Track> = board
4783            .tracks
4784            .iter()
4785            .filter(|t| view.visible(t.layer))
4786            .collect();
4787        tracks.sort_by_key(|t| t.layer != view.active_layer);
4788        if let Some(t) = tracks
4789            .into_iter()
4790            .find(|t| t.segments().any(|s| s.distance_to_point(q) <= tolerance))
4791        {
4792            return Some(BoardSelection::Track(t.id));
4793        }
4794        // SILKSCREEN after copper and before the courtyard: a line is legend
4795        // printed over the part, so copper under it is what a user is aiming at
4796        // when the two cross, and the courtyard around it is what they get when
4797        // they miss the line. A line is caught within the pointer tolerance of
4798        // any of its segments, the topmost part's first, as it is drawn.
4799        // A part's other drawn items answer the same way, after its lines.
4800        for placement in board.placements.iter().rev() {
4801            for (index, drawn) in placement.footprint.drawing().enumerate() {
4802                let near = drawn.strokes.iter().flat_map(|line| line.windows(2)).any(|s| {
4803                    let (a, b) = (placement.transform(s[0]), placement.transform(s[1]));
4804                    Shape::segment(a, b, 0).distance_to_point(q) <= tolerance
4805                });
4806                if near {
4807                    return Some(BoardSelection::Silk(placement.component, index));
4808                }
4809            }
4810        }
4811        // What is drawn on the board itself, after the parts' own legend: within
4812        // the pointer tolerance of its lines, or inside it when it is filled.
4813        if let Some(g) = board.graphics.iter().rev().find(|g| board_drawing_hit(g, q, tolerance)) {
4814            return Some(BoardSelection::Drawing(g.id));
4815        }
4816        // A zone's OUTLINE, after all the copper and legend that sit on it and
4817        // before the courtyards it runs through: the active layer's zones first.
4818        let mut zones: Vec<&Zone> = board.zones.iter().filter(|z| view.visible(z.layer)).collect();
4819        zones.sort_by_key(|z| z.layer != view.active_layer);
4820        let n = |z: &Zone| z.outline.len();
4821        if let Some(z) = zones.iter().find(|z| {
4822            (0..n(z)).any(|i| {
4823                Shape::segment(z.outline[i], z.outline[(i + 1) % n(z)], 0).distance_to_point(q) <= tolerance
4824            })
4825        }) {
4826            return Some(BoardSelection::Zone(z.id));
4827        }
4828        // A cutout, after everything drawn over the board and before the parts
4829        // whose courtyards it may cut into: within the pointer tolerance of its
4830        // edge, or inside it.
4831        if let Some(c) = board.cutouts.iter().rev().find(|c| {
4832            brep_ecad_core::board::polygon_contains(&c.points, q)
4833                || (0..c.points.len()).any(|i| {
4834                    let (a, b) = (c.points[i], c.points[(i + 1) % c.points.len()]);
4835                    Shape::segment(a, b, 0).distance_to_point(q) <= tolerance
4836                })
4837        }) {
4838            return Some(BoardSelection::Cutout(c.id));
4839        }
4840        let bottom_first = view.active_layer + 1 == board.layer_count && board.layer_count > 1;
4841        let part = board
4842            .placements
4843            .iter()
4844            .filter(|p| {
4845                let (min, max) = p.courtyard();
4846                q.x >= min.x && q.x <= max.x && q.y >= min.y && q.y <= max.y
4847            })
4848            .min_by_key(|p| {
4849                let (min, max) = p.courtyard();
4850                (
4851                    p.bottom != bottom_first,
4852                    i64::from(max.x - min.x) * i64::from(max.y - min.y),
4853                )
4854            })
4855            .map(|p| BoardSelection::Part(p.component));
4856        // Inside a zone, last: a zone covers most of a board, and everything on
4857        // it comes first.
4858        part.or_else(|| {
4859            zones
4860                .iter()
4861                .find(|z| z.fill.iter().any(|piece| piece.contains(q)) || brep_ecad_core::board::polygon_contains(&z.outline, q))
4862                .map(|z| BoardSelection::Zone(z.id))
4863        })
4864    }
4865
4866    /// Draw and interact with the board inside any egui Ui.
4867    pub(crate) fn show_board(&mut self, ui: &mut egui::Ui) {
4868        let (response, painter) = ui.allocate_painter(ui.available_size(), Sense::click_and_drag());
4869        let rect = response.rect;
4870        self.board_view.canvas = rect;
4871        self.board_view.canvas_pass = ui.ctx().cumulative_pass_nr();
4872        self.board_view.menu.clear();
4873        self.canvas_size = rect.size();
4874        if !self.board_view.fitted {
4875            self.board_view.fit(&self.document.board);
4876        }
4877        self.seed_fill_baseline();
4878        let ctx = ui.ctx().clone();
4879        let pointer = ui
4880            .input(|i| i.pointer.hover_pos())
4881            .filter(|p| rect.contains(*p));
4882        if !self.routing() {
4883            self.board_input(ui, &response, pointer);
4884        }
4885        let netlist = self.document.netlist();
4886        let conn = self.document.board.connectivity(&netlist);
4887        let airwires = self.document.board.ratsnest(&conn);
4888        self.board_view.unrouted = airwires.len();
4889        // The leg a click would add now, judged for clearance while it is only a
4890        // preview: the click places this very leg ([`Self::route_click`]).
4891        let leg = match (&self.board_view.draft, pointer) {
4892            (Some(draft), Some(p)) => {
4893                let (target, anchor) = self.route_target(p);
4894                Some(self.draft_leg(&conn, draft, target, anchor.is_some()))
4895            }
4896            _ => None,
4897        };
4898        self.paint_board(&painter, &airwires, pointer, leg.as_ref());
4899        if let (Some((from, _)), Some(to)) = (self.board_view.boxing, pointer) {
4900            crate::footprint_editor::paint_box(&painter, from, to, ACCENT);
4901        }
4902        if let Some(p) = pointer {
4903            let q = self.board_view.world(p);
4904            // Say which pad is under the pointer BEFORE a click commits to it,
4905            // with the net it is on: a board is mostly small targets, and the
4906            // reference silkscreened over a part does not name its pads.
4907            let under = match self.hit_board(p) {
4908                Some(BoardSelection::Pad(id, index)) => {
4909                    self.pad_at(id, index)
4910                        .map(|(reference, pad)| {
4911                            // This frame's netlist, not another derivation of it: the
4912                            // pointer moves sixty times a second and the sheet has not.
4913                            let net = netlist.nets.iter().find(|net| {
4914                                !pad.number.is_empty()
4915                                    && net.pins.iter().any(|pin| {
4916                                        pin.component_id == id && pin.number == pad.number
4917                                    })
4918                            });
4919                            match (net, pad.number.is_empty()) {
4920                                (Some(net), _) => {
4921                                    format!(" · {reference}.{} on {}", pad.number, net.name)
4922                                }
4923                                (None, true) => format!(" · mechanical pad of {reference}"),
4924                                (None, false) => format!(" · {reference}.{}, no net", pad.number),
4925                            }
4926                        })
4927                        .unwrap_or_default()
4928                }
4929                Some(BoardSelection::Silk(id, index)) => {
4930                    format!(" · {} of {}", self.drawing_name(id, index), self.reference_of(id))
4931                }
4932                Some(BoardSelection::Zone(id)) => self
4933                    .document
4934                    .board
4935                    .zones
4936                    .iter()
4937                    .find(|z| z.id == id)
4938                    .map(|z| format!(" · {}", zones::describe(z, self.document.board.layer_count)))
4939                    .unwrap_or_default(),
4940                Some(BoardSelection::Drawing(id)) => format!(" · {}", self.board_drawing_name(id)),
4941                Some(BoardSelection::Cutout(id)) => format!(" · {}", self.board_cutout_name(id)),
4942                _ => String::new(),
4943            };
4944            // A draft too close to another net says so on the line the pointer
4945            // is read from, as the preview turns the warning colour.
4946            let clearance = leg.as_ref().and_then(|leg| leg.clash.as_ref()).map_or_else(String::new, |clash| {
4947                if clash.crosses() {
4948                    format!(" · short: {}", clash.words())
4949                } else {
4950                    format!(" · clearance: {}, {}", clash.words(), clash.needed_words())
4951                }
4952            });
4953            // A part being dragged onto another net's copper or another part says so
4954            // on the same line, as a draft does, before it is let go.
4955            let placing = match (&self.board_view.placing, self.board_view.drag.as_ref().map(|d| d.3)) {
4956                (Some((_, landfall)), Some(Subject::Part(id))) => landfall
4957                    .words(self.reference_of(id))
4958                    .map_or_else(String::new, |words| format!(" · {words}")),
4959                _ => String::new(),
4960            };
4961            self.status = format!(
4962                "PCB · {:.2}, {:.2} mm · {} · {} unrouted · {:.0}%{under}{clearance}{placing}",
4963                mm(q.x),
4964                mm(q.y),
4965                layer_name(
4966                    self.board_view.active_layer,
4967                    self.document.board.layer_count
4968                ),
4969                airwires.len(),
4970                self.board_view.zoom / 0.012 * 100.
4971            );
4972        }
4973        self.poll_autoroute(&ctx);
4974    }
4975    fn board_input(&mut self, ui: &mut egui::Ui, response: &egui::Response, pointer: Option<Pos2>) {
4976        // A line in the Inspector is news about the last thing done, and it is spent
4977        // by the next press on the board, as the sheet's notice is: whatever that
4978        // press goes on to do, the user has moved on. First in the frame, so a line
4979        // this frame says (a key's refusal, the release that ends a drag) is kept.
4980        if response.hovered() && ui.input(|i| i.pointer.primary_pressed()) {
4981            self.board_view.message.clear();
4982        }
4983        // The wheel zooms about the pointer and needs it on the board; the keys do
4984        // not (`keys_reach_editor`).
4985        if response.hovered()
4986            && !ui.ctx().egui_wants_keyboard_input()
4987            && let Some((factor, p)) = crate::pointer_zoom(ui)
4988        {
4989            self.board_view.zoom_about(factor, p);
4990        }
4991        let pinch = crate::pinching(ui);
4992        if pinch {
4993            self.board_view.boxing = None;
4994        }
4995        if pinch && let Some((before, ..)) = self.board_view.drag.take() {
4996            self.document = before;
4997            self.board_view.placing = None;
4998            self.board_view.landing = None;
4999        }
5000        if crate::keys_reach_editor(ui.ctx()) {
5001            self.run_shortcuts(ui.ctx());
5002        }
5003        if response.dragged_by(PointerButton::Middle)
5004            || response.dragged_by(PointerButton::Secondary)
5005        {
5006            self.board_view.pan += ui.input(|i| i.pointer.delta());
5007        }
5008        if response.secondary_clicked()
5009            && !pointer.and_then(|p| self.hit_board(p)).is_some_and(|h| self.board_view.count() > 1 && self.board_view.is_member(h))
5010        {
5011            self.board_view.draft = None;
5012            self.board_view.selected = pointer.and_then(|p| self.hit_board(p));
5013        }
5014        response.context_menu(|ui| {
5015            menu_ui(ui);
5016            match self.board_view.selected {
5017                Some(
5018                    BoardSelection::Part(_) | BoardSelection::Pad(..) | BoardSelection::Silk(..),
5019                ) => {
5020                    // A pad's menu is its part's, with the pad named at the top so
5021                    // a right-click that landed on a pad says what it caught, and
5022                    // one entry to step up to the whole part.
5023                    if let Some(BoardSelection::Pad(id, index)) = self.board_view.selected {
5024                        let title = self
5025                            .pad_at(id, index)
5026                            .map(|(reference, pad)| pad_title(reference, pad));
5027                        if let Some(title) = title {
5028                            ui.label(egui::RichText::new(title).small());
5029                        }
5030                        let reference = self.reference_of(id).to_owned();
5031                        let select = ui.button(format!("Select {reference}"));
5032                        self.board_view.menu.push(("menuitem:select_part".into(), select.rect));
5033                        if select.clicked() {
5034                            self.board_view.selected = Some(BoardSelection::Part(id));
5035                            ui.close();
5036                        }
5037                        let route = ui.button("Route from this pad");
5038                        self.board_view.menu.push(("menuitem:route_from_here".into(), route.rect));
5039                        if route.clicked() {
5040                            self.set_board_tool(BoardTool::Route);
5041                            ui.close();
5042                        }
5043                    }
5044                    // A silk line's menu is its part's too, named the same way.
5045                    if let Some(BoardSelection::Silk(id, index)) = self.board_view.selected {
5046                        let reference = self.reference_of(id).to_owned();
5047                        let name = self.drawing_name(id, index);
5048                        ui.label(egui::RichText::new(format!("{reference} · {name}")).small());
5049                        let select = ui.button(format!("Select {reference}"));
5050                        self.board_view.menu.push(("menuitem:select_part".into(), select.rect));
5051                        if select.clicked() {
5052                            self.board_view.selected = Some(BoardSelection::Part(id));
5053                            ui.close();
5054                        }
5055                    }
5056                    let rotate = ui.button("Rotate 90°");
5057                    self.board_view.menu.push(("menuitem:rotate".into(), rotate.rect));
5058                    if rotate.clicked() {
5059                        self.rotate_selection();
5060                        ui.close();
5061                    }
5062                    let flip = ui.button("Flip side");
5063                    self.board_view.menu.push(("menuitem:flip_side".into(), flip.rect));
5064                    if flip.clicked() {
5065                        self.flip_part();
5066                        ui.close();
5067                    }
5068                }
5069                Some(selected) => {
5070                    if matches!(selected, BoardSelection::Zone(_)) {
5071                        let fill = ui.button("Fill zones");
5072                        self.board_view.menu.push(("menuitem:fill_zones".into(), fill.rect));
5073                        if fill.clicked() {
5074                            self.fill_zones();
5075                            ui.close();
5076                        }
5077                    }
5078                    if matches!(selected, BoardSelection::Via(_)) {
5079                        let route = ui.button("Route from this via");
5080                        self.board_view.menu.push(("menuitem:route_from_here".into(), route.rect));
5081                        if route.clicked() {
5082                            self.set_board_tool(BoardTool::Route);
5083                            ui.close();
5084                        }
5085                    }
5086                    let delete = ui.button("Delete");
5087                    self.board_view.menu.push(("menuitem:delete".into(), delete.rect));
5088                    if delete.clicked() {
5089                        self.delete_board_selection();
5090                        ui.close();
5091                    }
5092                }
5093                None => {
5094                    ui.close();
5095                }
5096            }
5097        });
5098        match self.board_view.tool {
5099            BoardTool::Select => {
5100                // Say what a press would take hold of before it is pressed.
5101                if let Some((.., Subject::DrawingHandle(_, h) | Subject::CutoutHandle(_, h))) = self.board_view.drag {
5102                    ui.ctx().set_cursor_icon(h.cursor());
5103                } else if self.board_view.drag.is_some() {
5104                    ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
5105                } else if let Some(h) = pointer.and_then(|p| self.board_handle_at(p)) {
5106                    ui.ctx().set_cursor_icon(h.cursor());
5107                } else if let Some(p) = pointer
5108                    && self.grabbable(p)
5109                {
5110                    ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
5111                }
5112                if !pinch
5113                    && response.drag_started_by(PointerButton::Primary)
5114                    && let Some(p) = ui.input(|i| i.pointer.press_origin())
5115                {
5116                    let previous = self.board_view.selected;
5117                    // A pad or silk line of a part in a multi-selection stands
5118                    // for its part: pressing one moves the group.
5119                    let hit = self.hit_board(p).map(|h| match part_of(Some(h)) {
5120                        Some(id) if self.board_view.count() > 1 && self.board_view.is_member(BoardSelection::Part(id)) => {
5121                            BoardSelection::Part(id)
5122                        }
5123                        _ => h,
5124                    });
5125                    let mods = ui.input(|i| i.modifiers);
5126                    // A drag from empty board draws a box: Ctrl/Cmd adds, Alt
5127                    // removes. On a member of a multi-selection, or with
5128                    // Ctrl/Cmd held, the whole selection moves.
5129                    let group = hit.is_some_and(|h| {
5130                        self.board_view.count() > 1 && self.board_view.is_member(h) || mods.command
5131                    });
5132                    if hit.is_none() {
5133                        use crate::footprint_editor::BoxMode;
5134                        let mode = if mods.alt { BoxMode::Remove } else if mods.command { BoxMode::Add } else { BoxMode::Replace };
5135                        self.board_view.boxing = Some((p, mode));
5136                    } else if let Some(h) = hit.filter(|_| group) {
5137                        self.board_view.add_member(h);
5138                    } else {
5139                        self.board_view.selected = hit;
5140                    }
5141                    let handle = (previous == self.board_view.selected && !group).then(|| self.board_handle_at(p)).flatten();
5142                    // An edge's middle puts a corner in only on a zone already
5143                    // selected, whose middles are drawn; on any other it drags it.
5144                    let zone_grip = match self.board_view.selected {
5145                        Some(BoardSelection::Zone(id)) => self.zone_grip(id, p).map(|g| match g {
5146                            ZoneGrip::Edge(_) if previous != Some(BoardSelection::Zone(id)) => ZoneGrip::Body,
5147                            g => g,
5148                        }),
5149                        _ => None,
5150                    };
5151                    // Parts, vias and tracks are all dragged. Dragging a PAD drags
5152                    // the part it belongs to — a pad cannot move on its own, and
5153                    // grabbing one is how a part with pads over most of its body is
5154                    // grabbed — while the SELECTION stays the pad the user pressed on.
5155                    // A silkscreen line is the same: it drags its part.
5156                    // A track is grabbed by a corner or by a segment; see `grip`.
5157                    let q = self.board_view.world(p);
5158                    let board = &self.document.board;
5159                    let grabbed = match self.board_view.selected {
5160                        _ if self.board_view.boxing.is_some() => None,
5161                        _ if group => Some((Subject::Group, q)),
5162                        Some(
5163                            BoardSelection::Part(id)
5164                            | BoardSelection::Pad(id, _)
5165                            | BoardSelection::Silk(id, _),
5166                        ) => board.placement(id).map(|p| (Subject::Part(id), p.at)),
5167                        Some(BoardSelection::Via(id)) => board
5168                            .vias
5169                            .iter()
5170                            .find(|v| v.id == id)
5171                            .map(|v| (Subject::Via(id), v.at)),
5172                        Some(BoardSelection::Track(id)) => board
5173                            .tracks
5174                            .iter()
5175                            .find(|t| t.id == id)
5176                            .and_then(|t| grip(board, t, q, self.board_view.tolerance()))
5177                            .map(|g| (Subject::Track(id, g), q)),
5178                        Some(BoardSelection::Zone(id)) => zone_grip.map(|g| (Subject::Zone(id, g), q)),
5179                        // A handle of the drawing or cutout ALREADY selected
5180                        // sizes it; anywhere else on it moves it.
5181                        Some(BoardSelection::Drawing(id)) => match handle {
5182                            Some(h) => Some((Subject::DrawingHandle(id, h), q)),
5183                            None => Some((Subject::Drawing(id), q)),
5184                        },
5185                        Some(BoardSelection::Cutout(id)) => match handle {
5186                            Some(h) => Some((Subject::CutoutHandle(id, h), q)),
5187                            None => Some((Subject::Cutout(id), q)),
5188                        },
5189                        None => None,
5190                    };
5191                    if let Some((what, at)) = grabbed {
5192                        self.board_view.drag = Some((self.document.clone(), q, at, what));
5193                        self.board_view.landing = None;
5194                        self.board_view.placing = matches!(what, Subject::Part(_)).then(|| {
5195                            let conn = self.document.board.connectivity(&self.document.netlist());
5196                            (conn, Landfall::default())
5197                        });
5198                    }
5199                }
5200                if let (Some((before, start, at, what)), Some(p)) = (&self.board_view.drag, pointer)
5201                {
5202                    let q = self.board_view.world(p);
5203                    // Snap the offset, not the position, so what moves keeps its existing
5204                    // alignment: a part stays where it sat between the grid's lines, and a
5205                    // via or a track keeps whatever pitch the autorouter left it on.
5206                    let raw = Point::new(q.x - start.x, q.y - start.y);
5207                    let mut delta = snap(raw, PLACE_GRID);
5208                    // A free END over a pad of its own net goes to the pad's centre
5209                    // rather than to the nearest grid step, which lands on a pad's
5210                    // centre only when the geometry happens to put it there.
5211                    let landing = match *what {
5212                        Subject::Track(id, Grip::Vertex(i)) => before
5213                            .board
5214                            .tracks
5215                            .iter()
5216                            .find(|t| t.id == id)
5217                            .and_then(|t| t.points.get(i))
5218                            .and_then(|end| land_end(before, id, i, end.offset(raw))),
5219                        _ => None,
5220                    };
5221                    if let Some(landing) = landing.filter(|l| l.joins) {
5222                        delta = landing.delta;
5223                    }
5224                    self.board_view.landing = landing;
5225                    let (target, what) = (at.offset(delta), *what);
5226                    let keep = ui.input(|i| i.modifiers.shift);
5227                    self.document = before.clone();
5228                    let board = &mut self.document.board;
5229                    match what {
5230                        Subject::Group => {
5231                            let members = self.board_view.members();
5232                            Self::move_board_group(board, &members, delta);
5233                        }
5234                        Subject::Part(id) => {
5235                            if let Some(p) = board.placements.iter_mut().find(|p| p.component == id)
5236                            {
5237                                p.at = target;
5238                            }
5239                        }
5240                        Subject::Via(id) => move_via(board, id, delta),
5241                        Subject::Track(id, Grip::Vertex(i)) => move_vertex(board, id, i, delta),
5242                        Subject::Track(id, Grip::Segment(k)) => slide_segment(board, id, k, delta),
5243                        // The fill is taken away while the outline moves, and made
5244                        // again when it is let go: a fill that trailed the outline
5245                        // would show copper the zone no longer asks for.
5246                        Subject::Zone(id, grip) if delta != Point::default() => {
5247                            if let Some(zone) = board.zones.iter_mut().find(|z| z.id == id) {
5248                                zone.outline = dragged_outline(&zone.outline, grip, delta);
5249                                zone.fill.clear();
5250                            }
5251                        }
5252                        Subject::Zone(..) => {}
5253                        Subject::Drawing(id) => {
5254                            if let Some(g) = board.graphics.iter_mut().find(|g| g.id == id) {
5255                                move_graphic(&mut g.graphic, delta);
5256                            }
5257                        }
5258                        Subject::Cutout(id) => {
5259                            if let Some(c) = board.cutouts.iter_mut().find(|c| c.id == id) {
5260                                for p in &mut c.points {
5261                                    *p = Point::new(p.x + delta.x, p.y + delta.y);
5262                                }
5263                            }
5264                        }
5265                        // A handle goes to the pointer's grid point; Shift keeps
5266                        // a box's proportions.
5267                        Subject::DrawingHandle(id, h) => {
5268                            let to = snap(q, PLACE_GRID);
5269                            if let (Some(g), Some(was)) = (
5270                                board.graphics.iter_mut().find(|g| g.id == id),
5271                                before.board.graphics.iter().find(|g| g.id == id),
5272                            ) {
5273                                grips::drag_graphic(&mut g.graphic.shape, &was.graphic.shape, h, to, keep);
5274                                // A shape no drawing may have is not taken.
5275                                if g.graphic.problem().is_some() {
5276                                    g.graphic.shape = was.graphic.shape.clone();
5277                                }
5278                            }
5279                        }
5280                        Subject::CutoutHandle(id, h) => {
5281                            let to = snap(q, PLACE_GRID);
5282                            if let (Some(c), Some(was)) = (
5283                                board.cutouts.iter_mut().find(|c| c.id == id),
5284                                before.board.cutouts.iter().find(|c| c.id == id),
5285                            ) {
5286                                grips::drag_ring(&mut c.points, &was.points, h, to, keep);
5287                            }
5288                        }
5289                    }
5290                    if let Subject::Part(id) = what
5291                        && let Some((before, _)) = &self.board_view.placing
5292                    {
5293                        let landfall = self.landfall(id, before);
5294                        if let Some((_, now)) = &mut self.board_view.placing {
5295                            *now = landfall;
5296                        }
5297                    }
5298                }
5299                if response.drag_stopped_by(PointerButton::Primary)
5300                    && let (Some((from, mode)), Some(to)) = (self.board_view.boxing.take(), pointer)
5301                {
5302                    self.board_box_select(Rect::from_two_pos(from, to), to.x < from.x, mode);
5303                }
5304                if response.drag_stopped_by(PointerButton::Primary)
5305                    && let Some((before, ..)) = self.board_view.drag.take()
5306                {
5307                    let members = self.board_view.members();
5308                    // An end left on another net's pad is not snapped, and says why.
5309                    if let Some(landing) = self.board_view.landing.take()
5310                        && !landing.joins
5311                        && let Some((reference, pad)) =
5312                            self.pad_at(landing.component, landing.index)
5313                    {
5314                        let on = self
5315                            .pad_net(landing.component, &pad.number)
5316                            .map_or_else(|| "no net".to_owned(), |net| format!("net {net}"));
5317                        self.board_view.message = format!(
5318                            "{} is on {on}, not this track's: the end was left on its grid step instead of snapped to the pad's centre. Check the board to see the short.",
5319                            pad_title(reference, pad)
5320                        );
5321                    }
5322                    // A part put down on another net's copper, or on another part, is
5323                    // put down, as a route that clears no corner is drawn; and the
5324                    // line the status bar showed while it moved stays in the
5325                    // Inspector, where it outlasts the drag.
5326                    if let Some((_, landfall)) = self.board_view.placing.take()
5327                        && let Some(BoardSelection::Part(id) | BoardSelection::Pad(id, _) | BoardSelection::Silk(id, _)) =
5328                            self.board_view.selected
5329                        && before.board != self.document.board
5330                    {
5331                        let reference = self.reference_of(id).to_owned();
5332                        if let Some(words) = landfall.words(&reference) {
5333                            let mut words = words;
5334                            words[..1].make_ascii_uppercase();
5335                            self.board_view.message = format!(
5336                                "{words}. {reference} was put down there; move it clear, or Undo puts it back."
5337                            );
5338                        }
5339                    }
5340                    // A zone moved is refilled, all zones with it — the one it now
5341                    // overlaps may be first in line — inside the same undo step.
5342                    let zone_moved = before.board.zones.len() == self.document.board.zones.len()
5343                        && before
5344                            .board
5345                            .zones
5346                            .iter()
5347                            .zip(&self.document.board.zones)
5348                            .any(|(a, b)| a.outline != b.outline);
5349                    // A cutout moved off the board, or onto another, is put back,
5350                    // and said; one moved fairly is refilled round, as a zone is.
5351                    let cutout_moved = before.board.cutouts != self.document.board.cutouts;
5352                    let board = &self.document.board;
5353                    let refused = cutout_moved
5354                        .then(|| {
5355                            board.cutouts.iter().enumerate().find_map(|(n, c)| {
5356                                board.cutout_problem(&c.points, Some(n)).map(|why| format!("Not moved: cutout {} {why}.", n + 1))
5357                            })
5358                        })
5359                        .flatten();
5360                    if let Some(words) = refused {
5361                        self.document = before;
5362                        self.board_view.message = words;
5363                    } else {
5364                        if zone_moved || (cutout_moved && !self.document.board.zones.is_empty()) {
5365                            let reports = self.document.fill_zones();
5366                            self.note_filled();
5367                            let words = self.zone_reports_words(&reports);
5368                            if let Some(BoardSelection::Zone(id)) = self.board_view.selected
5369                                && let Some(k) = self.document.board.zones.iter().position(|z| z.id == id)
5370                            {
5371                                self.board_view.message = words.get(k).cloned().unwrap_or_default();
5372                            }
5373                        }
5374                        self.commit(before, None);
5375                    }
5376                    // A group drag keeps the group.
5377                    if members.len() > 1 {
5378                        self.board_view.set_members(members);
5379                    }
5380                }
5381                if response.clicked_by(PointerButton::Primary)
5382                    && let Some(p) = pointer
5383                {
5384                    // Ctrl/Cmd+click adds or takes out one item (a pad or silk
5385                    // line, its part).
5386                    let hit = self.hit_board(p);
5387                    match hit {
5388                        Some(h) if ui.input(|i| i.modifiers.command) => {
5389                            self.board_view.toggle_member(part_of(Some(h)).map_or(h, BoardSelection::Part));
5390                        }
5391                        _ if ui.input(|i| i.modifiers.command) => {}
5392                        hit => self.board_view.selected = hit,
5393                    }
5394                }
5395            }
5396            BoardTool::Zone => {
5397                if response.double_clicked_by(PointerButton::Primary) {
5398                    self.finish_zone();
5399                } else if response.clicked_by(PointerButton::Primary)
5400                    && let Some(p) = pointer
5401                {
5402                    self.zone_click(p);
5403                }
5404            }
5405            BoardTool::Draw => {
5406                if response.double_clicked_by(PointerButton::Primary) {
5407                    self.finish_drawing();
5408                } else if response.clicked_by(PointerButton::Primary)
5409                    && let Some(p) = pointer
5410                {
5411                    self.drawing_click(p);
5412                }
5413            }
5414            BoardTool::Cutout => {
5415                if response.double_clicked_by(PointerButton::Primary) {
5416                    self.finish_cutout();
5417                } else if response.clicked_by(PointerButton::Primary)
5418                    && let Some(p) = pointer
5419                {
5420                    self.cutout_click(p);
5421                }
5422            }
5423            BoardTool::Text => {
5424                if response.clicked_by(PointerButton::Primary)
5425                    && let Some(p) = pointer
5426                {
5427                    self.text_click(p);
5428                }
5429            }
5430            BoardTool::Route => {
5431                if response.double_clicked_by(PointerButton::Primary) {
5432                    self.finish_draft();
5433                } else if response.clicked_by(PointerButton::Primary)
5434                    && let Some(p) = pointer
5435                {
5436                    self.route_click(p);
5437                }
5438            }
5439        }
5440    }
5441
5442    fn paint_board(&self, painter: &egui::Painter, airwires: &[Airwire], pointer: Option<Pos2>, leg: Option<&Leg>) {
5443        let view = &self.board_view;
5444        let board = &self.document.board;
5445        let count = board.layer_count;
5446        painter.rect_filled(view.canvas, 0., BACKGROUND);
5447        let outline: Vec<Pos2> = board.outline.iter().map(|p| view.screen(*p)).collect();
5448        if board.outline_is_rectangle() {
5449            painter.rect_filled(Rect::from_points(&outline), 0., SUBSTRATE);
5450        }
5451        painter.add(egui::Shape::closed_line(outline, Stroke::new(1.5, EDGE)));
5452        // Each cutout is a hole: the background shows through it. Its edge is
5453        // drawn over the copper, further down.
5454        for c in &board.cutouts {
5455            let ring: Vec<Pos2> = c.points.iter().map(|p| view.screen(*p)).collect();
5456            paint_filled(painter, &ring, BACKGROUND);
5457        }
5458        let paint_shape = |shape: &Shape, color: Color32| match *shape {
5459            Shape::Rect { min, max } => {
5460                painter.rect_filled(
5461                    Rect::from_two_pos(view.screen(min), view.screen(max)),
5462                    0.,
5463                    color,
5464                );
5465            }
5466            Shape::RoundRect { min, max, radius } if view.px(radius) <= crate::footprint_editor::MAX_PAINTED_CORNER => {
5467                painter.rect_filled(
5468                    Rect::from_two_pos(view.screen(min), view.screen(max)),
5469                    view.px(radius),
5470                    color,
5471                );
5472            }
5473            // Wider on screen than egui keeps a corner (a byte): the outline itself.
5474            Shape::RoundRect { .. } => {
5475                let ring: Vec<Pos2> = shape.outline(16).into_iter().map(|p| view.screen(p)).collect();
5476                painter.add(egui::Shape::convex_polygon(ring, color, Stroke::NONE));
5477            }
5478            // A trapezoid or custom pad, which may turn inward.
5479            Shape::Polygon { .. } => {
5480                let ring: Vec<Pos2> = shape.outline(16).into_iter().map(|p| view.screen(p)).collect();
5481                paint_filled(painter, &ring, color);
5482            }
5483            Shape::Capsule { a, b, radius } => {
5484                let r = view.px(radius).max(0.5);
5485                let (a, b) = (view.screen(a), view.screen(b));
5486                if a != b {
5487                    painter.line_segment([a, b], Stroke::new(2. * r, color));
5488                    painter.circle_filled(b, r, color);
5489                }
5490                painter.circle_filled(a, r, color);
5491            }
5492        };
5493        let paint_track = |track: &Track, color: Color32| {
5494            for shape in track.segments() {
5495                paint_shape(&shape, color);
5496            }
5497        };
5498        let routed: Vec<(&[Track], &[Via])> = view.job.iter().flat_map(|j| j.routed()).collect();
5499        let active = view.active_layer.min(count - 1);
5500        let layers: Vec<u8> = (0..count)
5501            .rev()
5502            .filter(|l| *l != active)
5503            .chain(std::iter::once(active))
5504            .filter(|l| view.visible(*l))
5505            .collect();
5506        let stale = self.zones_stale();
5507        for &layer in &layers {
5508            let base = layer_color(layer, count);
5509            let color = if layer == active {
5510                base.gamma_multiply(0.9)
5511            } else {
5512                base.gamma_multiply(0.45)
5513            };
5514            // A zone under everything else on its layer: its fill as the layer's
5515            // colour, see-through, and its outline dashed round it.
5516            for zone in board.zones.iter().filter(|z| z.layer == layer) {
5517                // Fainter than the layer's tracks and pads, which are drawn over
5518                // it in the layer's full colour, so copper on the zone's net still
5519                // reads as tracks and pads and not as more fill.
5520                let fill = if layer == active { base.gamma_multiply(0.3) } else { base.gamma_multiply(0.14) };
5521                let mut mesh = egui::epaint::Mesh::default();
5522                for piece in &zone.fill {
5523                    let rings: Vec<&[Point]> = std::iter::once(piece.outer.as_slice())
5524                        .chain(piece.holes.iter().map(Vec::as_slice))
5525                        .collect();
5526                    for tri in zones::fill_triangles(&rings) {
5527                        let base_index = mesh.vertices.len() as u32;
5528                        for (x, y) in tri {
5529                            let at = view.canvas.center() + view.pan + Vec2::new(x as f32, y as f32) * view.zoom;
5530                            mesh.colored_vertex(at, fill);
5531                        }
5532                        mesh.add_triangle(base_index, base_index + 1, base_index + 2);
5533                    }
5534                }
5535                painter.add(egui::Shape::mesh(mesh));
5536                let mut ring: Vec<Pos2> = zone.outline.iter().map(|p| view.screen(*p)).collect();
5537                ring.extend(ring.first().copied());
5538                let edge = if stale { WARNING.gamma_multiply(0.8) } else { base.gamma_multiply(0.8) };
5539                painter.extend(egui::Shape::dashed_line(&ring, Stroke::new(1.2, edge), 6., 4.));
5540            }
5541            for placement in &board.placements {
5542                for pad in placement
5543                    .footprint
5544                    .pads
5545                    .iter()
5546                    .filter(|p| p.drill.is_none())
5547                {
5548                    if placement.pad_layers(pad, count).0 == layer {
5549                        paint_shape(&placement.pad_shape(pad), color);
5550                    }
5551                }
5552            }
5553            for track in board.tracks.iter().filter(|t| t.layer == layer) {
5554                let selected = view.is_member(BoardSelection::Track(track.id));
5555                paint_track(
5556                    track,
5557                    if selected {
5558                        base.lerp_to_gamma(Color32::WHITE, 0.5)
5559                    } else {
5560                        color
5561                    },
5562                );
5563            }
5564            for (tracks, _) in &routed {
5565                for track in tracks.iter().filter(|t| t.layer == layer) {
5566                    paint_track(track, color);
5567                }
5568            }
5569            if let Some(draft) = &view.draft {
5570                for track in draft.tracks.iter().filter(|t| t.layer == layer) {
5571                    paint_track(track, base);
5572                }
5573            }
5574        }
5575        let paint_via = |via: &Via, selected: bool| {
5576            let at = view.screen(via.at);
5577            // A blind or buried via that does not reach the active layer is drawn
5578            // faint: it is not copper there.
5579            let (from, to) = via.layers(count);
5580            let here = (from..=to).contains(&view.active_layer.min(count - 1));
5581            let color = if selected { ACCENT } else if here { VIA } else { VIA.gamma_multiply(0.35) };
5582            painter.circle_filled(at, view.px(via.diameter / 2).max(1.5), color);
5583            painter.circle_filled(at, view.px(via.drill / 2).max(0.8), BACKGROUND);
5584        };
5585        for placement in &board.placements {
5586            for pad in placement.footprint.pads.iter() {
5587                if let Some(hole) = placement.pad_hole(pad) {
5588                    paint_shape(&placement.pad_shape(pad), THROUGH_HOLE);
5589                    paint_shape(&hole, BACKGROUND);
5590                }
5591            }
5592        }
5593        for via in &board.vias {
5594            paint_via(via, view.is_member(BoardSelection::Via(via.id)));
5595        }
5596        // A pad's own vias: the part's, selected and moved with it.
5597        for (via, _, _) in board.pad_vias() {
5598            paint_via(&via, false);
5599        }
5600        for (_, vias) in &routed {
5601            for via in *vias {
5602                paint_via(via, false);
5603            }
5604        }
5605        if let Some(draft) = &view.draft {
5606            for via in &draft.vias {
5607                paint_via(via, true);
5608            }
5609        }
5610        // The selected track's handles: a square on every corner a drag can take,
5611        // and a ring on each end that is held where it is.
5612        if let Some(BoardSelection::Track(id)) = view.selected
5613            && let Some(track) = board.tracks.iter().find(|t| t.id == id)
5614        {
5615            // Sized from the track's own width, or a fat track hides them.
5616            let size = (view.px(track.width) + 5.).max(9.);
5617            let last = track.points.len().saturating_sub(1);
5618            for (i, &p) in track.points.iter().enumerate() {
5619                let at = view.screen(p);
5620                if (i == 0 || i == last) && held(board, track, p) {
5621                    painter.circle_stroke(at, size / 2., Stroke::new(1.5, ACCENT));
5622                } else {
5623                    let handle = Rect::from_center_size(at, Vec2::splat(size));
5624                    painter.rect_filled(handle, 1., BACKGROUND);
5625                    painter.rect_stroke(
5626                        handle,
5627                        1.,
5628                        Stroke::new(1.5, ACCENT),
5629                        egui::StrokeKind::Inside,
5630                    );
5631                }
5632            }
5633        }
5634        // The selected zone: its outline in the accent, a square on every corner
5635        // and a dot on every edge's middle, which a drag turns into a corner.
5636        if let Some(BoardSelection::Zone(id)) = view.selected
5637            && let Some(zone) = board.zones.iter().find(|z| z.id == id)
5638        {
5639            let mut ring: Vec<Pos2> = zone.outline.iter().map(|p| view.screen(*p)).collect();
5640            ring.extend(ring.first().copied());
5641            painter.add(egui::Shape::line(ring, Stroke::new(1.5, ACCENT)));
5642            for &c in &zone.outline {
5643                let handle = Rect::from_center_size(view.screen(c), Vec2::splat(9.));
5644                painter.rect_filled(handle, 1., BACKGROUND);
5645                painter.rect_stroke(handle, 1., Stroke::new(1.5, ACCENT), egui::StrokeKind::Inside);
5646            }
5647            for m in edge_middles(&zone.outline) {
5648                painter.circle_filled(view.screen(m), 3.5, ACCENT.gamma_multiply(0.8));
5649            }
5650            if stale {
5651                painter.text(
5652                    view.screen(zone.outline[0]) + Vec2::new(8., -8.),
5653                    Align2::LEFT_BOTTOM,
5654                    stale_words(board),
5655                    FontId::proportional(12.),
5656                    WARNING,
5657                );
5658            }
5659        } else if stale && let Some(zone) = board.zones.first() {
5660            // With no zone selected, the same words at the first zone's first
5661            // corner: a fill saved stale showed only a dashed outline in the
5662            // warning colour, which on a pour drawn to the board's edge lies
5663            // under the board outline and cannot be seen.
5664            painter.text(
5665                view.screen(zone.outline[0]) + Vec2::new(8., -8.),
5666                Align2::LEFT_BOTTOM,
5667                stale_words(board),
5668                FontId::proportional(12.),
5669                WARNING,
5670            );
5671        }
5672        // The zone being drawn: its corners so far, the edge to the pointer, and
5673        // the closing edge back to the first corner dashed.
5674        // The cutouts' edges, over the copper: Edge.Cuts, the selected one in the
5675        // accent.
5676        for c in &board.cutouts {
5677            let ring: Vec<Pos2> = c.points.iter().map(|p| view.screen(*p)).collect();
5678            let chosen = view.is_member(BoardSelection::Cutout(c.id));
5679            painter.add(egui::Shape::closed_line(ring, Stroke::new(if chosen { 2.5 } else { 1.5 }, if chosen { ACCENT } else { EDGE })));
5680        }
5681        if view.tool == BoardTool::Cutout && !view.cutout_draft.is_empty() {
5682            let mut points: Vec<Pos2> = view.cutout_draft.iter().map(|p| view.screen(*p)).collect();
5683            if let Some(p) = pointer {
5684                points.push(view.screen(snap(view.world(p), PLACE_GRID)));
5685            }
5686            painter.add(egui::Shape::line(points.clone(), Stroke::new(1.5, EDGE)));
5687            if points.len() >= 3 {
5688                painter.extend(egui::Shape::dashed_line(&[*points.last().unwrap(), points[0]], Stroke::new(1., EDGE.gamma_multiply(0.7)), 5., 4.));
5689            }
5690            for (i, &c) in view.cutout_draft.iter().enumerate() {
5691                painter.circle_filled(view.screen(c), if i == 0 { 5. } else { 3.5 }, EDGE);
5692            }
5693        }
5694        if view.tool == BoardTool::Zone && !view.zone_draft.is_empty() {
5695            let colour = layer_color(active, count);
5696            let mut points: Vec<Pos2> = view.zone_draft.iter().map(|p| view.screen(*p)).collect();
5697            if let Some(p) = pointer {
5698                points.push(view.screen(snap(view.world(p), PLACE_GRID)));
5699            }
5700            painter.add(egui::Shape::line(points.clone(), Stroke::new(1.5, colour)));
5701            if points.len() >= 3 {
5702                painter.extend(egui::Shape::dashed_line(
5703                    &[*points.last().unwrap(), points[0]],
5704                    Stroke::new(1., colour.gamma_multiply(0.7)),
5705                    5.,
5706                    4.,
5707                ));
5708            }
5709            for (i, &c) in view.zone_draft.iter().enumerate() {
5710                let at = view.screen(c);
5711                painter.circle_filled(at, if i == 0 { 5. } else { 3.5 }, colour);
5712            }
5713        }
5714        if let Some(p) = pointer
5715            && matches!(view.tool, BoardTool::Zone | BoardTool::Draw | BoardTool::Text | BoardTool::Cutout)
5716        {
5717            let at = view.screen(snap(view.world(p), PLACE_GRID));
5718            painter.circle_stroke(at, 5., Stroke::new(1.5, ACCENT));
5719            painter.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
5720        }
5721        // The line being drawn: its corners so far and the segment to the pointer,
5722        // in its layer's colour at its pen.
5723        if view.tool == BoardTool::Draw && !view.drawing_draft.is_empty() {
5724            let colour = graphic_color(view.draw_layer);
5725            let width = (view.draw_width.unwrap_or(view.draw_layer.default_width()) as f32 * view.zoom).max(1.);
5726            let mut points: Vec<Pos2> = view.drawing_draft.iter().map(|p| view.screen(*p)).collect();
5727            if let Some(p) = pointer {
5728                points.push(view.screen(snap(view.world(p), PLACE_GRID)));
5729            }
5730            painter.add(egui::Shape::line(points, Stroke::new(width, colour)));
5731            for (i, &c) in view.drawing_draft.iter().enumerate() {
5732                painter.circle_filled(view.screen(c), if i == 0 { 5. } else { 3.5 }, colour);
5733            }
5734        }
5735        // The pad a dragged free end is coming down on: the accent where it
5736        // snaps to the centre, the warning colour where it is another net's.
5737        if view.drag.is_some()
5738            && let Some(landing) = view.landing
5739            && let Some(placement) = board.placement(landing.component)
5740            && let Some(pad) = placement.footprint.pads.get(landing.index)
5741        {
5742            let (min, max) = placement.pad_shape(pad).bounds();
5743            painter.rect_stroke(
5744                Rect::from_two_pos(view.screen(min), view.screen(max)).expand(3.),
5745                2.,
5746                Stroke::new(2., if landing.joins { ACCENT } else { WARNING }),
5747                egui::StrokeKind::Outside,
5748            );
5749        }
5750        let references: BTreeMap<Uuid, &str> = self
5751            .document
5752            .components
5753            .iter()
5754            .map(|c| (c.id, c.reference.as_str()))
5755            .collect();
5756        // What is drawn on the board itself, each item with its pen, the
5757        // selected one in the accent.
5758        for g in &board.graphics {
5759            let chosen = view.is_member(BoardSelection::Drawing(g.id));
5760            let color = if chosen { ACCENT } else { graphic_color(g.graphic.layer) };
5761            let width = (g.graphic.width() as f32 * view.zoom).max(if chosen { 2. } else { 1. });
5762            let strokes = g.graphic.strokes(!g.graphic.layer.front());
5763            if g.graphic.filled
5764                && let Some(line) = strokes.first()
5765            {
5766                let outline: Vec<Pos2> = line.iter().map(|p| view.screen(*p)).collect();
5767                paint_filled(painter, &outline, color.gamma_multiply(0.6));
5768            }
5769            for line in strokes {
5770                painter.add(egui::Shape::line(line.iter().map(|p| view.screen(*p)).collect(), Stroke::new(width, color)));
5771            }
5772        }
5773        for placement in &board.placements {
5774            let silk = if placement.bottom {
5775                Color32::from_rgb(142, 154, 186)
5776            } else {
5777                SILK
5778            };
5779            let (min, max) = placement.courtyard();
5780            let bounds = Rect::from_two_pos(view.screen(min), view.screen(max));
5781            for (index, line) in placement.footprint.silk.iter().enumerate() {
5782                // A selected line wears the accent, and its part the dimmer
5783                // outline a selected pad gives it: legend is always legend OF a part.
5784                let chosen =
5785                    view.selected == Some(BoardSelection::Silk(placement.component, index));
5786                if chosen {
5787                    painter.rect_stroke(
5788                        bounds,
5789                        2.,
5790                        Stroke::new(1., ACCENT.gamma_multiply(0.4)),
5791                        egui::StrokeKind::Outside,
5792                    );
5793                }
5794                painter.add(egui::Shape::line(
5795                    line.iter()
5796                        .map(|p| view.screen(placement.transform(*p)))
5797                        .collect(),
5798                    if chosen {
5799                        Stroke::new(2.5, ACCENT)
5800                    } else {
5801                        Stroke::new(1., silk.gamma_multiply(0.7))
5802                    },
5803                ));
5804            }
5805            // The footprint's drawn items, each with its own pen: silkscreen in
5806            // its side's colour, fabrication drawing and a drawn courtyard dimmer.
5807            let silk_lines = placement.footprint.silk.len();
5808            for (k, graphic) in placement.footprint.graphics.iter().enumerate() {
5809                let (layer, strokes) = placement.place_graphic(graphic);
5810                let chosen = view.selected == Some(BoardSelection::Silk(placement.component, silk_lines + k));
5811                let color = if chosen { ACCENT } else { graphic_color(layer) };
5812                let width = (graphic.width() as f32 * view.zoom).max(1.);
5813                if graphic.filled
5814                    && let Some(line) = strokes.first()
5815                {
5816                    let outline: Vec<Pos2> = line.iter().map(|p| view.screen(*p)).collect();
5817                    paint_filled(painter, &outline, color.gamma_multiply(0.6));
5818                }
5819                for line in strokes {
5820                    painter.add(egui::Shape::line(
5821                        line.iter().map(|p| view.screen(*p)).collect(),
5822                        Stroke::new(width, color),
5823                    ));
5824                }
5825            }
5826            if bounds.width() > 12. {
5827                painter.text(
5828                    Pos2::new(bounds.center().x, bounds.top() - 2.),
5829                    Align2::CENTER_BOTTOM,
5830                    references.get(&placement.component).copied().unwrap_or("?"),
5831                    FontId::proportional((view.zoom * 1000.).clamp(9., 16.)),
5832                    silk,
5833                );
5834            }
5835            // A pad carries its number as soon as it is big enough on screen to hold
5836            // one, which is how the footprint editor shows them.
5837            for pad in placement
5838                .footprint
5839                .pads
5840                .iter()
5841                .filter(|p| !p.number.is_empty())
5842            {
5843                let Some(height) = pad_number_height(pad.size, view.zoom) else {
5844                    continue;
5845                };
5846                painter.text(
5847                    view.screen(placement.transform(pad.at)),
5848                    Align2::CENTER_CENTER,
5849                    &pad.number,
5850                    FontId::monospace(height),
5851                    Color32::WHITE,
5852                );
5853            }
5854            if view.is_member(BoardSelection::Part(placement.component)) {
5855                painter.rect_stroke(
5856                    bounds,
5857                    2.,
5858                    Stroke::new(1.5, ACCENT),
5859                    egui::StrokeKind::Outside,
5860                );
5861            }
5862            // A selected PAD wears the accent itself, and its part keeps a
5863            // dimmer line of the same colour: a pad is always a pad OF
5864            // something, and at board zoom the part is what a user recognises.
5865            if let Some(BoardSelection::Pad(component, index)) = view.selected
5866                && component == placement.component
5867                && let Some(pad) = placement.footprint.pads.get(index)
5868            {
5869                painter.rect_stroke(
5870                    bounds,
5871                    2.,
5872                    Stroke::new(1., ACCENT.gamma_multiply(0.4)),
5873                    egui::StrokeKind::Outside,
5874                );
5875                let (min, max) = placement.pad_shape(pad).bounds();
5876                painter.rect_stroke(
5877                    Rect::from_two_pos(view.screen(min), view.screen(max)).expand(2.),
5878                    1.,
5879                    Stroke::new(2., ACCENT),
5880                    egui::StrokeKind::Outside,
5881                );
5882            }
5883        }
5884        if view.show_ratsnest {
5885            for wire in airwires {
5886                painter.line_segment(
5887                    [view.screen(wire.a), view.screen(wire.b)],
5888                    Stroke::new(1., Color32::from_rgba_unmultiplied(236, 236, 236, 150)),
5889                );
5890            }
5891        }
5892        if let Some(violations) = &view.violations {
5893            for (i, v) in violations
5894                .iter()
5895                .enumerate()
5896                .filter(|(_, v)| v.kind != ViolationKind::Unrouted)
5897            {
5898                let at = view.screen(v.at);
5899                // The finding the list was last clicked on wears a second, wider
5900                // ring, so it is the one the eye finds among its neighbours.
5901                if view.focused_violation == Some(i) {
5902                    painter.circle_stroke(at, 13., Stroke::new(2.5, WARNING));
5903                }
5904                painter.circle_stroke(at, 7., Stroke::new(2., WARNING));
5905                painter.line_segment(
5906                    [at - Vec2::splat(4.), at + Vec2::splat(4.)],
5907                    Stroke::new(2., WARNING),
5908                );
5909                painter.line_segment(
5910                    [at + Vec2::new(-4., 4.), at + Vec2::new(4., -4.)],
5911                    Stroke::new(2., WARNING),
5912                );
5913            }
5914        }
5915        if let (Some(draft), Some(leg)) = (&view.draft, leg) {
5916            let mut points = draft.points.clone();
5917            points.extend(leg.points.iter().skip(1).copied());
5918            let preview = Track {
5919                id: Uuid::nil(),
5920                layer: draft.layer,
5921                width: draft.width,
5922                fixed_width: false,
5923                points,
5924            };
5925            // Too close to another net: the preview wears the warning colour,
5926            // and the copper it is too close to is ringed, before any click.
5927            let colour = if leg.clash.is_some() { WARNING } else { layer_color(draft.layer, count) };
5928            paint_track(&preview, colour.gamma_multiply(0.85));
5929            if let Some(clash) = &leg.clash {
5930                let at = view.screen(clash.at);
5931                painter.circle_stroke(at, 11., Stroke::new(2., WARNING));
5932                painter.text(
5933                    at + Vec2::new(14., -14.),
5934                    Align2::LEFT_BOTTOM,
5935                    if clash.crosses() { format!("short: {}", clash.words()) } else { format!("{} — clearance", clash.words()) },
5936                    FontId::proportional(13.),
5937                    WARNING,
5938                );
5939            }
5940        }
5941        if let Some(p) = pointer
5942            && view.tool == BoardTool::Route
5943        {
5944            let (target, anchor) = self.route_target(p);
5945            let at = view.screen(target);
5946            painter.circle_stroke(
5947                at,
5948                if anchor.is_some() { 8. } else { 5. },
5949                Stroke::new(1.5, ACCENT),
5950            );
5951            painter.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
5952        }
5953        // A part being dragged onto another net's copper or another part: its
5954        // courtyard and what it would come down on wear the warning colour, and
5955        // the copper is ringed as a draft's clash is. Last, over the selection's
5956        // own outline, which would otherwise hide it.
5957        if let (Some((_, landfall)), Some((.., Subject::Part(id)))) = (&view.placing, &view.drag)
5958            && !landfall.is_clear()
5959            && let Some(placement) = board.placement(*id)
5960        {
5961            let (min, max) = placement.courtyard();
5962            painter.rect_stroke(
5963                Rect::from_two_pos(view.screen(min), view.screen(max)),
5964                2.,
5965                Stroke::new(2., WARNING),
5966                egui::StrokeKind::Outside,
5967            );
5968            for (_, clash) in &landfall.copper {
5969                painter.circle_stroke(view.screen(clash.at), 11., Stroke::new(2., WARNING));
5970            }
5971            for (other, _) in &landfall.courtyards {
5972                if let Some(other) = board.placements.iter().find(|p| self.reference_of(p.component) == other) {
5973                    let (min, max) = other.courtyard();
5974                    painter.rect_stroke(
5975                        Rect::from_two_pos(view.screen(min), view.screen(max)),
5976                        2.,
5977                        Stroke::new(1.5, WARNING.gamma_multiply(0.8)),
5978                        egui::StrokeKind::Outside,
5979                    );
5980                }
5981            }
5982        }
5983        // The selected drawing's or cutout's grab handles, on top; the one held
5984        // or under the pointer filled, and what a held one sets beside the
5985        // pointer.
5986        let handles = self.board_handles();
5987        if !handles.is_empty() {
5988            let held = match view.drag {
5989                Some((.., Subject::DrawingHandle(_, h) | Subject::CutoutHandle(_, h))) => Some(h),
5990                _ => None,
5991            };
5992            let hot = held.or_else(|| {
5993                view.drag.is_none().then(|| pointer.and_then(|p| grips::handle_at(&handles, |q| view.screen(q), p))).flatten()
5994            });
5995            grips::paint_handles(painter, &handles, |q| view.screen(q), hot, ACCENT);
5996            if let (Some(h), Some(p)) = (held, pointer)
5997                && let Some(text) = self.board_grip_readout(h)
5998            {
5999                grips::paint_readout(painter, p, text);
6000            }
6001        }
6002        if board.placements.is_empty() {
6003            painter.text(
6004                view.canvas.center(),
6005                Align2::CENTER_CENTER,
6006                "No parts on the board yet\nAdd native assembly parts with pads, then choose Update from parts",
6007                FontId::proportional(18.),
6008                Color32::from_rgb(119, 137, 158),
6009            );
6010        }
6011    }
6012}
6013