use super::*;
use crate::actions::{Action, ActionGroup, action, command, key};
use crate::board_view::{BACKGROUND, SILK, THROUGH_HOLE, WARNING, layer_color};
use crate::symbol_editor::{InspectorHits, LIST_SHARE, grip_under, key_word, list_height};
use brep_ecad_core::board::{COURTYARD_MARGIN, Footprint, Pad, PadShape, Shape};
#[derive(Clone, Copy, PartialEq, Debug)]
pub(crate) enum DrawTool {
Select,
Pad,
ThroughHole,
Line,
Rectangle,
Circle,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Item {
Pad(usize),
Silk(usize),
}
#[derive(Clone, Copy, PartialEq)]
enum PadKind {
SurfaceMount,
ThroughHole,
Unplated,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum PadLink {
Pin,
NoSuchPin,
Mechanical,
Unknown,
}
fn link_of(number: &str, pins: &[String], known: bool) -> PadLink {
if number.is_empty() {
PadLink::Mechanical
} else if !known {
PadLink::Unknown
} else if pins.iter().any(|pin| pin == number) {
PadLink::Pin
} else {
PadLink::NoSuchPin
}
}
fn link_note(link: PadLink) -> &'static str {
match link {
PadLink::Pin => "On the symbol pin of this number.",
PadLink::NoSuchPin => {
"No pin of the symbol carries this number, so this pad is on no net. Choose a pin below, or make it mechanical."
}
PadLink::Mechanical => {
"Mechanical: no pin and no net. It reaches the copper and drill files and never the netlist."
}
PadLink::Unknown => "No symbol pins are known here, so nothing checks this number.",
}
}
const RING_GAP: f32 = 2.;
const RING_WIDTH: f32 = 2.;
fn link_ring(link: PadLink) -> Option<Color32> {
match link {
PadLink::Pin | PadLink::Unknown => None,
PadLink::Mechanical => Some(Color32::from_gray(132)),
PadLink::NoSuchPin => Some(WARNING),
}
}
#[derive(Clone, Copy)]
enum Mark {
Ring(Color32),
Silk,
}
fn swatch(ui: &mut egui::Ui, mark: Option<Mark>) {
let (rect, _) = ui.allocate_exact_size(Vec2::new(22., 12.), Sense::hover());
let Some(mark) = mark else { return };
let painter = ui.painter();
painter.rect_filled(rect, 2., BACKGROUND);
match mark {
Mark::Ring(colour) => {
let pad = Rect::from_center_size(rect.center(), Vec2::new(10., 4.));
painter.rect_filled(pad, 0., layer_color(0, 2));
painter.rect_stroke(
pad.expand(RING_GAP),
0.,
Stroke::new(RING_WIDTH, colour),
egui::StrokeKind::Outside,
);
}
Mark::Silk => {
painter.line_segment(
[rect.left_center() + Vec2::new(4., 0.), rect.right_center() - Vec2::new(4., 0.)],
Stroke::new(1.5, SILK),
);
}
}
}
const GRIDS: [i32; 8] = [10, 50, 100, 250, 500, 635, 1270, 2540];
fn grid_text(grid: i32) -> String {
match grid {
635 => "0.635 mm (25 mil)".into(),
1270 => "1.27 mm (50 mil)".into(),
2540 => "2.54 mm (100 mil)".into(),
_ => format!("{} mm", mm_text(grid)),
}
}
const SMD_SIZE: Point = Point::new(1500, 900);
const THT_SIZE: Point = Point::new(1700, 1700);
const ITEMS_HEIGHT: f32 = 200.;
const PINS_HEIGHT: f32 = 150.;
const PINS_SHARE: f32 = 0.2;
const PIN_BUTTONS: usize = 8;
pub struct FootprintEditor {
pub footprint: Footprint,
pub target: Option<Uuid>,
pins: Vec<String>,
pin_names: std::collections::BTreeMap<String, String>,
tool: DrawTool,
selected: Option<Item>,
start: Option<Point>,
drag: Option<(Footprint, Point)>,
history: History<Footprint>,
zoom: f32,
pan: Vec2,
fit: bool,
grid: i32,
repeat: (u32, i32, i32),
pending_number: Option<String>,
canvas: Rect,
error: String,
pending_change: Option<Change>,
inspector: InspectorHits,
canvas_pass: u64,
listed: Option<Item>,
items_height: Option<f32>,
pins_height: Option<f32>,
}
impl FootprintEditor {
pub fn new(footprint: Footprint, target: Option<Uuid>, pins: Vec<String>) -> Self {
Self {
footprint,
target,
pins,
pin_names: Default::default(),
tool: DrawTool::Select,
selected: None,
start: None,
drag: None,
history: History::default(),
zoom: 0.08,
pan: Vec2::ZERO,
fit: true,
grid: 50,
repeat: (1, 0, 1270),
pending_number: None,
canvas: Rect::from_min_size(Pos2::ZERO, Vec2::new(800., 600.)),
error: String::new(),
pending_change: None,
inspector: InspectorHits::default(),
canvas_pass: 0,
listed: None,
items_height: None,
pins_height: None,
}
}
pub fn blank() -> Self {
Self::new(
Footprint {
name: "Custom:NewFootprint".into(),
pads: vec![],
silk: vec![],
model: None,
},
None,
vec![],
)
}
fn record(&mut self, before: Footprint) {
self.record_as(before, None);
}
fn record_as(&mut self, before: Footprint, coalesce: Option<&str>) {
if before != self.footprint {
self.history.record(before, &self.footprint);
self.note_change(coalesce.map(str::to_owned));
}
}
fn note_change(&mut self, coalesce: Option<String>) {
Change::record(&mut self.pending_change, coalesce);
}
pub fn take_change(&mut self) -> Option<Change> {
self.pending_change.take()
}
pub fn tool_name(&self) -> &'static str {
match self.tool {
DrawTool::Select => "select",
DrawTool::Pad => "smd",
DrawTool::ThroughHole => "through_hole",
DrawTool::Line => "line",
DrawTool::Rectangle => "rectangle",
DrawTool::Circle => "circle",
}
}
pub fn pan_zoom(&self) -> (Vec2, f32) {
(self.pan, self.zoom)
}
pub fn set_pins(&mut self, pins: Vec<String>) {
self.pins = pins;
}
pub fn set_pin_names(&mut self, pins: Vec<(String, String)>) {
self.pins = pins.iter().map(|(number, _)| number.clone()).collect();
self.pin_names = pins
.into_iter()
.filter_map(|(number, name)| {
let name = crate::pin_name(&name)?.to_owned();
(name != number).then_some((number, name))
})
.collect();
}
fn pin_row(&self, number: &str) -> String {
match self.pin_names.get(number) {
Some(name) => format!("{number} {name}"),
None => number.to_owned(),
}
}
pub fn selected_pad(&self) -> Option<&str> {
match self.selected {
Some(Item::Pad(index)) => {
self.footprint.pads.get(index).map(|pad| pad.number.as_str())
}
_ => None,
}
}
pub fn select_pad(&mut self, number: &str) -> bool {
match self.footprint.pads.iter().position(|pad| pad.number == number) {
Some(index) => {
self.selected = Some(Item::Pad(index));
let at = self.footprint.pads[index].at;
let centre = self.canvas.center() + self.pan;
if !self
.canvas
.shrink(12.)
.contains(on_canvas(centre, self.zoom, at))
{
self.pan = -Vec2::new(at.x as f32, at.y as f32) * self.zoom;
}
true
}
None => false,
}
}
pub fn hits(&self, canvas: Rect) -> Vec<(String, Rect)> {
let center = canvas.center() + self.pan;
let screen = |p: Point| on_canvas(center, self.zoom, p);
let pads = self.footprint.pads.iter().enumerate().map(|(i, pad)| {
let size = Vec2::new(pad.size.x.abs() as f32, pad.size.y.abs() as f32) * self.zoom;
let rect = Rect::from_center_size(screen(pad.at), size.max(Vec2::splat(6.)));
(pad_key(i, pad), rect)
});
let silk = self.footprint.silk.iter().enumerate().filter_map(|(i, line)| {
let (a, b) = line
.windows(2)
.map(|s| (screen(s[0]), screen(s[1])))
.max_by(|a, b| a.0.distance(a.1).total_cmp(&b.0.distance(b.1)))?;
Some((format!("silk:{i}"), Rect::from_center_size(a.lerp(b, 0.5), Vec2::splat(8.))))
});
pads.chain(silk).chain(self.inspector.shown(self.canvas_pass)).collect()
}
pub fn selected_silk(&self) -> Option<usize> {
match self.selected {
Some(Item::Silk(index)) if index < self.footprint.silk.len() => Some(index),
_ => None,
}
}
pub fn set_footprint(&mut self, footprint: Footprint) {
self.footprint = footprint;
self.history = History::default();
self.selected = None;
self.drag = None;
self.start = None;
self.error.clear();
self.pending_change = None;
}
pub fn run_action(&mut self, id: &str) -> bool {
crate::actions::run_action(self, pad_actions().iter(), id)
}
fn set_tool(&mut self, tool: DrawTool) {
if let Some((before, _)) = self.drag.take() {
self.footprint = before;
}
if !matches!(tool, DrawTool::Pad | DrawTool::ThroughHole) {
self.pending_number = None;
}
self.tool = tool;
self.start = None;
}
fn undo(&mut self) {
if self.history.can_undo() {
self.history.undo(&mut self.footprint);
self.selected = None;
self.note_change(None);
}
}
pub(crate) fn step_history(&mut self, key: HistoryKey) {
if self.drag.is_none() {
match key {
HistoryKey::Undo => self.undo(),
HistoryKey::Redo => self.redo(),
}
}
}
pub(crate) fn can_step_history(&self, key: HistoryKey) -> bool {
self.drag.is_none()
&& match key {
HistoryKey::Undo => self.history.can_undo(),
HistoryKey::Redo => self.history.can_redo(),
}
}
fn redo(&mut self) {
if self.history.can_redo() {
self.history.redo(&mut self.footprint);
self.selected = None;
self.note_change(None);
}
}
fn validate(&self) -> Result<(), String> {
self.footprint.validate()
}
fn pins_known(&self) -> bool {
self.target.is_some() || !self.pins.is_empty()
}
fn link(&self, pad: &Pad) -> PadLink {
link_of(&pad.number, &self.pins, self.pins_known())
}
fn link_counts(&self) -> (usize, usize, usize) {
let mut counts = (0, 0, 0);
for pad in &self.footprint.pads {
match self.link(pad) {
PadLink::Pin | PadLink::Unknown => counts.0 += 1,
PadLink::Mechanical => counts.1 += 1,
PadLink::NoSuchPin => counts.2 += 1,
}
}
counts
}
fn orphan_numbers(&self) -> Vec<&str> {
self.footprint
.pads
.iter()
.filter(|pad| self.link(pad) == PadLink::NoSuchPin)
.map(|pad| pad.number.as_str())
.collect()
}
fn item_note(&self, item: Item) -> String {
match item {
Item::Pad(i) => match self.footprint.pads.get(i) {
None => "A pad that is no longer here".to_owned(),
Some(pad) => {
let kind = match (pad.drill, pad.plated) {
(None, _) => "Pad",
(Some(_), true) => "Through-hole pad",
(Some(_), false) => "Unplated hole",
};
match self.link(pad) {
PadLink::Mechanical => format!("{kind} · mechanical"),
PadLink::NoSuchPin => format!("{kind} {} · no pin {}", pad.number, pad.number),
PadLink::Pin | PadLink::Unknown => format!("{kind} {}", pad.number),
}
}
},
Item::Silk(i) => format!("Silkscreen {} · decoration", i + 1),
}
}
fn place_pad_for(&mut self, number: String) {
if !matches!(self.tool, DrawTool::Pad | DrawTool::ThroughHole) {
self.tool = DrawTool::Pad;
}
self.start = None;
self.drag = None;
self.pending_number = Some(number);
}
fn missing_pins(&self) -> Vec<&str> {
self.pins
.iter()
.filter(|pin| !self.footprint.pads.iter().any(|p| &p.number == *pin))
.map(String::as_str)
.collect()
}
fn next_number(&self) -> String {
(1..)
.map(|n: u32| n.to_string())
.find(|n| !self.footprint.pads.iter().any(|p| p.number == *n))
.unwrap_or_default()
}
fn snap(&self, p: Point) -> Point {
let g = f64::from(self.grid);
Point::new(
((f64::from(p.x) / g).round() * g) as i32,
((f64::from(p.y) / g).round() * g) as i32,
)
}
pub fn grid(&self) -> i32 {
self.grid
}
fn set_grid(&mut self, grid: i32) {
if GRIDS.contains(&grid) {
self.grid = grid;
}
}
fn grid_combo(&mut self, ui: &mut egui::Ui, salt: &str) -> egui::Response {
egui::ComboBox::from_id_salt(salt)
.selected_text(format!("Grid {}", grid_text(self.grid)))
.show_ui(ui, |ui| {
for grid in GRIDS {
ui.selectable_value(&mut self.grid, grid, grid_text(grid));
}
})
.response
}
fn close_pads(&self) -> Vec<(usize, usize, f64)> {
let minimum = f64::from(min_pad_gap());
let pads = &self.footprint.pads;
let copper = |pad: &Pad| pad.drill.is_none() || pad.plated;
let mut close = vec![];
for (i, a) in pads.iter().enumerate().filter(|(_, p)| copper(p)) {
for (j, b) in pads.iter().enumerate().skip(i + 1).filter(|(_, p)| copper(p)) {
if !a.number.is_empty() && a.number == b.number {
continue;
}
let gap = Shape::pad(a.at, a.size, a.shape).distance(&Shape::pad(b.at, b.size, b.shape));
if gap + 0.5 < minimum {
close.push((i, j, gap));
}
}
}
close.sort_by(|a, b| a.2.total_cmp(&b.2));
close
}
pub fn toolbar(&mut self, ui: &mut egui::Ui) {
ui.horizontal_wrapped(|ui| {
crate::actions::action_buttons(
self,
pad_actions().iter().filter(|a| !SILK_TOOLS.contains(&a.id)),
ui,
ActionGroup::Tool,
);
ui.separator();
ui.small("Silkscreen");
crate::actions::action_buttons(
self,
pad_actions().iter().filter(|a| SILK_TOOLS.contains(&a.id)),
ui,
ActionGroup::Tool,
);
ui.separator();
for group in [ActionGroup::History, ActionGroup::Zoom] {
crate::actions::action_buttons(self, pad_actions().iter(), ui, group);
}
self.grid_combo(ui, "footprint-grid");
});
ui.label(match (self.pending_number.clone(), self.tool) {
(Some(pin), _) => format!(
"Click to place the pad for pin {pin}; it is on that pin from the moment it exists. Select puts the tool down."
),
(None, DrawTool::Select) => {
"Select or drag an item. Right-drag pans. Scroll zooms. Pads are viewed from the top.".to_owned()
}
(None, DrawTool::Pad | DrawTool::ThroughHole) => {
"Click to place a pad, or drag to draw its outline. A new pad takes the lowest free number; Item properties puts it on a pin.".to_owned()
}
_ => {
"Drag to draw silkscreen — decoration, on no pin and no net. Item properties can turn a rectangle or a circle into a pad.".to_owned()
}
});
}
fn legend(&self, ui: &mut egui::Ui) {
let (_, mechanical, orphans) = self.link_counts();
if mechanical == 0 && orphans == 0 && self.footprint.silk.is_empty() {
return;
}
ui.horizontal_wrapped(|ui| {
ui.small("On the canvas:");
if let Some(ring) = link_ring(PadLink::Mechanical).filter(|_| mechanical > 0) {
swatch(ui, Some(Mark::Ring(ring)));
ui.small("grey ring — mechanical, on no pin");
}
if let Some(ring) = link_ring(PadLink::NoSuchPin).filter(|_| orphans > 0) {
swatch(ui, Some(Mark::Ring(ring)));
ui.label(
egui::RichText::new("orange ring — no pin of that number")
.small()
.color(ui.visuals().warn_fg_color),
);
}
if !self.footprint.silk.is_empty() {
swatch(ui, Some(Mark::Silk));
ui.small("thin line — silkscreen, decoration");
}
});
}
pub fn show(&mut self, ui: &mut egui::Ui) {
let size = ui.available_size();
self.canvas(ui, size);
}
pub fn run_shortcuts(&mut self, ctx: &egui::Context) {
if crate::keys_reach_editor(ctx) {
let actions: Vec<_> = pad_actions().iter().collect();
crate::actions::run_shortcuts(self, &actions, ctx);
}
}
pub(crate) fn window(&mut self, ctx: &egui::Context) -> Option<bool> {
let mut open = true;
let mut action = None;
self.run_shortcuts(ctx);
egui::Window::new("Footprint editor")
.id(egui::Id::new("footprint_editor"))
.default_size(Vec2::new(980., 680.))
.min_size(Vec2::new(660., 460.))
.open(&mut open)
.collapsible(false)
.show(ctx, |ui| {
self.toolbar(ui);
ui.separator();
ui.horizontal_top(|ui| {
let height = (ui.available_height() - 55.).max(300.);
ui.allocate_ui_with_layout(
Vec2::new(250., height),
egui::Layout::top_down(egui::Align::Min),
|ui| self.properties(ui),
);
let size = Vec2::new(ui.available_width().max(300.), height);
self.canvas(ui, size);
});
ui.separator();
if !self.error.is_empty() {
ui.colored_label(ui.visuals().error_fg_color, &self.error);
}
ui.horizontal(|ui| {
if ui.button("Apply footprint").clicked() {
match self.validate() {
Ok(()) => action = Some(true),
Err(e) => self.error = e,
}
}
if ui.button("Cancel").clicked() {
action = Some(false);
}
ui.small(if self.target.is_some() {
"Updates this part and the session footprint library."
} else {
"Adds or updates this footprint in the session library."
});
});
});
if !open {
action = Some(false);
}
action
}
pub fn properties(&mut self, ui: &mut egui::Ui) {
let pane = ui.available_height();
self.inspector.begin(ui.ctx());
egui::ScrollArea::vertical()
.id_salt("footprint_inspector")
.auto_shrink([false, true])
.show(ui, |ui| self.inspector_body(ui, pane));
}
fn inspector_body(&mut self, ui: &mut egui::Ui, pane: f32) {
let before = self.footprint.clone();
ui.label("Footprint name");
let name = ui.text_edit_singleline(&mut self.footprint.name);
self.inspector.mark("footprint_name", &name);
ui.small(format!(
"{} · {}",
crate::count(self.footprint.pads.len(), "pad", "pads"),
crate::count(self.footprint.silk.len(), "silkscreen line", "silkscreen lines")
));
let (on_pins, mechanical, orphans) = self.link_counts();
if self.pins_known() && !self.footprint.pads.is_empty() {
ui.small(format!("{on_pins} on a pin · {mechanical} mechanical"));
}
if orphans > 0 {
ui.label(
egui::RichText::new(format!(
"{orphans} on no pin: {}",
self.orphan_numbers().join(", ")
))
.color(ui.visuals().warn_fg_color),
);
}
self.legend(ui);
ui.horizontal(|ui| {
ui.label("Snap");
let grid = self.grid_combo(ui, "footprint-grid-inspector");
self.inspector.mark("grid", &grid);
});
let close = self.close_pads();
if let Some(&(i, j, gap)) = close.first() {
let pads = &self.footprint.pads;
let name = |k: usize| {
let number = &pads[k].number;
if number.is_empty() { format!("mechanical pad {}", k + 1) } else { format!("pad {number}") }
};
let more = match close.len() {
1 => String::new(),
n => format!(" ({} more pairs)", n - 1),
};
let warning = ui.label(
egui::RichText::new(format!(
"{} and {} are {} mm apart; pads need {} mm between them{more}.",
name(i),
name(j),
mm_text(gap.round() as i32),
mm_text(min_pad_gap()),
))
.color(ui.visuals().warn_fg_color),
);
self.inspector.mark("gap_warning", &warning);
}
let reveal = self.selected != self.listed;
self.pins_section(ui, pane, reveal);
ui.separator();
ui.label("Items");
let notes: Vec<(Item, String, Option<Mark>)> = self
.footprint
.pads
.iter()
.enumerate()
.map(|(i, pad)| {
(
Item::Pad(i),
self.item_note(Item::Pad(i)),
link_ring(self.link(pad)).map(Mark::Ring),
)
})
.chain((0..self.footprint.silk.len()).map(|i| {
(Item::Silk(i), self.item_note(Item::Silk(i)), Some(Mark::Silk))
}))
.collect();
let reveal = self.selected != self.listed;
let selected = self.selected;
let mut pick = None;
let keys: Vec<String> = self
.footprint
.pads
.iter()
.enumerate()
.map(|(i, pad)| format!("row:{}", pad_key(i, pad)))
.chain((0..self.footprint.silk.len()).map(|i| format!("row:silk:{i}")))
.collect();
let hits = &mut self.inspector;
let list = egui::ScrollArea::vertical()
.id_salt("footprint_items")
.max_height(list_height(self.items_height, pane, LIST_SHARE, ITEMS_HEIGHT))
.show(ui, |ui| {
if notes.is_empty() {
ui.small("Nothing drawn yet. Place a pad with the SMD or Through-hole tool.");
}
let warn = ui.visuals().warn_fg_color;
for ((item, note, mark), key) in notes.iter().zip(&keys) {
let orphan = matches!(mark, Some(Mark::Ring(c)) if *c == WARNING);
let text = if orphan && selected != Some(*item) {
egui::RichText::new(note).color(warn)
} else {
egui::RichText::new(note)
};
let row = ui
.horizontal(|ui| {
swatch(ui, *mark);
ui.selectable_label(selected == Some(*item), text)
})
.inner;
if reveal && selected == Some(*item) {
row.scroll_to_me(Some(egui::Align::Center));
}
hits.mark(key, &row);
if row.clicked() {
pick = Some(*item);
}
}
});
if let Some(grip) = grip_under(ui, &list, &mut self.items_height) {
self.inspector.mark("items_grip", &grip);
}
if let Some(item) = pick {
self.selected = Some(item);
}
self.listed = self.selected;
ui.separator();
ui.label("Item properties");
match self.selected {
Some(Item::Pad(i)) if i < self.footprint.pads.len() => self.pad_properties(ui, i),
Some(Item::Silk(i)) if i < self.footprint.silk.len() => self.silk_properties(ui, i),
_ => {
ui.small("Select an item on the canvas or in the list.");
}
}
if self.selected.is_some() {
let delete = ui.button("Delete item");
self.inspector.mark("delete", &delete);
if delete.clicked() {
self.remove_selected();
}
}
self.record_as(before, Some("pads:properties"));
}
fn pins_section(&mut self, ui: &mut egui::Ui, pane: f32, reveal: bool) {
if !self.pins_known() {
return;
}
ui.separator();
ui.label("Symbol pins");
if self.pins.is_empty() {
ui.small("This part's symbol has no pins, so every pad here is mechanical.");
return;
}
let rows: Vec<(String, String, Option<usize>)> = self
.pins
.iter()
.map(|pin| {
let pad = self.footprint.pads.iter().position(|p| p.number == *pin);
(pin.clone(), self.pin_row(pin), pad)
})
.collect();
let selected = self.selected;
let armed = self.pending_number.clone();
let (mut pick, mut place, mut cancel) = (None, None, false);
let hits = &mut self.inspector;
let list = egui::ScrollArea::vertical()
.id_salt("footprint_pins")
.max_height(list_height(self.pins_height, pane, PINS_SHARE, PINS_HEIGHT))
.show(ui, |ui| {
for (pin, shown, pad) in &rows {
ui.horizontal_wrapped(|ui| match pad {
Some(index) => {
let row = ui
.selectable_label(
selected == Some(Item::Pad(*index)),
format!("{shown} · pad"),
)
.on_hover_text("Select this pin's pad");
if reveal && selected == Some(Item::Pad(*index)) {
row.scroll_to_me(Some(egui::Align::Center));
}
hits.mark(format!("pin:{pin}:pad"), &row);
if row.clicked() {
pick = Some(*index);
}
}
None => {
ui.label(
egui::RichText::new(format!("{shown} · no pad"))
.color(ui.visuals().warn_fg_color),
);
let waiting = armed.as_deref() == Some(pin.as_str());
let label = if waiting {
"Cancel".to_owned()
} else {
format!("Place pad for pin {pin}")
};
let button = ui.selectable_label(waiting, label).on_hover_text(format!(
"The next click on the canvas puts a pad there, already on pin {pin}"
));
hits.mark(format!("place_pad:{pin}"), &button);
if button.clicked() {
if waiting {
cancel = true;
} else {
place = Some(pin.clone());
}
}
}
});
}
});
if let Some(grip) = grip_under(ui, &list, &mut self.pins_height) {
self.inspector.mark("pins_grip", &grip);
}
if let Some(index) = pick {
self.selected = Some(Item::Pad(index));
}
if let Some(pin) = place {
self.place_pad_for(pin);
}
if cancel {
self.pending_number = None;
}
if self.missing_pins().is_empty() {
ui.small("Every symbol pin has a pad.");
}
}
fn silk_properties(&mut self, ui: &mut egui::Ui, i: usize) {
ui.horizontal(|ui| {
swatch(ui, Some(Mark::Silk));
ui.label("Silkscreen line");
});
ui.small(
"Decoration: it prints on the silkscreen film. It carries no pin and no net, so there is nothing to link it to.",
);
if let Some((at, size, shape)) = silk_as_pad(&self.footprint.silk[i]) {
let number = self
.missing_pins()
.first()
.map(|pin| (*pin).to_owned())
.unwrap_or_else(|| self.next_number());
let make = ui.button(format!("Make this a pad on pin {number}")).on_hover_text(
"Replaces this outline with copper of the same size and place. Offered for a rectangle or a circle, which are the two shapes a pad comes in.",
);
self.inspector.mark("make_pad", &make);
if make.clicked() {
self.footprint.silk.remove(i);
self.selected = Some(Item::Pad(self.footprint.pads.len()));
self.footprint.pads.push(Pad {
number,
at,
size,
shape,
drill: None,
plated: true,
});
return;
}
}
for (n, p) in self.footprint.silk[i].iter_mut().enumerate() {
point_fields(ui, &mut self.inspector, &format!("Point {}", n + 1), p);
}
}
fn pad_properties(&mut self, ui: &mut egui::Ui, i: usize) {
let pins = self.pins.clone();
let known = self.pins_known();
let free: Vec<String> = self.missing_pins().into_iter().map(str::to_owned).collect();
let pad = &mut self.footprint.pads[i];
let hits = &mut self.inspector;
let mut kind = match (pad.drill, pad.plated) {
(None, _) => PadKind::SurfaceMount,
(Some(_), true) => PadKind::ThroughHole,
(Some(_), false) => PadKind::Unplated,
};
let choice = egui::ComboBox::from_label("Type")
.selected_text(kind_name(kind))
.show_ui(ui, |ui| {
for k in [
PadKind::SurfaceMount,
PadKind::ThroughHole,
PadKind::Unplated,
] {
ui.selectable_value(&mut kind, k, kind_name(k));
}
});
hits.mark("type", &choice.response);
let default_drill = (pad.size.x.min(pad.size.y) * 6 / 10 / 50 * 50).max(100);
match kind {
PadKind::SurfaceMount => {
pad.drill = None;
pad.plated = true;
}
PadKind::ThroughHole => {
pad.drill = Some(pad.drill.unwrap_or(default_drill));
pad.plated = true;
}
PadKind::Unplated => {
if pad.plated || pad.drill.is_none() {
pad.number.clear();
}
pad.drill = Some(pad.drill.unwrap_or(pad.size.x.min(pad.size.y)));
pad.plated = false;
}
}
ui.separator();
if kind == PadKind::Unplated {
ui.label("Pin");
ui.small(link_note(PadLink::Mechanical));
ui.small("An unplated hole is drilled, not plated: it cannot carry a pin.");
} else {
let link = link_of(&pad.number, &pins, known);
ui.label("Pin");
let colour = match link {
PadLink::NoSuchPin => ui.visuals().warn_fg_color,
_ => ui.visuals().weak_text_color(),
};
let note = egui::RichText::new(link_note(link)).color(colour);
ui.label(if link == PadLink::NoSuchPin { note } else { note.small() });
ui.horizontal(|ui| {
ui.label("Number");
hits.mark("pad_number", &ui.text_edit_singleline(&mut pad.number));
});
if free.len() > PIN_BUTTONS {
ui.small("Put this pad on a pin with no pad:");
let choice = egui::ComboBox::from_id_salt("pad-pin-choice")
.selected_text("Choose a pin")
.show_ui(ui, |ui| {
for pin in &free {
if ui.selectable_label(false, pin).clicked() {
pad.number = pin.clone();
}
}
});
hits.mark("choose_pin", &choice.response);
} else if !free.is_empty() {
ui.small("Pins with no pad — click one to put this pad on it:");
ui.horizontal_wrapped(|ui| {
for pin in &free {
let button = ui.button(pin).on_hover_text(format!("Put this pad on pin {pin}"));
hits.mark(format!("put_on:{pin}"), &button);
if button.clicked() {
pad.number = pin.clone();
}
}
});
}
if !pad.number.is_empty() {
let button = ui.button("Make mechanical").on_hover_text(
"On no pin and no net, on purpose: a mounting hole, a shield tab, a castellation.",
);
hits.mark("make_mechanical", &button);
if button.clicked() {
pad.number.clear();
}
}
}
ui.separator();
let shape = egui::ComboBox::from_label("Shape")
.selected_text(shape_name(pad.shape))
.show_ui(ui, |ui| {
for shape in [PadShape::Rect, PadShape::Circle, PadShape::Oval] {
ui.selectable_value(&mut pad.shape, shape, shape_name(shape));
}
});
hits.mark("shape", &shape.response);
point_fields(ui, hits, "Position", &mut pad.at);
ui.label("Size");
mm_field(ui, hits, "Width", &mut pad.size.x, 0.01..=100.);
mm_field(ui, hits, "Height", &mut pad.size.y, 0.01..=100.);
if let Some(drill) = &mut pad.drill {
mm_field(ui, hits, "Drill", drill, 0.05..=100.);
}
let rotate = ui.button("Rotate pad 90°");
hits.mark("rotate", &rotate);
if rotate.clicked() {
pad.size = Point::new(pad.size.y, pad.size.x);
}
ui.separator();
ui.label("Repeat pad");
ui.horizontal(|ui| {
ui.label("Copies");
let copies = ui.add(egui::DragValue::new(&mut self.repeat.0).range(1..=200));
hits.mark("copies", &copies);
});
mm_field(ui, hits, "Step X", &mut self.repeat.1, -100. ..=100.);
mm_field(ui, hits, "Step Y", &mut self.repeat.2, -100. ..=100.);
let add = ui
.add_enabled(
self.repeat.1 != 0 || self.repeat.2 != 0,
egui::Button::new("Add copies"),
)
.on_hover_text("Copies continue the pad numbering, e.g. 1 -> 2, 3, 4.");
hits.mark("add_copies", &add);
if add.clicked() {
self.repeat_pad(i);
}
}
fn repeat_pad(&mut self, i: usize) {
let (count, dx, dy) = self.repeat;
let source = self.footprint.pads[i].clone();
let mut number = source.number.parse::<u32>().ok();
for k in 1..=count as i32 {
let mut pad = source.clone();
pad.at = Point::new(source.at.x + dx * k, source.at.y + dy * k);
if !source.number.is_empty() {
pad.number = match number {
Some(n) => {
let next = (n + 1..)
.find(|m| {
!self
.footprint
.pads
.iter()
.any(|p| p.number == m.to_string())
})
.unwrap_or(n + 1);
number = Some(next);
next.to_string()
}
None => self.next_number(),
};
}
self.footprint.pads.push(pad);
}
self.selected = Some(Item::Pad(self.footprint.pads.len() - 1));
}
fn remove_selected(&mut self) {
match self.selected.take() {
Some(Item::Pad(i)) if i < self.footprint.pads.len() => {
self.footprint.pads.remove(i);
}
Some(Item::Silk(i)) if i < self.footprint.silk.len() => {
self.footprint.silk.remove(i);
}
_ => {}
}
}
fn hit(&self, p: Pos2, screen: impl Fn(Point) -> Pos2, world: Point) -> Option<Item> {
let tolerance = f64::from(5. / self.zoom);
for (i, pad) in self.footprint.pads.iter().enumerate().rev() {
if Shape::pad(pad.at, pad.size, pad.shape).distance_to_point(world) <= tolerance {
return Some(Item::Pad(i));
}
}
for (i, line) in self.footprint.silk.iter().enumerate().rev() {
if line
.windows(2)
.any(|s| segment_distance(p, screen(s[0]), screen(s[1])) < 8.)
{
return Some(Item::Silk(i));
}
}
None
}
fn canvas(&mut self, ui: &mut egui::Ui, size: Vec2) {
self.canvas_pass = ui.ctx().cumulative_pass_nr();
let (response, painter) = ui.allocate_painter(size, Sense::click_and_drag());
let rect = response.rect;
self.canvas = rect;
if self.fit {
let (mut min, mut max) = self.footprint.bounds();
min = Point::new(min.x.min(-2000), min.y.min(-2000));
max = Point::new(max.x.max(2000), max.y.max(2000));
self.zoom = crate::valid_zoom(((rect.width() - 70.) / (max.x - min.x) as f32)
.min((rect.height() - 70.) / (max.y - min.y) as f32)
.min(1.), self.zoom);
self.pan =
-Vec2::new((min.x + max.x) as f32 / 2., (min.y + max.y) as f32 / 2.) * self.zoom;
self.fit = false;
}
if response.dragged_by(PointerButton::Secondary)
|| response.dragged_by(PointerButton::Middle)
{
self.pan += ui.input(|i| i.pointer.delta());
}
if response.hovered() {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
self.zoom = crate::scaled_zoom(self.zoom, (scroll * 0.002).exp());
}
let zoom = self.zoom;
let center = rect.center() + self.pan;
let screen = |p: Point| on_canvas(center, zoom, p);
let raw = |p: Pos2| {
Point::new(
((p.x - center.x) / zoom).round() as i32,
((p.y - center.y) / zoom).round() as i32,
)
};
let pointer = response.interact_pointer_pos();
if response.drag_started_by(PointerButton::Primary)
&& let Some(p) = ui.input(|i| i.pointer.press_origin())
{
if self.tool == DrawTool::Select {
self.selected = self.hit(p, screen, raw(p));
self.drag = self.selected.map(|_| (self.footprint.clone(), raw(p)));
} else {
self.start = Some(self.snap(raw(p)));
}
}
if let (Some((before, start)), Some(p)) = (&self.drag, pointer) {
let q = raw(p);
let delta = self.snap(Point::new(q.x - start.x, q.y - start.y));
self.footprint = before.clone();
match self.selected {
Some(Item::Pad(i)) => {
let pad = &mut self.footprint.pads[i];
pad.at = pad.at.offset(delta);
}
Some(Item::Silk(i)) => {
for p in &mut self.footprint.silk[i] {
*p = p.offset(delta);
}
}
None => {}
}
}
if response.drag_stopped_by(PointerButton::Primary) {
if let Some((before, _)) = self.drag.take() {
self.record(before);
}
if let Some(start) = self.start.take()
&& let Some(p) = pointer
{
let end = self.snap(raw(p));
self.add_item(start, end);
}
}
if response.clicked()
&& let Some(p) = pointer
{
match self.tool {
DrawTool::Pad | DrawTool::ThroughHole => {
let at = self.snap(raw(p));
self.add_item(at, at);
}
DrawTool::Select => self.selected = self.hit(p, screen, raw(p)),
_ => {}
}
}
if response.secondary_clicked()
&& let Some(p) = pointer
{
self.selected = self.hit(p, screen, raw(p));
}
response.context_menu(|ui| {
menu_ui(ui);
if self.selected.is_some() && ui.button("Delete item").clicked() {
let before = self.footprint.clone();
self.remove_selected();
self.record(before);
ui.close();
}
});
painter.rect_filled(rect, 0., BACKGROUND);
let painter = painter.with_clip_rect(rect);
let step = self.grid as f32 * zoom;
if step > 6. {
let mut x = rect.left() + (center.x - rect.left()).rem_euclid(step);
while x < rect.right() {
let mut y = rect.top() + (center.y - rect.top()).rem_euclid(step);
while y < rect.bottom() {
painter.circle_filled(Pos2::new(x, y), 0.8, Color32::from_gray(52));
y += step;
}
x += step;
}
}
for (a, b) in [
(Vec2::new(10., 0.), Vec2::new(-10., 0.)),
(Vec2::new(0., 10.), Vec2::new(0., -10.)),
] {
painter.line_segment([center + a, center + b], Stroke::new(1., Color32::GRAY));
}
if !self.footprint.pads.is_empty() || !self.footprint.silk.is_empty() {
let (min, max) = self.footprint.bounds();
let margin = Point::new(COURTYARD_MARGIN, COURTYARD_MARGIN);
let courtyard = Rect::from_two_pos(
screen(Point::new(min.x - margin.x, min.y - margin.y)),
screen(max.offset(margin)),
);
painter.rect_stroke(
courtyard,
0.,
Stroke::new(1., Color32::from_gray(90)),
egui::StrokeKind::Middle,
);
}
let paint_shape = |shape: Shape, fill: Option<Color32>, outline: Option<Stroke>, grow: f32| match shape
{
Shape::Rect { min, max } => {
let r = Rect::from_two_pos(screen(min), screen(max));
if let Some(fill) = fill {
painter.rect_filled(r, 0., fill);
}
if let Some(stroke) = outline {
painter.rect_stroke(r.expand(grow), 0., stroke, egui::StrokeKind::Outside);
}
}
Shape::Capsule { a, b, radius } => {
let r = (radius as f32 * zoom).max(0.5);
let (a, b) = (screen(a), screen(b));
if let Some(fill) = fill {
if a != b {
painter.line_segment([a, b], Stroke::new(2. * r, fill));
painter.circle_filled(b, r, fill);
}
painter.circle_filled(a, r, fill);
}
if let Some(stroke) = outline {
let r = r + grow + stroke.width / 2.;
if a == b {
painter.circle_stroke(a, r, stroke);
} else {
let n = (b - a).normalized().rot90() * r;
painter.line_segment([a + n, b + n], stroke);
painter.line_segment([a - n, b - n], stroke);
painter.circle_stroke(a, r, stroke);
painter.circle_stroke(b, r, stroke);
}
}
}
};
for (i, pad) in self.footprint.pads.iter().enumerate() {
let shape = Shape::pad(pad.at, pad.size, pad.shape);
let fill = match (pad.drill, pad.plated) {
(None, _) => Some(layer_color(0, 2)),
(Some(_), true) => Some(THROUGH_HOLE),
(Some(_), false) => None,
};
paint_shape(shape, fill, None, 0.);
if let Some(drill) = pad.drill {
let radius = drill as f32 / 2. * zoom;
painter.circle_filled(screen(pad.at), radius, BACKGROUND);
if !pad.plated {
painter.circle_stroke(screen(pad.at), radius, Stroke::new(1., SILK));
}
}
if let Some(colour) = link_ring(self.link(pad)) {
paint_shape(shape, None, Some(Stroke::new(RING_WIDTH, colour)), RING_GAP);
}
if self.selected == Some(Item::Pad(i)) {
paint_shape(shape, None, Some(Stroke::new(2., ACCENT)), 0.);
}
}
for (i, j, _) in self.close_pads() {
let (a, b) = (&self.footprint.pads[i], &self.footprint.pads[j]);
painter.line_segment([screen(a.at), screen(b.at)], Stroke::new(3., WARNING));
}
for pad in self.footprint.pads.iter().filter(|p| !p.number.is_empty()) {
let height = (pad.size.x.min(pad.size.y) as f32 * zoom * 0.5).clamp(8., 16.);
painter.text(
screen(pad.at),
Align2::CENTER_CENTER,
&pad.number,
FontId::monospace(height),
Color32::WHITE,
);
}
for (i, line) in self.footprint.silk.iter().enumerate() {
let color = if self.selected == Some(Item::Silk(i)) {
ACCENT
} else {
SILK
};
painter.add(egui::Shape::line(
line.iter().map(|p| screen(*p)).collect(),
Stroke::new(1.5, color),
));
}
if self.drag.is_none()
&& self.start.is_none()
&& let Some(p) = ui
.input(|i| i.pointer.hover_pos())
.filter(|p| rect.contains(*p))
&& let Some(item) = self.hit(p, screen, raw(p))
{
let note = match item {
Item::Pad(i) => match self.footprint.pads.get(i) {
Some(pad) => format!("{}\n{}", self.item_note(item), link_note(self.link(pad))),
None => self.item_note(item),
},
Item::Silk(_) => format!("{}\nNo pin and no net: it prints on the silkscreen film.", self.item_note(item)),
};
response.clone().on_hover_text_at_pointer(note);
}
if self.tool != DrawTool::Select
&& self.drag.is_none()
&& let Some(p) = ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p))
{
let at = self.snap(raw(p));
let c = screen(at);
let stroke = Stroke::new(1., ACCENT);
painter.line_segment([c - Vec2::new(6., 0.), c + Vec2::new(6., 0.)], stroke);
painter.line_segment([c - Vec2::new(0., 6.), c + Vec2::new(0., 6.)], stroke);
painter.text(
c + Vec2::new(8., -8.),
Align2::LEFT_BOTTOM,
format!("{}, {} mm", mm_text(at.x), mm_text(at.y)),
FontId::proportional(12.),
ACCENT,
);
}
if let (Some(start), Some(p)) = (self.start, pointer) {
let a = screen(start);
let b = screen(self.snap(raw(p)));
let stroke = Stroke::new(1.5, ACCENT);
match self.tool {
DrawTool::Circle => {
painter.circle_stroke(a, a.distance(b), stroke);
}
DrawTool::Line => {
painter.line_segment([a, b], stroke);
}
_ => {
painter.rect_stroke(
Rect::from_two_pos(a, b),
0.,
stroke,
egui::StrokeKind::Middle,
);
}
}
}
}
fn add_item(&mut self, a: Point, b: Point) {
let pad_tool = matches!(self.tool, DrawTool::Pad | DrawTool::ThroughHole);
if a == b && !pad_tool {
return;
}
let before = self.footprint.clone();
match self.tool {
DrawTool::Pad | DrawTool::ThroughHole => {
let through = self.tool == DrawTool::ThroughHole;
let size = if a == b {
if through { THT_SIZE } else { SMD_SIZE }
} else {
Point::new((b.x - a.x).abs().max(50), (b.y - a.y).abs().max(50))
};
let at = Point::new(
((i64::from(a.x) + i64::from(b.x)) / 2) as i32,
((i64::from(a.y) + i64::from(b.y)) / 2) as i32,
);
let number = match self.pending_number.take() {
Some(pin) if !self.footprint.pads.iter().any(|p| p.number == pin) => pin,
_ => self.next_number(),
};
self.selected = Some(Item::Pad(self.footprint.pads.len()));
self.footprint.pads.push(Pad {
number,
at,
size,
shape: match (through, size.x == size.y) {
(false, _) => PadShape::Rect,
(true, true) => PadShape::Circle,
(true, false) => PadShape::Oval,
},
drill: through.then(|| (size.x.min(size.y) * 6 / 10 / 50 * 50).max(100)),
plated: true,
});
}
DrawTool::Line | DrawTool::Rectangle | DrawTool::Circle => {
let line = match self.tool {
DrawTool::Line => vec![a, b],
DrawTool::Rectangle => {
vec![a, Point::new(b.x, a.y), b, Point::new(a.x, b.y), a]
}
_ => {
let r = f64::from(b.x - a.x).hypot(f64::from(b.y - a.y));
(0..=36)
.map(|i| {
let t = std::f64::consts::TAU * f64::from(i) / 36.;
Point::new(
a.x + (r * t.cos()).round() as i32,
a.y + (r * t.sin()).round() as i32,
)
})
.collect()
}
};
self.selected = Some(Item::Silk(self.footprint.silk.len()));
self.footprint.silk.push(line);
}
DrawTool::Select => {}
}
self.record(before);
}
}
const fn pad_action(
id: &'static str,
label: &'static str,
group: ActionGroup,
run: fn(&mut FootprintEditor),
) -> Action<FootprintEditor> {
action(id, label, group, run)
}
macro_rules! grid_action {
($id:literal, $label:literal, $grid:literal) => {
pad_action($id, $label, ActionGroup::Grid, |e| e.set_grid($grid))
.pressed_when(|e| e.grid == $grid)
};
}
const SILK_TOOLS: [&str; 3] = ["pads.tool.line", "pads.tool.rectangle", "pads.tool.circle"];
pub fn pad_actions() -> &'static [Action<FootprintEditor>] {
PAD_ACTIONS
}
static PAD_ACTIONS: &[Action<FootprintEditor>] = &[
pad_action("pads.tool.select", "Select", ActionGroup::Tool, |e| {
e.set_tool(DrawTool::Select)
})
.keys(&[key(Key::Escape)])
.pressed_when(|e| e.tool == DrawTool::Select),
pad_action("pads.tool.smd", "SMD pad", ActionGroup::Tool, |e| {
e.set_tool(DrawTool::Pad)
})
.pressed_when(|e| e.tool == DrawTool::Pad),
pad_action(
"pads.tool.through_hole",
"Through-hole pad",
ActionGroup::Tool,
|e| e.set_tool(DrawTool::ThroughHole),
)
.pressed_when(|e| e.tool == DrawTool::ThroughHole),
pad_action("pads.tool.line", "Line", ActionGroup::Tool, |e| {
e.set_tool(DrawTool::Line)
})
.pressed_when(|e| e.tool == DrawTool::Line),
pad_action("pads.tool.rectangle", "Rectangle", ActionGroup::Tool, |e| {
e.set_tool(DrawTool::Rectangle)
})
.pressed_when(|e| e.tool == DrawTool::Rectangle),
pad_action("pads.tool.circle", "Circle", ActionGroup::Tool, |e| {
e.set_tool(DrawTool::Circle)
})
.pressed_when(|e| e.tool == DrawTool::Circle),
pad_action(
"pads.undo",
"Undo",
ActionGroup::History,
FootprintEditor::undo,
)
.keys(&[command(Key::Z)])
.enabled_when(|e| e.can_step_history(HistoryKey::Undo)),
pad_action(
"pads.redo",
"Redo",
ActionGroup::History,
FootprintEditor::redo,
)
.keys(&[
egui::KeyboardShortcut::new(
egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT),
Key::Z,
),
command(Key::Y),
])
.enabled_when(|e| e.can_step_history(HistoryKey::Redo)),
pad_action("pads.fit", "Fit", ActionGroup::Zoom, |e| e.fit = true).keys(&[key(Key::F)]),
pad_action("pads.zoom_in", "Zoom +", ActionGroup::Zoom, |e| {
e.zoom = crate::scaled_zoom(e.zoom, 1.25)
}),
pad_action("pads.zoom_out", "Zoom −", ActionGroup::Zoom, |e| {
e.zoom = crate::scaled_zoom(e.zoom, 1.0 / 1.25)
}),
grid_action!("pads.grid.10", "Grid 0.01 mm", 10),
grid_action!("pads.grid.50", "Grid 0.05 mm", 50),
grid_action!("pads.grid.100", "Grid 0.1 mm", 100),
grid_action!("pads.grid.250", "Grid 0.25 mm", 250),
grid_action!("pads.grid.500", "Grid 0.5 mm", 500),
grid_action!("pads.grid.635", "Grid 0.635 mm (25 mil)", 635),
grid_action!("pads.grid.1270", "Grid 1.27 mm (50 mil)", 1270),
grid_action!("pads.grid.2540", "Grid 2.54 mm (100 mil)", 2540),
pad_action("pads.delete", "Delete item", ActionGroup::Selection, |e| {
let before = e.footprint.clone();
e.remove_selected();
e.record(before);
})
.keys(&[key(Key::Delete), key(Key::Backspace)])
.enabled_when(|e| e.selected.is_some()),
];
fn silk_as_pad(line: &[Point]) -> Option<(Point, Point, PadShape)> {
if line.len() < 4 {
return None;
}
let (min, max) = (
Point::new(
line.iter().map(|p| p.x).min()?,
line.iter().map(|p| p.y).min()?,
),
Point::new(
line.iter().map(|p| p.x).max()?,
line.iter().map(|p| p.y).max()?,
),
);
let size = Point::new(max.x - min.x, max.y - min.y);
if size.x <= 0 || size.y <= 0 {
return None;
}
let at = Point::new(
((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
((i64::from(min.y) + i64::from(max.y)) / 2) as i32,
);
let slack = f64::from(size.x.min(size.y)) / 10.;
let on_the_box = line
.iter()
.all(|p| p.x == min.x || p.x == max.x || p.y == min.y || p.y == max.y);
if on_the_box {
return Some((at, size, PadShape::Rect));
}
let radius = f64::from(size.x.max(size.y)) / 2.;
let round = line.iter().all(|p| {
(f64::from(p.x - at.x).hypot(f64::from(p.y - at.y)) - radius).abs() <= slack
});
round.then(|| (at, Point::new(size.x, size.y), PadShape::Circle))
}
fn kind_name(kind: PadKind) -> &'static str {
match kind {
PadKind::SurfaceMount => "Surface mount",
PadKind::ThroughHole => "Plated through hole",
PadKind::Unplated => "Unplated hole",
}
}
fn shape_name(shape: PadShape) -> &'static str {
match shape {
PadShape::Rect => "Rectangle",
PadShape::Circle => "Circle",
PadShape::Oval => "Oval",
}
}
pub(crate) fn min_pad_gap() -> i32 {
brep_ecad_core::board::DesignRules::default().clearance
}
fn mm_text(micrometres: i32) -> String {
let text = format!("{:.3}", f64::from(micrometres) / 1000.);
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
fn point_fields(ui: &mut egui::Ui, hits: &mut InspectorHits, name: &str, p: &mut Point) {
ui.push_id(name, |ui| {
ui.label(name);
let key = key_word(name);
mm_field(ui, hits, &format!("{key}:x"), &mut p.x, -1000. ..=1000.);
mm_field(ui, hits, &format!("{key}:y"), &mut p.y, -1000. ..=1000.);
});
}
fn mm_field(
ui: &mut egui::Ui,
hits: &mut InspectorHits,
name: &str,
value: &mut i32,
range: std::ops::RangeInclusive<f64>,
) {
let mut mm = *value as f64 / 1000.;
let (label, key) = match name.rsplit_once(':') {
Some((_, axis)) => (axis.to_uppercase(), name.to_owned()),
None => (name.to_owned(), key_word(name)),
};
ui.horizontal(|ui| {
ui.label(label);
let field = ui.add(
egui::DragValue::new(&mut mm)
.speed(0.01)
.range(range)
.max_decimals(3)
.suffix(" mm"),
);
hits.mark(key, &field);
if field.changed() {
*value = (mm * 1000.).round() as i32;
}
});
}
fn pad_key(index: usize, pad: &Pad) -> String {
if pad.number.trim().is_empty() {
format!("unnumbered-pad:{index}")
} else {
format!("pad:{}", pad.number)
}
}
fn on_canvas(center: Pos2, zoom: f32, p: Point) -> Pos2 {
center + Vec2::new(p.x as f32, p.y as f32) * zoom
}