From 348d7c2184ad5fb4833277412d7a0b781ad559c8 Mon Sep 17 00:00:00 2001 From: Nils Schlemminger Date: Wed, 21 Oct 2026 15:40:31 +0200 Subject: [PATCH] Add engineering, data exchange, forms, symbols and panel production features - Structure identifiers (=function +location) per page, relative tags - Cables with cores, wire numbering (sequential, page/column, potential) - Macros (window / page) with placeholders and value sets - Terminal strip editor (order, jumpers, spares) and PLC overview with symbol table export / import - Revisions with page snapshots, change marks and released (locked) pages - PDF export (bookmarks, links), DXF export, production wire list - Title block editor with placeholders, report forms (columns, rows) - Symbol editor for user symbols; NFPA, fluid power, single-line and black box / PLC box libraries; overview function - Panel production: busbars, cutouts, drilling pattern, NC export (DXF / CSV), wire end treatment with ferrules, clearance checks - Enclosure door with door devices and door cutouts, wiring over the hinge - Collision check with the parts' 3D models instead of their boxes - Wire harnesses per point-to-point connection: harness data report, connectors, bundle diameter, simplified KBL export Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 2 +- README.md | 110 +++- crates/openecraft-parts/src/catalog.rs | 44 +- crates/openecraft-parts/src/part.rs | 12 +- crates/openecraft-parts/src/part/tests.rs | 9 + crates/openecraft-parts/src/vec3.rs | 92 +++ crates/openecraft-parts/src/vec3/tests.rs | 26 + crates/openecraft-ui/src/io.rs | 2 + src/app.rs | 649 +++++++++++++++++++++- src/app/engineering.rs | 640 +++++++++++++++++++++ src/app/forms_ui.rs | 447 +++++++++++++++ src/app/harness_ui.rs | 155 ++++++ src/app/symbol_editor.rs | 559 +++++++++++++++++++ src/dxf.rs | 154 +++++ src/dxf/tests.rs | 41 ++ src/editor.rs | 60 +- src/editor/tests.rs | 70 +++ src/forms.rs | 366 ++++++++++++ src/forms/tests.rs | 112 ++++ src/harness.rs | 271 +++++++++ src/harness/tests.rs | 115 ++++ src/index.rs | 19 +- src/io.rs | 12 + src/macros.rs | 168 ++++++ src/macros/tests.rs | 76 +++ src/main.rs | 12 + src/model.rs | 191 ++++++- src/model/tests.rs | 21 + src/netlist.rs | 67 ++- src/ops.rs | 95 +++- src/ops/tests.rs | 109 +++- src/panel.rs | 218 +++++++- src/panel/tests.rs | 71 ++- src/panel_ui.rs | 214 +++++-- src/parts.rs | 7 + src/pdf.rs | 283 ++++++++++ src/pdf/tests.rs | 44 ++ src/plc.rs | 192 +++++++ src/plc/tests.rs | 60 ++ src/production.rs | 393 +++++++++++++ src/production/tests.rs | 178 ++++++ src/render.rs | 388 +++++++++---- src/reports.rs | 495 ++++++++++++++--- src/reports/tests.rs | 83 +++ src/revision.rs | 185 ++++++ src/revision/tests.rs | 58 ++ src/sample.rs | 50 ++ src/strips.rs | 162 ++++++ src/strips/tests.rs | 62 +++ src/structure.rs | 116 ++++ src/structure/tests.rs | 47 ++ src/symbols.rs | 275 ++++++++- src/symbols/tests.rs | 37 ++ src/symlib.rs | 329 +++++++++++ src/symlib/tests.rs | 132 +++++ src/wirenum.rs | 145 +++++ src/wirenum/tests.rs | 85 +++ 57 files changed, 8654 insertions(+), 361 deletions(-) create mode 100644 src/app/engineering.rs create mode 100644 src/app/forms_ui.rs create mode 100644 src/app/harness_ui.rs create mode 100644 src/app/symbol_editor.rs create mode 100644 src/dxf.rs create mode 100644 src/dxf/tests.rs create mode 100644 src/editor/tests.rs create mode 100644 src/forms.rs create mode 100644 src/forms/tests.rs create mode 100644 src/harness.rs create mode 100644 src/harness/tests.rs create mode 100644 src/macros.rs create mode 100644 src/macros/tests.rs create mode 100644 src/pdf.rs create mode 100644 src/pdf/tests.rs create mode 100644 src/plc.rs create mode 100644 src/plc/tests.rs create mode 100644 src/production.rs create mode 100644 src/production/tests.rs create mode 100644 src/reports/tests.rs create mode 100644 src/revision.rs create mode 100644 src/revision/tests.rs create mode 100644 src/strips.rs create mode 100644 src/strips/tests.rs create mode 100644 src/structure.rs create mode 100644 src/structure/tests.rs create mode 100644 src/symlib.rs create mode 100644 src/symlib/tests.rs create mode 100644 src/wirenum.rs create mode 100644 src/wirenum/tests.rs diff --git a/Cargo.toml b/Cargo.toml index 9b282830..33ab7880 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ eframe = { version = "0.37", default-features = false, features = [ # Bundle the symbol / emoji fonts: native builds have no browser font fallback, # so icons used in the UI must be in the bundled fonts (see src/glyphs.rs). egui = { version = "0.37", features = ["monochrome_emoji_fonts"] } -serde = { version = "1", features = ["derive"] } +serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" log = "0.4" openecraft-parts = { path = "crates/openecraft-parts" } diff --git a/README.md b/README.md index 7a725254..66218f94 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,50 @@ built with [egui / eframe](https://github.com/emilk/egui). - **Device-oriented engineering**: device tags (`-K1`, `-S3`, …) are assigned automatically. Main function (coil) + auxiliary functions (contacts) form one device. Select a coil and place contacts: they are assigned to it and numbered (13/14, 21/22, …). +- **Structure identifiers (IEC 81346)**: pages carry a function (`=A1`) and a location + (`+CAB1`). Devices placed on a page get its structure (`=A1+CAB1-K1`); on the page, tags + and cross references show only what differs from the page structure (EPLAN style), + tags are numbered per structure, copy / paste moves devices into the target structure, + changing a page structure can move its devices along. The device navigator groups by + structure; the title block shows the full page name (`=A1+CAB1/3`). +- **Cables**: cable definitions (tag, type, cores, cross-section, length, part from the + product group *Cables*). Wires are assigned to cores (several wires at once get the free + cores in order); cores and the cable tag are shown on the schematic. Cable overview and + cable diagram reports, cables in the BOM by length, checks for unknown cables, cores + used twice or not in the cable. +- **Wire numbers**: one number per connection (all its wire segments; the two sides of a + terminal are separate connections). Automatic numbering: sequential, page/column + (`3.4.1`) or by potential name (`L1`, `+24V`), with prefix and start value; manually + set numbers are kept. Shown on the schematic, in the connection list and the panel + wire list; checks for conflicting and duplicate numbers. +- **Macros**: save a selection (window macro) or a whole page (page macro) into a macro + library (stored with the application, JSON import / export). Window macros are placed + with the mouse (ghost preview, devices get new tags), page macros insert a page. + Placeholders such as `{MOTOR}` in tags, texts, function texts and designations are + filled from **value sets** when inserting. +- **Terminal strip editor**: terminal order (move up / down, sort), renumbering 1 … n, + **jumpers** (bridged terminals share their potential), spare terminals (in the terminal + diagram and the BOM). +- **PLC overview**: all inputs / outputs per card with connected devices, editable + addresses and function texts, card start byte / rack / slot, readdressing, **symbol + table export / import** (CSV: name, data type, address, comment) for PLC programming + tools; addresses used on several cards are reported. +- **Revisions**: a revision stores a snapshot of all pages and can release (lock) them; + locked pages are read only. Changes since the last revision (added / changed / removed + symbols, wires, texts, pages) are listed, marked on the pages with a revision triangle + and reported in the *revision overview*. +- **Symbol editor and libraries**: besides the IEC symbols there are NFPA / JIC + symbols, fluid power symbols (ISO 1219: pump, cylinder, 4/2 valve, filter, gauge, + tank), single-line / overview symbols (cross references to the device, not part of + the netlist) and black boxes / PLC boxes. Own symbols are drawn in the symbol editor + (lines, rectangles, circles, texts, tag / label fields, connection points on the 4 mm + grid, function such as main function, contact, terminal, PLC point), or copied from a + built-in symbol; they are stored in the project and exchanged as library files. +- **Forms**: title blocks are lists of lines, rectangles and texts with placeholders + (`{project}`, `{page}`, `{sheet}`, `{rev.date}`, user properties `{prop:Name}` …), + edited in the title block editor and shared as files; one per project with an + override per page (built-in: Standard, Compact, None). Report forms choose the + columns, their order, the heading and the rows per report page. - **Live cross references**: contacts show where their coil is (`/3.4`), coils show a contact image with all contacts and their locations, interruption points reference their counterparts on other pages. @@ -22,7 +66,8 @@ built with [egui / eframe](https://github.com/emilk/egui). potential connection points (L1, N, PE, +24V, …) and interruption points are evaluated into nets across pages. Selecting a wire highlights its whole potential. - **Reports**: table of contents, device list, bill of materials (with parts and prices), - terminal diagram, connection list, PLC assignment list, potential overview — in a window, + terminal diagram, connection list, PLC assignment list, potential overview, cable + overview, cable diagram — in a window, as CSV export, or inserted as live report pages. - **Project check**: aux functions without main function, duplicate main functions, open connection points, unpaired interruption points, short circuits between @@ -48,7 +93,21 @@ built with [egui / eframe](https://github.com/emilk/egui). block add up in depth, terminal strips are as wide as their terminals) and snapped onto rails; move (devices travel with their rail), rotate, delete; - 2D front view and a 3D view (orbit, pan, zoom, click to select); - - collision and boundary checks (overlaps, outside the plate, too deep for the enclosure); + - collision and boundary checks (overlaps, outside the plate, too deep for the enclosure + including a door clearance, mounted over a cutout, inside the clearance a device + needs above and below from its part data `Clearance: 25 mm`); where a device has a + 3D model, the **models** are checked for penetration, not just their boxes; + - **enclosure door**: command and signal devices (pushbuttons, lamps …) are placed on + the door (front view *Door*); each gets its **door cutout** (Ø22.5 by default or from + the part data `Door cutout: Ø30.5` / `92 x 68`), checked against the door frame and + in 3D against the equipment of the mounting plate; their wires are routed over the + hinge; the mounting layout page shows plate and door side by side; + - copper **busbar systems** (bars drawn, metres and holders in the BOM) and rectangular + or round **cutouts** in the mounting plate; + - **drilling pattern**: rails, ducts and busbar holders get tapped holes along their + length, devices screwed onto the plate get holes from their part data + (`Mounting holes: M5: 9,12; 69,72`) or two default holes; **NC export** per + enclosure and face as DXF (outline, one layer per hole diameter, cutouts) or CSV; - virtual wiring: every schematic connection between placed devices is routed through the cable duct network (shortest path) → wire list with lengths, wires shown in 2D/3D; - mounting layout pages (scaled 2D model view with dimensions) for printing / SVG; @@ -57,7 +116,22 @@ built with [egui / eframe](https://github.com/emilk/egui). - **Editing**: select / window select / move with rubber-band wires, rotate, mirror, copy / cut / paste (via clipboard, devices get new tags), undo / redo, texts, graphic lines and rectangles, grid snapping, pan and zoom. -- **Output**: SVG per page, printable HTML of all pages (print to PDF from the browser). +- **Output / data exchange**: **PDF** of all pages (bookmarks per page, clickable cross + references and report rows), **DXF** (R12, layers by kind) per page or all pages side + by side, SVG per page, printable HTML, production wire list (CSV with wire numbers, + ends, colour, cross-section, routed length, stripping length and ferrule per + DIN 46228-4, cable cores; panel wires sorted by cross-section, colour and length for + wire processing machines; ferrules also in the BOM), report CSVs, PLC symbol tables, + NC data of mounting plates. + DWG and EPLAN's EDZ format are proprietary and not supported. +- **Wire harnesses**: single point-to-point connections (`-S1:13 – -K1:A1`) are + assigned to harnesses (`-WH1`), independent of the other connections of the same + potential section; assignments follow renamed devices, missing connections are + reported by the check; the *harness data* + report lists their wires with length (routed in the panel layout or the harness's + field length) and end treatment, the harness window shows the connectors with their + pin assignment and the bundle diameter; export as simplified **KBL** (VDA 4964, XML) + for harness manufacturing. - **Storage**: JSON project files (`.oec`); the current project is also auto-saved (app storage on desktop, local storage in the browser). @@ -141,6 +215,18 @@ cargo test --workspace | Draw wires | `W`, click start and corner points, ends automatically on a connection point; `Space` flips the corner | | Select / move | click, `Shift`+click, drag on empty space for window selection, drag items to move | | Edit properties | right panel: tag, function text, connection point designations, part, cross references | +| Page structure | *Page › Page properties…*: function (`=`) and location (`+`) | +| Cables | *Project › Cables…*; select wires › *Assign to cable*; single wire: cable and core | +| Wire numbers | *Project › Wire numbering…*; single wire: type a number (kept by automatic numbering) | +| Macros | select items › *Edit › Save selection as macro…*; *Insert › Macro…* to place one | +| Terminal strips / PLC | *Project › Terminal strips…* / *Project › PLC overview…* | +| Revisions | *Project › Revisions…*: create (and release) revisions, lock / unlock pages, see changes | +| Export | *File*: PDF, DXF (page / all), SVG, HTML, production wire list | +| Own symbols | *Project › Symbol editor…*; they appear under *User symbols* in the symbol list | +| Title blocks / report forms | *Project › Title blocks and report forms…*; per page in the page properties | +| Panel production | panel layout: *Busbar* / *Cutout* tools; enclosure properties: NC data (DXF / CSV) | +| Door devices | panel layout: front view *Door*, place devices there or move them in their properties | +| Harnesses | *Project › Harnesses…*; select the wires between two devices › *Assign to harness*, or per connection in the wire properties; KBL export in the window | | Pan / zoom | right or middle mouse drag / mouse wheel, `F` fits the page | | Pages | `Page Up` / `Page Down`, navigator on the left | | Undo / redo | `Ctrl+Z` / `Ctrl+Y` | @@ -155,13 +241,27 @@ cargo test --workspace | `server/` | `openecraft-server`: parts database server (REST API, JSON storage) | | `parts-manager/` | `openecraft-parts-manager`: standalone parts server maintenance (desktop + web) | | `src/model.rs` | Project data model (pages, symbols, wires, parts) and page layout constants | -| `src/symbols.rs` | Built-in IEC symbol library | +| `src/symbols.rs` | Built-in symbol libraries (IEC, NFPA, fluid power, single-line, black boxes) | +| `src/symlib.rs` | User symbols: registry, editing helpers, library files | +| `src/forms.rs` | Title blocks (placeholders) and report forms | +| `src/production.rs` | Panel production: drilling pattern, door cutouts, NC export, wire end treatment, clearances | +| `src/harness.rs` | Wire harnesses: wires, connectors, bundle diameter, KBL export | | `src/netlist.rs` | Connectivity analysis (nets / potentials, junctions) | | `src/index.rs` | Device and cross-reference index | | `src/reports.rs` | Reports and project check | | `src/render.rs` | Backend independent page renderer (used by canvas and SVG) | | `src/editor.rs` | Interactive canvas (tools, hit testing, pan/zoom) | -| `src/ops.rs` | Editing operations (placement defaults, move, rotate, paste, …) | +| `src/ops.rs` | Editing operations (placement defaults, move, rotate, paste, cable cores, page structure, …) | +| `src/structure.rs` | Structure identifiers: parse / complete / shorten tags (`=A1+CAB1-K1`) | +| `src/wirenum.rs` | Wire numbers per connection and automatic numbering | +| `src/macros.rs` | Window / page macros, placeholders and value sets | +| `src/strips.rs` | Terminal strips: order, renumbering, jumpers, spare terminals | +| `src/plc.rs` | PLC points, addressing, symbol table export / import | +| `src/revision.rs` | Revisions: page snapshots, change detection, revision names | +| `src/pdf.rs` / `src/dxf.rs` | PDF and DXF export (through the `render::Draw` trait) | +| `src/app/engineering.rs` | Windows for macros, terminal strips, PLC overview and revisions | +| `src/app/symbol_editor.rs` / `src/app/forms_ui.rs` | Symbol editor and forms (title block / report form) windows | +| `src/app/harness_ui.rs` | Harness window | | `src/panel.rs` | Panel layout model, device sizes, rail snapping, collisions, duct routing | | `src/panel_ui.rs` | Panel layout workspace: navigator, 2D editor, 3D view, properties | | `src/parts.rs` | Parts database, function templates, project parts, CSV import/export | diff --git a/crates/openecraft-parts/src/catalog.rs b/crates/openecraft-parts/src/catalog.rs index 46e67ab2..c6b223e0 100644 --- a/crates/openecraft-parts/src/catalog.rs +++ b/crates/openecraft-parts/src/catalog.rs @@ -116,7 +116,10 @@ pub fn default_catalog() -> Vec { let p = c.add("GEN.PS-24DC-5A", "Power supply 230 V AC / 24 V DC 5 A", "Power supplies, transformers", "Power supply", "T", 89.0, (40.0, 125.0, 115.0, 0.6), &[(PowerSupply, "L N PE L+ M")]); p.voltage = "230 V AC / 24 V DC".into(); p.current = "5 A".into(); - c.add("GEN.TR-230-24-100VA", "Control transformer 230 V / 24 V 100 VA", "Power supplies, transformers", "Control transformer", "T", 46.0, (78.0, 84.0, 70.0, 1.6), &[(Transformer, "1.1 1.2 2.1 2.2")]); + p.tech_data = "Clearance: 25 mm (convection cooling, above and below)".into(); + let p = c.add("GEN.TR-230-24-100VA", "Control transformer 230 V / 24 V 100 VA", "Power supplies, transformers", "Control transformer", "T", 46.0, (78.0, 84.0, 70.0, 1.6), &[(Transformer, "1.1 1.2 2.1 2.2")]); + p.mounting = "Screw mounting".into(); + p.tech_data = "Mounting holes: M5: 9,12; 69,12; 9,72; 69,72".into(); let p = c.add("GEN.TB-2.5", "Feed-through terminal 2.5 mm², grey", "Terminals", "Feed-through terminal", "X", 0.95, (5.2, 48.0, 36.0, 0.006), &[(Terminal, "")]); p.accessories = vec!["GEN.TB-END".into()]; @@ -146,6 +149,45 @@ pub fn default_catalog() -> Vec { p.mounting.clear(); let p = c.add("GEN.ENC-600X800", "Steel enclosure 600 x 800 x 250 mm, IP66", "Mounting", "Enclosure", "", 320.0, (600.0, 800.0, 250.0, 28.0), &[]); p.mounting.clear(); + // Busbar system: width = length of 1 m, height = width of the system, depth = height above the plate. + let p = c.add("GEN.BB-3X12X5", "Busbar system 3-pole, Cu 12 x 5 mm, 60 mm centre distance", "Mounting", "Busbar system", "", 38.0, (1000.0, 75.0, 40.0, 1.6), &[]); + p.quantity_unit = "m".into(); + p.mounting.clear(); + p.tech_data = "Bars: 3\nBar: Cu 12 x 5 mm\nRated current: 200 A".into(); + let p = c.add("GEN.BB-HOLDER-3P", "Busbar holder 3-pole for 12 x 5 mm, 60 mm", "Mounting", "Busbar holder", "", 6.4, (75.0, 25.0, 40.0, 0.08), &[]); + p.mounting.clear(); + + // Ferrules (DIN 46228-4 colour code), sold per piece. + for (cs, color, len) in [ + ("0.34", "turquoise", 8), + ("0.5", "white", 8), + ("0.75", "grey", 8), + ("1.0", "red", 8), + ("1.5", "black", 8), + ("2.5", "blue", 8), + ("4", "grey", 10), + ("6", "yellow", 12), + ("10", "red", 12), + ("16", "blue", 12), + ] { + let number = format!("GEN.FER-{cs}"); + let desc = format!("Ferrule {cs} mm², insulated, {color}, {len} mm"); + let p = c.add(&number, &desc, "Wiring material", "Ferrule", "", 0.03, (0.0, 0.0, 0.0, 0.0), &[]); + p.mounting.clear(); + p.tech_data = format!("Cross-section: {cs} mm²\nColour: {color}\nLength: {len} mm"); + } + + // Cables: sold by the metre; the cores are listed in the technical data. + for (number, desc, subgroup, price, kg, cores, cs) in [ + ("GEN.CBL-4G1.5", "Power cable 4G1.5, rubber sheathed", "Power cable", 2.4, 0.12, "BN BK GY GNYE", "1.5 mm²"), + ("GEN.CBL-5G2.5", "Power cable 5G2.5, rubber sheathed", "Power cable", 4.1, 0.2, "BN BK GY BU GNYE", "2.5 mm²"), + ("GEN.CBL-7G1.0", "Control cable 7G1.0, numbered cores", "Control cable", 2.9, 0.11, "1 2 3 4 5 6 GNYE", "1 mm²"), + ("GEN.CBL-SENS-3X0.34", "Sensor cable M12 3 x 0.34, PUR", "Control cable", 1.6, 0.04, "BN BU BK", "0.34 mm²"), + ] { + let p = c.add(number, desc, "Cables", subgroup, "W", price, (0.0, 0.0, 0.0, kg), &[]); + p.quantity_unit = "m".into(); + p.tech_data = format!("Cores: {cores}\nCross-section: {cs}"); + } let mut parts = c.parts; for p in &mut parts { diff --git a/crates/openecraft-parts/src/part.rs b/crates/openecraft-parts/src/part.rs index c33c6337..c7819dac 100644 --- a/crates/openecraft-parts/src/part.rs +++ b/crates/openecraft-parts/src/part.rs @@ -37,7 +37,9 @@ pub const PRODUCT_GROUPS: &[(&str, &[&str])] = &[ ("PLC", &["Digital input module", "Digital output module", "CPU"]), ("Valves", &["Solenoid valve"]), ("Passive components", &["Resistor", "Capacitor", "Diode"]), - ("Mounting", &["Mounting rail", "Cable duct", "Enclosure"]), + ("Mounting", &["Mounting rail", "Cable duct", "Enclosure", "Busbar system", "Busbar holder"]), + ("Cables", &["Power cable", "Control cable"]), + ("Wiring material", &["Ferrule"]), ]; /// Kinds of functions in a function template. Placed symbols map onto these kinds. @@ -291,6 +293,14 @@ impl Part { } /// Short summary of the function template, e.g. "Coil, Main3, NO". + /// Value of a `Name: value` line of the technical data (e.g. the cores of a cable). + pub fn tech_value(&self, name: &str) -> Option<&str> { + self.tech_data.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + k.trim().eq_ignore_ascii_case(name).then_some(v.trim()) + }) + } + pub fn template_summary(&self) -> String { let mut counts: BTreeMap = BTreeMap::new(); for f in &self.functions { diff --git a/crates/openecraft-parts/src/part/tests.rs b/crates/openecraft-parts/src/part/tests.rs index 23e8ffb3..b3dfcf5f 100644 --- a/crates/openecraft-parts/src/part/tests.rs +++ b/crates/openecraft-parts/src/part/tests.rs @@ -19,3 +19,12 @@ fn unique_numbers() { assert_eq!(unique_number(&list, "Y"), "Y"); assert_eq!(unique_number(&list, "X"), "X_2"); } + +#[test] +fn technical_data_values() { + let p = crate::default_catalog().into_iter().find(|p| p.number == "GEN.CBL-4G1.5").unwrap(); + assert_eq!(p.tech_value("cores"), Some("BN BK GY GNYE")); + assert_eq!(p.tech_value("Cross-section"), Some("1.5 mm²")); + assert_eq!(p.tech_value("Voltage"), None); + assert_eq!(p.quantity_unit, "m"); +} diff --git a/crates/openecraft-parts/src/vec3.rs b/crates/openecraft-parts/src/vec3.rs index 07a17079..1c728e1f 100644 --- a/crates/openecraft-parts/src/vec3.rs +++ b/crates/openecraft-parts/src/vec3.rs @@ -19,6 +19,98 @@ pub fn norm(a: V3) -> V3 { [a[0] / l, a[1] / l, a[2] / l] } +pub type Tri = [V3; 3]; + +/// Bounding box (min, max) of triangles. +pub fn tri_bounds(tris: &[Tri]) -> (V3, V3) { + let mut min = [f32::INFINITY; 3]; + let mut max = [f32::NEG_INFINITY; 3]; + for v in tris.iter().flatten() { + for k in 0..3 { + min[k] = min[k].min(v[k]); + max[k] = max[k].max(v[k]); + } + } + (min, max) +} + +fn boxes_overlap(a: (V3, V3), b: (V3, V3), eps: f32) -> bool { + (0..3).all(|k| a.0[k] < b.1[k] - eps && b.0[k] < a.1[k] - eps) +} + +/// True if the segment p0–p1 passes through the inside of the triangle (touching +/// edges, end points and segments lying in the triangle's plane do not count). +pub fn segment_crosses_triangle(p0: V3, p1: V3, t: &Tri) -> bool { + const EPS: f32 = 1e-4; + let dir = sub(p1, p0); + let e1 = sub(t[1], t[0]); + let e2 = sub(t[2], t[0]); + let h = cross(dir, e2); + let a = dot(e1, h); + if a.abs() < 1e-9 { + return false; + } + let f = 1.0 / a; + let s = sub(p0, t[0]); + let u = f * dot(s, h); + let q = cross(s, e1); + let v = f * dot(dir, q); + let along = f * dot(e2, q); + u > EPS && v > EPS && u + v < 1.0 - EPS && along > 1e-6 && along < 1.0 - 1e-6 +} + +/// Ray parity test: is `q` inside the closed surface(s) made of `tris`? +pub fn point_inside(q: V3, tris: &[Tri]) -> bool { + // A slightly skewed ray avoids hitting edges of axis aligned models exactly. + let far = [q[0] + 1.0e4, q[1] + 170.0, q[2] + 230.0]; + tris.iter().filter(|t| segment_crosses_triangle(q, far, t)).count() % 2 == 1 +} + +/// True if two triangle surfaces penetrate each other or one lies inside the +/// other. Surfaces that only touch do not count. +pub fn surfaces_intersect(a: &[Tri], b: &[Tri]) -> bool { + let (ba, bb) = (tri_bounds(a), tri_bounds(b)); + if a.is_empty() || b.is_empty() || !boxes_overlap(ba, bb, 1e-4) { + return false; + } + let edges_cross = |x: &[Tri], y: &[Tri], by: (V3, V3)| { + x.iter().any(|t| { + (0..3).any(|i| { + let (p0, p1) = (t[i], t[(i + 1) % 3]); + let eb = ( + [p0[0].min(p1[0]), p0[1].min(p1[1]), p0[2].min(p1[2])], + [p0[0].max(p1[0]), p0[1].max(p1[1]), p0[2].max(p1[2])], + ); + // Quick reject of edges outside the other surface. + if (0..3).any(|k| eb.1[k] < by.0[k] || eb.0[k] > by.1[k]) { + return false; + } + y.iter().any(|u| segment_crosses_triangle(p0, p1, u)) + }) + }) + }; + if edges_cross(a, b, bb) || edges_cross(b, a, ba) { + return true; + } + // No crossing edges: one surface may lie completely inside the other. + let centroid = |t: &Tri| [(t[0][0] + t[1][0] + t[2][0]) / 3.0, (t[0][1] + t[1][1] + t[2][1]) / 3.0, (t[0][2] + t[1][2] + t[2][2]) / 3.0]; + point_inside(centroid(&a[0]), b) || point_inside(centroid(&b[0]), a) +} + +/// The 12 triangles of a box (outward winding). +pub fn box_triangles(min: V3, max: V3) -> Vec { + let c = |x: usize, y: usize, z: usize| [if x == 0 { min[0] } else { max[0] }, if y == 0 { min[1] } else { max[1] }, if z == 0 { min[2] } else { max[2] }]; + let quads = [ + [c(0, 0, 0), c(0, 0, 1), c(0, 1, 1), c(0, 1, 0)], + [c(1, 0, 0), c(1, 1, 0), c(1, 1, 1), c(1, 0, 1)], + [c(0, 0, 0), c(1, 0, 0), c(1, 0, 1), c(0, 0, 1)], + [c(0, 1, 0), c(0, 1, 1), c(1, 1, 1), c(1, 1, 0)], + [c(0, 0, 0), c(0, 1, 0), c(1, 1, 0), c(1, 0, 0)], + [c(0, 0, 1), c(1, 0, 1), c(1, 1, 1), c(0, 1, 1)], + ]; + quads.iter().flat_map(|q| [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]).collect() +} + /// Camera orbiting around `target` (y up). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Orbit { diff --git a/crates/openecraft-parts/src/vec3/tests.rs b/crates/openecraft-parts/src/vec3/tests.rs index 602cc402..2c14d1ee 100644 --- a/crates/openecraft-parts/src/vec3/tests.rs +++ b/crates/openecraft-parts/src/vec3/tests.rs @@ -20,3 +20,29 @@ fn orbit_from_the_front_looks_down_minus_z() { assert!(close(right, [1.0, 0.0, 0.0])); assert!(close(up, [0.0, 1.0, 0.0])); } + +#[test] +fn segments_and_triangles() { + let t = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [0.0, 10.0, 0.0]]; + assert!(segment_crosses_triangle([2.0, 2.0, -1.0], [2.0, 2.0, 1.0], &t)); + // Ending on the plane, outside, or lying in the plane does not count. + assert!(!segment_crosses_triangle([2.0, 2.0, 0.0], [2.0, 2.0, 1.0], &t)); + assert!(!segment_crosses_triangle([8.0, 8.0, -1.0], [8.0, 8.0, 1.0], &t)); + assert!(!segment_crosses_triangle([1.0, 1.0, 0.0], [3.0, 1.0, 0.0], &t)); +} + +#[test] +fn box_surfaces() { + let a = box_triangles([0.0; 3], [10.0; 3]); + assert!(point_inside([5.0, 5.0, 5.0], &a)); + assert!(!point_inside([15.0, 5.0, 5.0], &a)); + // Overlapping, touching, apart, contained. + assert!(surfaces_intersect(&a, &box_triangles([8.0, 2.0, 2.0], [20.0, 8.0, 8.0]))); + assert!(!surfaces_intersect(&a, &box_triangles([10.0, 0.0, 0.0], [20.0, 10.0, 10.0]))); + assert!(!surfaces_intersect(&a, &box_triangles([12.0, 0.0, 0.0], [20.0, 10.0, 10.0]))); + assert!(surfaces_intersect(&a, &box_triangles([2.0; 3], [4.0; 3]))); + assert!(surfaces_intersect(&box_triangles([2.0; 3], [4.0; 3]), &a)); + // Crossing bars (no corner inside the other box). + let x = box_triangles([-5.0, 4.0, 4.0], [15.0, 6.0, 6.0]); + assert!(surfaces_intersect(&a, &x)); +} diff --git a/crates/openecraft-ui/src/io.rs b/crates/openecraft-ui/src/io.rs index f02271ae..a9da6129 100644 --- a/crates/openecraft-ui/src/io.rs +++ b/crates/openecraft-ui/src/io.rs @@ -128,6 +128,8 @@ pub fn mime_type(ext: &str) -> &'static str { "svg" => "image/svg+xml", "html" => "text/html", "csv" => "text/csv", + "pdf" => "application/pdf", + "dxf" => "application/dxf", _ => "application/json", } } diff --git a/src/app.rs b/src/app.rs index 2746ffdb..f9afb344 100644 --- a/src/app.rs +++ b/src/app.rs @@ -11,10 +11,16 @@ use crate::model::*; use crate::netlist::{pin_designation, PinRef}; use crate::ops; use crate::reports::{Analysis, Severity}; +use crate::structure::{self, Dt}; use crate::symbols::{self, Category, Func}; -use crate::{history::History, sample, svg}; +use crate::{history::History, sample, svg, wirenum}; use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText}; +mod engineering; +mod forms_ui; +mod harness_ui; +mod symbol_editor; + #[derive(Clone, Copy, PartialEq, Eq)] enum Workspace { Schematic, @@ -49,6 +55,16 @@ pub struct App { workspace: Workspace, panel_ui: PanelUi, show_help: bool, + show_cables: bool, + show_numbering: bool, + /// Macros, terminal strips, PLC overview, revisions. + eng: engineering::EngineeringUi, + macro_lib: crate::macros::MacroLibrary, + symed: symbol_editor::SymbolEditor, + forms_ui: forms_ui::FormsUi, + harness_ui: harness_ui::HarnessUi, + /// Wire numbering: also renumber / remove manually set numbers. + numbering_overwrite: bool, page_props: Option, message: Option<(String, f64)>, title: String, @@ -60,11 +76,13 @@ impl App { let mut file_name = None; let mut parts_db: Option = None; let mut server_url: Option = None; + let mut macro_lib = None; if let Some(storage) = cc.storage { prj = eframe::get_value(storage, "project"); file_name = eframe::get_value(storage, "file_name").flatten(); parts_db = eframe::get_value(storage, "parts_db"); server_url = eframe::get_value(storage, "parts_server_url"); + macro_lib = eframe::get_value(storage, "macros"); } let parts_db = parts_db.unwrap_or_default(); let mut parts_ui = PartsUi::default(); @@ -96,6 +114,14 @@ impl App { workspace: Workspace::Schematic, panel_ui: PanelUi::default(), show_help: false, + show_cables: false, + show_numbering: false, + eng: Default::default(), + macro_lib: macro_lib.unwrap_or_default(), + symed: Default::default(), + forms_ui: Default::default(), + harness_ui: Default::default(), + numbering_overwrite: false, page_props: None, message: None, title: String::new(), @@ -203,6 +229,56 @@ impl App { self.notify(ctx, msg); return; } + if loaded.purpose == Purpose::Macros { + let text = loaded.text(); + let lib = serde_json::from_str::(&text) + .or_else(|_| serde_json::from_str::(&text).map(|m| crate::macros::MacroLibrary { macros: vec![m] })); + match lib { + Ok(lib) => { + let n = self.macro_lib.merge(lib); + self.notify(ctx, format!("Imported {n} macros")); + } + Err(e) => self.notify(ctx, format!("Not a macro file: {e}")), + } + return; + } + if loaded.purpose == Purpose::Symbols { + let text = loaded.text(); + let lib = serde_json::from_str::(&text) + .or_else(|_| serde_json::from_str::(&text).map(|u| crate::symlib::SymbolLibrary { symbols: vec![u] })); + match lib { + Ok(lib) => { + let (added, replaced) = crate::symlib::merge(&mut self.prj.symbols, lib); + self.symed.open = true; + self.notify(ctx, format!("{added} symbols added, {replaced} replaced")); + } + Err(e) => self.notify(ctx, format!("Not a symbol library: {e}")), + } + return; + } + if loaded.purpose == Purpose::Forms { + match serde_json::from_str::(&loaded.text()) { + Ok(lib) => { + let n = lib.title_blocks.len(); + for f in lib.title_blocks { + match self.prj.forms.title_blocks.iter_mut().find(|x| x.name == f.name) { + Some(x) => *x = f, + None => self.prj.forms.title_blocks.push(f), + } + } + self.notify(ctx, format!("Imported {n} title blocks")); + } + Err(e) => self.notify(ctx, format!("Not a title block file: {e}")), + } + return; + } + if loaded.purpose == Purpose::PlcTable { + match crate::plc::import_symbol_table(&mut self.prj, &loaded.text()) { + Ok(n) => self.notify(ctx, format!("{n} PLC function texts updated")), + Err(e) => self.notify(ctx, format!("Symbol table import failed: {e}")), + } + return; + } if loaded.purpose == Purpose::Parts { match parts::import(&loaded.text()) { Ok(list) => { @@ -285,6 +361,24 @@ impl App { let html = svg::print_document(&self.prj); self.export(&ctx, self.suggested_name("html"), ("HTML document", "html"), html); } + if ui.button("Export as PDF (bookmarks, linked cross references)…").clicked() { + let pdf = crate::pdf::document(&self.prj); + self.export(&ctx, self.suggested_name("pdf"), ("PDF document", "pdf"), pdf); + } + if ui.button("Export page as DXF…").clicked() { + let dxf = crate::dxf::pages_dxf(&self.prj, &[self.page]); + let name = format!("{}_page_{}.dxf", self.suggested_name("x").trim_end_matches(".x"), self.prj.pages[self.page].name); + self.export(&ctx, name, ("DXF drawing", "dxf"), dxf); + } + if ui.button("Export all pages as DXF…").clicked() { + let all: Vec = (0..self.prj.pages.len()).collect(); + let dxf = crate::dxf::pages_dxf(&self.prj, &all); + self.export(&ctx, self.suggested_name("dxf"), ("DXF drawing", "dxf"), dxf); + } + if ui.button("Export production wire list (CSV)…").on_hover_text("Wire numbers, ends, colour, cross-section, routed length, cable cores").clicked() { + let csv = crate::reports::production_wire_list(&self.prj, &self.analysis).to_csv(); + self.export(&ctx, "wire_list.csv".into(), ("CSV", "csv"), csv); + } #[cfg(not(target_arch = "wasm32"))] { ui.separator(); @@ -316,8 +410,16 @@ impl App { self.editor.selection = ops::all_ids(&self.prj.pages[self.page]).into_iter().collect(); } ui.label(RichText::new("Copy / paste: Ctrl+C, Ctrl+X, Ctrl+V").weak()); + ui.separator(); + if ui.add_enabled(has_sel, egui::Button::new("Save selection as macro…")).clicked() { + self.save_as_macro(false); + } }); ui.menu_button("Insert", |ui| { + if ui.button("Macro…").clicked() { + self.eng.show_macros = true; + } + ui.separator(); if ui.button("Wire W").clicked() { self.editor.set_tool(Tool::Wire); } @@ -340,6 +442,16 @@ impl App { } }); } + let user = self.user_symbols(); + if !user.is_empty() { + ui.menu_button(Category::User.title(), |ui| { + for def in user { + if ui.button(format!("{} ({})", def.name, def.library)).clicked() { + self.editor.set_tool(Tool::Place(def.key)); + } + } + }); + } }); ui.menu_button("Page", |ui| { if ui.button("New schematic page").clicked() { @@ -370,6 +482,9 @@ impl App { if ui.button("Page properties…").clicked() { self.page_props = Some(self.page); } + if ui.button("Save page as macro…").clicked() { + self.save_as_macro(true); + } if ui.add_enabled(self.page > 0, egui::Button::new("Move page up")).clicked() { self.prj.pages.swap(self.page, self.page - 1); self.page -= 1; @@ -391,6 +506,34 @@ impl App { if ui.button("Parts management…").clicked() { self.parts_ui.open = true; } + if ui.button("Cables…").clicked() { + self.show_cables = true; + } + if ui.button("Wire numbering…").clicked() { + self.show_numbering = true; + } + if ui.button("Harnesses…").clicked() { + self.harness_ui.open = true; + } + if ui.button("Terminal strips…").clicked() { + self.eng.show_strips = true; + } + if ui.button("PLC overview…").clicked() { + self.eng.show_plc = true; + } + if ui.button("Revisions…").clicked() { + self.eng.show_revisions = true; + } + if ui.button("Macros…").clicked() { + self.eng.show_macros = true; + } + ui.separator(); + if ui.button("Symbol editor…").clicked() { + self.symed.open = true; + } + if ui.button("Title blocks and report forms…").clicked() { + self.forms_ui.open = true; + } if ui.button("Check project").clicked() { self.left_tab = LeftTab::Check; } @@ -409,6 +552,7 @@ impl App { } ui.checkbox(&mut self.editor.show_grid, "Grid"); ui.checkbox(&mut self.editor.show_pins, "Connection points"); + ui.checkbox(&mut self.editor.show_revision_marks, "Revision marks"); ui.separator(); let mut pref = ui.ctx().options(|o| o.theme_preference); ui.horizontal(|ui| { @@ -488,7 +632,7 @@ impl App { self.goto(self.page - 1, 0); } let pg = &self.prj.pages[self.page]; - ui.label(RichText::new(format!("Page {} {}", pg.name, pg.description)).strong()); + ui.label(RichText::new(format!("Page {} {}", structure::page_full_name(pg), pg.description)).strong()); if ui.add_enabled(self.page + 1 < self.prj.pages.len(), egui::Button::new("▶")).on_hover_text("Next page (Page Down)").clicked() { self.goto(self.page + 1, 0); } @@ -535,7 +679,7 @@ impl App { PageKind::Report(_) => "📊", PageKind::Mounting(_) => "🗄", }; - let r = ui.selectable_label(i == self.page, format!("{icon} {} {}", pg.name, pg.description)); + let r = ui.selectable_label(i == self.page, format!("{icon} {} {}", structure::page_full_name(pg), pg.description)); if r.clicked() { goto = Some(i); } @@ -553,25 +697,49 @@ impl App { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let mut jump = None; let f = self.device_filter.to_lowercase(); - for tag in idx.sorted_tags() { - if !f.is_empty() && !tag.to_lowercase().contains(&f) { - continue; + // Devices grouped by structure (=function+location). + let mut groups: Vec<(String, Vec<&String>)> = Vec::new(); + for tag in idx.sorted_tags().into_iter().filter(|t| f.is_empty() || t.to_lowercase().contains(&f)) { + let st = Dt::parse(tag).structure(); + match groups.iter_mut().find(|g| g.0 == st) { + Some(g) => g.1.push(tag), + None => groups.push((st, vec![tag])), } + } + groups.sort_by(|a, b| natural_cmp(&a.0, &b.0)); + let structured = groups.iter().any(|g| !g.0.is_empty()); + let prj = &self.prj; + let mut device = |ui: &mut egui::Ui, tag: &String| { let dev = &idx.devices[tag]; - egui::CollapsingHeader::new(RichText::new(tag).monospace().strong()).id_salt(tag).show(ui, |ui| { + let title = if structured { Dt::parse(tag).name } else { tag.clone() }; + egui::CollapsingHeader::new(RichText::new(title).monospace().strong()).id_salt(tag).show(ui, |ui| { for (kind, locs) in [("Main", &dev.mains), ("Aux", &dev.auxs), ("", &dev.others)] { for loc in locs { - let inst = self.prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id); + let inst = prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id); let Some(inst) = inst else { continue }; let name = symbols::get(&inst.sym).map(|d| d.name).unwrap_or("?"); let extra = if inst.label.is_empty() { inst.pins.join("-") } else { inst.label.clone() }; - let text = format!("{} {kind} {name} {extra}", loc.reference(&self.prj)); + let text = format!("{} {kind} {name} {extra}", loc.reference(prj)); if ui.link(text.trim()).clicked() { jump = Some((loc.page, loc.sym_id)); } } } }); + }; + for (st, tags) in &groups { + if structured { + let title = if st.is_empty() { "(no structure)" } else { st.as_str() }; + egui::CollapsingHeader::new(RichText::new(title).strong()).id_salt(("structure", st)).default_open(true).show(ui, |ui| { + for tag in tags { + device(ui, tag); + } + }); + } else { + for tag in tags { + device(ui, tag); + } + } } if idx.devices.is_empty() { ui.weak("No devices yet. Pick a symbol from the library on the right and click into the page."); @@ -623,16 +791,22 @@ impl App { ui.add(egui::TextEdit::singleline(&mut self.lib_filter).hint_text("Search…").desired_width(f32::INFINITY)); }); let f = self.lib_filter.to_lowercase(); + let user = self.user_symbols(); + let mut libs: Vec<&str> = user.iter().map(|d| d.library).collect(); + libs.dedup(); egui::ScrollArea::vertical().id_salt("lib").max_height(ui.available_height() * 0.45).auto_shrink([false, true]).show(ui, |ui| { - for cat in Category::ALL { - let defs: Vec<_> = symbols::library() - .iter() - .filter(|d| d.category == cat && (f.is_empty() || d.name.to_lowercase().contains(&f))) - .collect(); + let groups = libs + .iter() + .map(|lib| (format!("{}: {lib}", Category::User.title()), user.iter().copied().filter(|d| d.library == *lib).collect::>())) + .chain(Category::ALL.into_iter().map(|cat| (cat.title().to_string(), symbols::library().iter().filter(|d| d.category == cat).collect()))); + for (title, defs) in groups { + let defs: Vec<&symbols::SymbolDef> = defs.into_iter().filter(|d| f.is_empty() || d.name.to_lowercase().contains(&f)).collect(); if defs.is_empty() { continue; } - egui::CollapsingHeader::new(cat.title()).default_open(f.is_empty() || !defs.is_empty()).show(ui, |ui| { + // The extra libraries start collapsed. + let main = !matches!(defs[0].category, Category::Nfpa | Category::Fluid | Category::SingleLine | Category::BlackBox); + egui::CollapsingHeader::new(title).default_open(!f.is_empty() || main).show(ui, |ui| { for def in defs { let active = self.editor.tool == Tool::Place(def.key); ui.horizontal(|ui| { @@ -650,15 +824,29 @@ impl App { }); } + /// Registered symbols of the project symbol library, sorted by library and name. + fn user_symbols(&self) -> Vec<&'static symbols::SymbolDef> { + let mut v: Vec<&'static symbols::SymbolDef> = self.prj.symbols.iter().filter_map(|u| symbols::get(&u.key)).collect(); + v.sort_by(|a, b| a.library.cmp(b.library).then(natural_cmp(a.name, b.name))); + v + } + fn properties(&mut self, ui: &mut egui::Ui, idx: &Index) { ui.heading("Properties"); let sel: Vec = self.editor.selection.iter().copied().collect(); let pi = self.page; + if self.prj.pages[pi].locked { + ui.label(RichText::new("🔒 Released page – read only").color(Color32::from_rgb(220, 140, 0))); + ui.disable(); + } if sel.is_empty() { let pg = &mut self.prj.pages[pi]; - ui.label(RichText::new(format!("Page {} – {}", pg.name, pg.kind.label())).strong()); + ui.label(RichText::new(format!("Page {} – {}", structure::page_full_name(pg), pg.kind.label())).strong()); ui.label("Description"); ui.text_edit_singleline(&mut pg.description); + if ui.link("Structure (function / location)…").on_hover_text("Page properties").clicked() { + self.page_props = Some(pi); + } ui.add_space(6.0); ui.weak(self.editor.tool.hint()); return; @@ -694,6 +882,70 @@ impl App { w.cross_section = cs.clone(); } } + let cables: Vec = self.prj.cables.iter().map(|c| c.tag.clone()).collect(); + let mut assign = None; + ui.horizontal(|ui| { + ui.menu_button("Assign to cable", |ui| { + for c in &cables { + if ui.button(c).clicked() { + assign = Some(c.clone()); + } + } + if cables.is_empty() { + ui.weak("No cables yet – Project › Cables…"); + } + }) + .response + .on_hover_text("The wires get the free cores of the cable in order (left to right)"); + if ui.button("Remove from cable").clicked() { + for w in self.prj.pages[pi].wires.iter_mut().filter(|w| wires.contains(&w.id)) { + w.cable.clear(); + w.core.clear(); + } + } + }); + let harnesses: Vec = self.prj.harnesses.iter().map(|h| h.tag.clone()).collect(); + let mut to_harness = None; + ui.horizontal(|ui| { + ui.menu_button("Assign to harness", |ui| { + for h in &harnesses { + if ui.button(h).clicked() { + to_harness = Some(h.clone()); + } + } + if harnesses.is_empty() { + ui.weak("No harnesses yet – Project › Harnesses…"); + } + }) + .response + .on_hover_text("Connections whose two ends are both on selected wires"); + if ui.button("Remove from harness").clicked() { + to_harness = Some(String::new()); + } + }); + if let Some(tag) = to_harness { + let sel: std::collections::BTreeSet = wires.iter().copied().collect(); + let conns = crate::harness::connections_at(&self.prj, &self.analysis, pi, &sel); + let ends: Vec<(String, String)> = conns + .iter() + .map(|&i| { + let c = &self.analysis.connections[i]; + (pin_designation(&self.prj, c.a), pin_designation(&self.prj, c.b)) + }) + .collect(); + for (a, b) in &ends { + crate::harness::assign(&mut self.prj, a, b, &tag); + } + let ctx = ui.ctx().clone(); + let what = if tag.is_empty() { "removed from their harness".to_string() } else { format!("assigned to {tag}") }; + self.notify(&ctx, format!("{} connections {what}", ends.len())); + } + if let Some(c) = assign { + let sel: std::collections::BTreeSet = wires.iter().copied().collect(); + let n = ops::assign_cores(&mut self.prj, pi, &sel, &c); + let ctx = ui.ctx().clone(); + self.notify(&ctx, format!("{n} of {} wires assigned to cores of {c}", wires.len())); + } } return; } @@ -713,8 +965,68 @@ impl App { ui.weak("All wires of this potential are highlighted."); } ui.separator(); + let open_net = self.analysis.open.wire_net.get(&id).map(|&n| self.analysis.open.nets[n].clone()); + let number_now = open_net.as_ref().map(|n| wirenum::number_of(&self.prj, n)).unwrap_or_default(); + let mut number = number_now.clone(); + let here = Page { function: self.prj.pages[pi].function.clone(), location: self.prj.pages[pi].location.clone(), ..Default::default() }; + let cables: Vec<(String, Vec)> = self.prj.cables.iter().map(|c| (c.tag.clone(), c.core_list())).collect(); + // Cores of the wire's cable already used by other connections + let own: Vec = open_net.as_ref().map(|n| n.wires.iter().map(|w| w.1).collect()).unwrap_or_default(); + let cable_now = self.prj.pages[pi].wires[wi].cable.clone(); + let used: Vec = self + .prj + .pages + .iter() + .flat_map(|pg| pg.wires.iter()) + .filter(|x| x.cable == cable_now && !cable_now.is_empty() && !own.contains(&x.id)) + .map(|x| x.core.clone()) + .collect(); + let harnesses: Vec = self.prj.harnesses.iter().map(|h| h.tag.clone()).collect(); + // Connections of this wire's potential section, each with its own harness. + let conns: Vec<(String, String, String)> = crate::harness::connections_of_wire(&self.analysis, id) + .into_iter() + .map(|i| { + let c = &self.analysis.connections[i]; + (pin_designation(&self.prj, c.a), pin_designation(&self.prj, c.b), c.harness.clone()) + }) + .collect(); + let mut harness_change = None; let w = &mut self.prj.pages[pi].wires[wi]; egui::Grid::new("wprops1").num_columns(2).show(ui, |ui| { + ui.label("Wire number"); + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut number).hint_text("not numbered").desired_width(90.0)) + .on_hover_text("Applies to all wires of this connection; automatic numbering keeps manual numbers"); + if w.number_fixed { + ui.weak("manual"); + } + }); + ui.end_row(); + ui.label("Cable"); + let shown = if w.cable.is_empty() { "(none)".to_string() } else { structure::relative(&here, &w.cable) }; + egui::ComboBox::from_id_salt("wcable").selected_text(shown).show_ui(ui, |ui| { + if ui.selectable_label(w.cable.is_empty(), "(none)").clicked() { + w.cable.clear(); + w.core.clear(); + } + for (tag, _) in &cables { + if ui.selectable_label(w.cable == *tag, tag).clicked() && w.cable != *tag { + w.cable = tag.clone(); + w.core.clear(); + } + } + }); + ui.end_row(); + if let Some((_, cores)) = cables.iter().find(|(t, _)| *t == w.cable) { + ui.label("Core"); + egui::ComboBox::from_id_salt("wcore").selected_text(w.core.clone()).show_ui(ui, |ui| { + for c in cores { + let text = if used.contains(c) { format!("{c} (used)") } else { c.clone() }; + ui.selectable_value(&mut w.core, c.clone(), text); + } + }); + ui.end_row(); + } ui.label("Colour"); ui.add(egui::TextEdit::singleline(&mut w.color).hint_text("e.g. BU, BK, GNYE")); ui.end_row(); @@ -728,6 +1040,35 @@ impl App { ui.label(format!("{:.0} / {:.0}", w.b.x, w.b.y)); ui.end_row(); }); + if number != number_now { + if let Some(net) = &open_net { + wirenum::set(&mut self.prj, net, number.trim(), true); + } + } + if !conns.is_empty() { + ui.separator(); + ui.label(RichText::new("Connections / harness").strong()).on_hover_text("Each point-to-point connection can belong to a harness"); + egui::Grid::new("wharness").num_columns(2).show(ui, |ui| { + for (i, (a, b, h)) in conns.iter().enumerate() { + ui.label(RichText::new(format!("{a} – {b}")).monospace()); + let shown = if h.is_empty() { "(none)".to_string() } else { structure::relative(&here, h) }; + egui::ComboBox::from_id_salt(("wharness", i)).selected_text(shown).show_ui(ui, |ui| { + if ui.selectable_label(h.is_empty(), "(none)").clicked() { + harness_change = Some((a.clone(), b.clone(), String::new())); + } + for t in &harnesses { + if ui.selectable_label(t == h, t).clicked() { + harness_change = Some((a.clone(), b.clone(), t.clone())); + } + } + }); + ui.end_row(); + } + }); + } + if let Some((a, b, tag)) = harness_change { + crate::harness::assign(&mut self.prj, &a, &b, &tag); + } } else if let Some(t) = self.prj.pages[pi].texts.iter_mut().find(|t| t.id == id) { ui.label("Text"); ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(3)); @@ -749,11 +1090,19 @@ impl App { }; ui.label(RichText::new(def.name).strong()); let mut edited = s.clone(); + let here = Page { function: self.prj.pages[pi].function.clone(), location: self.prj.pages[pi].location.clone(), ..Default::default() }; egui::Grid::new("sprops").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { if def.func.has_tag() { ui.label(if def.func == Func::Terminal { "Terminal strip" } else if def.func == Func::Plc { "PLC card" } else { "Device tag" }); ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut edited.tag).desired_width(90.0).font(egui::TextStyle::Monospace)); + // Shown relative to the page structure, stored complete. + let mut shown = structure::relative(&here, &edited.tag); + let before = shown.clone(); + ui.add(egui::TextEdit::singleline(&mut shown).desired_width(90.0).font(egui::TextStyle::Monospace)) + .on_hover_text(format!("Complete tag: {}\nAspects missing here are taken from the page (=function +location).", edited.tag)); + if shown != before { + edited.tag = if shown.trim().is_empty() { String::new() } else { structure::complete(&here, &shown) }; + } // Assign to an existing device (e.g. contact → coil) egui::ComboBox::from_id_salt("assign").selected_text("…").width(30.0).show_ui(ui, |ui| { for tag in idx.sorted_tags() { @@ -981,6 +1330,9 @@ impl App { if ui.button("➕ Insert as report page").clicked() { add_page = Some(kind); } + if ui.button("Form…").on_hover_text("Columns, order and rows of the report pages").clicked() { + self.forms_ui.open_report(kind); + } }); let Some(table) = self.analysis.reports.get(&kind) else { return }; egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { @@ -1026,6 +1378,7 @@ impl App { // Project properties if self.show_project { let mut open = true; + let prj_tb_names = crate::forms::names(&self.prj); egui::Window::new("Project properties").open(&mut open).resizable(false).show(ctx, |ui| { let info = &mut self.prj.info; egui::Grid::new("prj").num_columns(2).show(ui, |ui| { @@ -1047,7 +1400,53 @@ impl App { ui.label("Revision"); ui.text_edit_singleline(&mut info.revision); ui.end_row(); + ui.label("Title block"); + let forms = &mut self.prj.forms; + let current = if forms.default_title_block.is_empty() { crate::forms::STANDARD.to_string() } else { forms.default_title_block.clone() }; + egui::ComboBox::from_id_salt("prjtb").selected_text(¤t).show_ui(ui, |ui| { + for n in prj_tb_names.iter().cloned() { + if ui.selectable_label(n == current, &n).clicked() { + forms.default_title_block = if n == crate::forms::STANDARD { String::new() } else { n }; + } + } + }); + ui.end_row(); }); + ui.separator(); + ui.label(RichText::new("Project properties").strong()).on_hover_text("Shown in title blocks with {prop:Name}"); + let props = &mut self.prj.info.properties; + let mut remove = None; + let mut rename = None; + egui::Grid::new("prjprops").num_columns(3).show(ui, |ui| { + for (k, v) in props.iter_mut() { + let mut key = k.clone(); + if ui.add(egui::TextEdit::singleline(&mut key).desired_width(120.0)).changed() { + rename = Some((k.clone(), key)); + } + ui.add(egui::TextEdit::singleline(v).desired_width(200.0)); + if ui.small_button("🗑").clicked() { + remove = Some(k.clone()); + } + ui.end_row(); + } + }); + if let Some((old, new)) = rename { + if !new.is_empty() && !props.contains_key(&new) { + if let Some(v) = props.remove(&old) { + props.insert(new, v); + } + } + } + if let Some(k) = remove { + props.remove(&k); + } + if ui.button("➕ Property").clicked() { + let mut n = props.len() + 1; + while props.contains_key(&format!("Property{n}")) { + n += 1; + } + props.insert(format!("Property{n}"), String::new()); + } }); self.show_project = open; } @@ -1063,10 +1462,19 @@ impl App { } self.parts_ui.selector(ctx, &self.parts_db, &mut self.prj); + self.cables_window(ctx); + self.numbering_window(ctx); + self.engineering_windows(ctx); + self.symbol_editor_window(ctx); + self.forms_window(ctx); + self.harness_window(ctx); + // Page properties if let Some(pi) = self.page_props { let mut open = true; + let mut apply_structure = None; if pi < self.prj.pages.len() { + let tb_names = crate::forms::names(&self.prj); egui::Window::new("Page properties").open(&mut open).resizable(false).show(ctx, |ui| { let pg = &mut self.prj.pages[pi]; egui::Grid::new("pgprops").num_columns(2).show(ui, |ui| { @@ -1089,13 +1497,47 @@ impl App { }); ui.end_row(); }); + ui.horizontal(|ui| { + ui.label("Title block"); + let shown = if pg.title_block.is_empty() { "(project default)".to_string() } else { pg.title_block.clone() }; + egui::ComboBox::from_id_salt("pgtb").selected_text(shown).show_ui(ui, |ui| { + ui.selectable_value(&mut pg.title_block, String::new(), "(project default)"); + for n in &tb_names { + ui.selectable_value(&mut pg.title_block, n.clone(), n); + } + }); + }); if pg.kind != PageKind::Schematic && !pg.is_empty() { ui.colored_label(Color32::from_rgb(220, 140, 0), "This page contains schematic content which is not evaluated on non-schematic pages."); } + ui.separator(); + ui.label(RichText::new("Structure (IEC 81346)").strong()); + let key = ui.scope_id().with(("page_structure", pi)); + let (mut function, mut location, mut move_devices): (String, String, bool) = + ui.data_mut(|d| d.get_temp(key)).unwrap_or_else(|| (pg.function.clone(), pg.location.clone(), true)); + egui::Grid::new("pgstruct").num_columns(2).show(ui, |ui| { + ui.label("Function ="); + ui.add(egui::TextEdit::singleline(&mut function).hint_text("e.g. A1, PUMP.2")); + ui.end_row(); + ui.label("Location +"); + ui.add(egui::TextEdit::singleline(&mut location).hint_text("e.g. CAB1, FIELD")); + ui.end_row(); + }); + ui.checkbox(&mut move_devices, "Move the devices of this page into the new structure") + .on_hover_text("Renames the devices (all their functions, also on other pages)"); + let changed = structure::clean_aspect(&function) != pg.function || structure::clean_aspect(&location) != pg.location; + if ui.add_enabled(changed, egui::Button::new("Apply structure")).clicked() { + apply_structure = Some((function.clone(), location.clone(), move_devices)); + } + ui.weak("Devices placed on the page get its structure; their tags are shown without it."); + ui.data_mut(|d| d.insert_temp(key, (function, location, move_devices))); }); } else { open = false; } + if let Some((function, location, move_devices)) = apply_structure { + ops::set_page_structure(&mut self.prj, pi, &function, &location, move_devices); + } if !open { self.page_props = None; } @@ -1110,6 +1552,15 @@ impl App { ui.label("3. Draw wires with the wire tool (W). Wires end automatically on connection points. T-junctions get a connection dot."); ui.label("4. Potentials (L1, +24V …) and interruption points name the nets across pages. Select a wire to highlight its potential."); ui.label("5. Assign parts in the property panel; generate reports (device list, BOM, terminal diagram, connection list, PLC list) and insert them as report pages."); + ui.label("6. Structure: give pages a function (=A1) and location (+CAB1) in the page properties. Devices placed there get it (=A1+CAB1-K1); on the page only the differing part is shown."); + ui.label("7. Cables: define them in Project › Cables…, select wires and use Assign to cable. Wire numbers: Project › Wire numbering…, or type a number in the wire properties."); + ui.label("8. Macros: select items › Edit › Save selection as macro; insert them from Insert › Macro…. Placeholders {NAME} are filled from value sets."); + ui.label("9. Project › Terminal strips / PLC overview / Revisions: strip order, jumpers and spares; PLC addresses and symbol tables; revisions with change marks and released (locked) pages."); + ui.label("10. Project › Symbol editor: draw your own symbols (or copy built-in ones) with connection points and function; they are saved in the project and can be exchanged as library files."); + ui.label("11. Project › Title blocks and report forms: own title blocks with placeholders ({project}, {page}, {prop:Name} …) and the columns of report pages."); + ui.label("12. Panel layout: busbars and cutouts; the enclosure properties export the drilling pattern (NC data as DXF / CSV). The production wire list contains stripping lengths and ferrules."); + ui.label("13. Harnesses: Project › Harnesses…; select the wires between two devices › Assign to harness, or per connection in the wire properties. Harness data report with lengths, connectors and bundle diameter, KBL export."); + ui.label("14. Door: switch the panel front view to Door and place command / signal devices there; their door cutouts are generated. Collisions are checked with the parts' 3D models."); ui.separator(); ui.label(RichText::new("Shortcuts").strong()); egui::Grid::new("keys").striped(true).show(ui, |ui| { @@ -1139,6 +1590,149 @@ impl App { } } + fn cables_window(&mut self, ctx: &egui::Context) { + if !self.show_cables { + return; + } + let mut open = true; + let mut renamed: Vec<(String, String)> = Vec::new(); + let mut remove = None; + let mut picked: Vec = Vec::new(); + let mut overview = false; + let mut used: std::collections::HashMap> = Default::default(); + for w in self.prj.pages.iter().flat_map(|pg| pg.wires.iter()).filter(|w| !w.cable.is_empty()) { + used.entry(w.cable.clone()).or_default().insert(w.core.clone()); + } + let structure = structure::page_structure(&self.prj.pages[self.page]); + egui::Window::new("Cables").open(&mut open).default_size([1000.0, 360.0]).show(ctx, |ui| { + ui.horizontal_wrapped(|ui| { + if ui.button("➕ New cable").on_hover_text("In the structure of the current page").clicked() { + let tag = self.prj.next_tag(&structure, "W"); + let id = self.prj.new_id(); + self.prj.cables.push(Cable { id, tag, cores: "BN BK GY GNYE".into(), cross_section: "1.5 mm²".into(), ..Default::default() }); + } + if ui.button("📊 Cable overview").clicked() { + overview = true; + } + ui.weak("Assign wires: select them in the schematic › Assign to cable."); + }); + ui.separator(); + let cable_parts: Vec<&parts::Part> = self.parts_db.parts.iter().filter(|p| p.group == "Cables").collect(); + egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { + egui::Grid::new("cables").striped(true).num_columns(9).spacing([8.0, 4.0]).show(ui, |ui| { + for h in ["Cable", "Type", "Cores", "Cross-section", "Length", "Part", "Description", "Used", ""] { + ui.label(RichText::new(h).strong()); + } + ui.end_row(); + for (i, c) in self.prj.cables.iter_mut().enumerate() { + let old = c.tag.clone(); + ui.add_sized([100.0, 20.0], egui::TextEdit::singleline(&mut c.tag).font(egui::TextStyle::Monospace)); + if c.tag != old { + renamed.push((old.clone(), c.tag.clone())); + } + ui.add_sized([120.0, 20.0], egui::TextEdit::singleline(&mut c.cable_type)); + ui.add_sized([140.0, 20.0], egui::TextEdit::singleline(&mut c.cores)).on_hover_text("Core designations separated by blanks"); + ui.add_sized([70.0, 20.0], egui::TextEdit::singleline(&mut c.cross_section)); + ui.add(egui::DragValue::new(&mut c.length).speed(0.5).range(0.0..=100000.0).suffix(" m")); + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut c.part).desired_width(120.0)); + ui.menu_button("…", |ui| { + for p in &cable_parts { + if ui.button(format!("{} {}", p.number, p.description)).clicked() { + c.part = p.number.clone(); + c.cable_type = p.type_number.clone(); + if let Some(cores) = p.tech_value("Cores") { + c.cores = cores.to_string(); + } + if let Some(cs) = p.tech_value("Cross-section") { + c.cross_section = cs.to_string(); + } + picked.push(p.number.clone()); + } + } + if cable_parts.is_empty() { + ui.weak("No parts of the product group Cables in the parts database."); + } + }); + }); + ui.add_sized([160.0, 20.0], egui::TextEdit::singleline(&mut c.description)); + let n = used.get(&old).map(|s| s.len()).unwrap_or(0); + ui.label(format!("{n}/{}", c.core_list().len())); + if ui.small_button("🗑").on_hover_text("Delete cable (its wires are removed from it)").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + if self.prj.cables.is_empty() { + ui.weak("No cables defined."); + } + }); + }); + for (old, new) in renamed { + for w in self.prj.pages.iter_mut().flat_map(|pg| pg.wires.iter_mut()).filter(|w| w.cable == old) { + w.cable = new.clone(); + } + } + if let Some(i) = remove { + let tag = self.prj.cables.remove(i).tag; + for w in self.prj.pages.iter_mut().flat_map(|pg| pg.wires.iter_mut()).filter(|w| w.cable == tag) { + w.cable.clear(); + w.core.clear(); + } + } + for n in picked { + parts::ensure_in_project(&mut self.prj, &self.parts_db, &n); + } + if overview { + self.report_kind = ReportKind::CableOverview; + self.show_reports = true; + } + self.show_cables = open; + } + + fn numbering_window(&mut self, ctx: &egui::Context) { + if !self.show_numbering { + return; + } + let mut open = true; + let (mut number, mut remove) = (false, false); + let nets: Vec<&crate::netlist::Net> = self.analysis.open.nets.iter().filter(|n| !n.wires.is_empty() && !n.pins.is_empty()).collect(); + let numbered = nets.iter().filter(|n| !wirenum::number_of(&self.prj, n).is_empty()).count(); + let total = nets.len(); + egui::Window::new("Wire numbering").open(&mut open).resizable(false).show(ctx, |ui| { + let s = &mut self.prj.wire_numbering; + ui.label("Every connection gets one number for all its wires; the two sides of a terminal are separate connections."); + ui.add_space(4.0); + for scheme in NumberScheme::ALL { + ui.radio_value(&mut s.scheme, scheme, scheme.title()); + } + egui::Grid::new("numbering").num_columns(2).show(ui, |ui| { + ui.label("Prefix"); + ui.add(egui::TextEdit::singleline(&mut s.prefix).desired_width(60.0).hint_text("e.g. W")); + ui.end_row(); + ui.label("Start at"); + ui.add(egui::DragValue::new(&mut s.start).range(0..=1_000_000)); + ui.end_row(); + }); + ui.checkbox(&mut self.numbering_overwrite, "Include manually set numbers"); + ui.label(format!("{numbered} of {total} connections numbered")); + ui.horizontal(|ui| { + number = ui.button("Number wires").clicked(); + remove = ui.button("Remove numbers").clicked(); + }); + }); + if number { + let n = wirenum::renumber(&mut self.prj, &self.analysis.open, &self.analysis.netlist, self.numbering_overwrite); + self.notify(ctx, format!("{n} connections numbered")); + } + if remove { + let n = wirenum::clear(&mut self.prj, self.numbering_overwrite); + self.notify(ctx, format!("Numbers removed from {n} wires")); + } + self.show_numbering = open; + } + fn shortcuts(&mut self, ctx: &egui::Context) { if ctx.egui_wants_keyboard_input() { return; @@ -1199,6 +1793,11 @@ impl eframe::App for App { self.shortcuts(&ctx); self.page = self.page.min(self.prj.pages.len().saturating_sub(1)); + // User symbols are rebuilt when they change (not while one is dragged in the + // symbol editor). + if !self.symed.busy() { + crate::symlib::register(&self.prj.symbols); + } if self.analysis_rev != self.history.rev { self.analysis = Analysis::build(&self.prj); self.analysis_rev = self.history.rev; @@ -1256,6 +1855,19 @@ impl eframe::App for App { self.goto(loc.page, loc.sym_id); } } + if let Some((ei, face, dxf)) = self.panel_ui.export.take() { + if let Some(e) = self.prj.layout.enclosures.get(ei) { + let base: String = e.name.chars().map(|c| if c.is_alphanumeric() { c } else { '_' }).collect(); + let what = if face == crate::panel::Face::Door { "door" } else { "plate" }; + if dxf { + let content = crate::production::nc_dxf(&self.prj, ei, face); + self.export(&ctx, format!("{what}{base}.dxf"), ("DXF drawing", "dxf"), content); + } else { + let content = crate::production::nc_csv(&self.prj, ei, face); + self.export(&ctx, format!("{what}{base}_drilling.csv"), ("CSV", "csv"), content); + } + } + } if let Some(id) = self.panel_ui.add_page.take() { self.add_page(PageKind::Mounting(id)); self.workspace = Workspace::Schematic; @@ -1265,7 +1877,7 @@ impl eframe::App for App { self.windows(&ctx); // Commit finished edits as one undo step. - let can_commit = !ctx.input(|i| i.pointer.any_down()) && ctx.memory(|m| m.focused().is_none()) && !self.editor.busy() && !self.panel_ui.busy(); + let can_commit = !ctx.input(|i| i.pointer.any_down()) && ctx.memory(|m| m.focused().is_none()) && !self.editor.busy() && !self.panel_ui.busy() && !self.symed.busy() && !self.forms_ui.busy(); self.history.track(&self.prj, can_commit); let title = format!( @@ -1284,5 +1896,6 @@ impl eframe::App for App { eframe::set_value(storage, "file_name", &self.file_name); eframe::set_value(storage, "parts_db", &self.parts_db); eframe::set_value(storage, "parts_server_url", &self.parts_ui.server.url); + eframe::set_value(storage, "macros", &self.macro_lib); } } diff --git a/src/app/engineering.rs b/src/app/engineering.rs new file mode 100644 index 00000000..a42d72da --- /dev/null +++ b/src/app/engineering.rs @@ -0,0 +1,640 @@ +//! Engineering windows: macros, terminal strips, PLC overview and revisions. + +use super::App; +use crate::editor::{EguiDraw, Palette, Tool}; +use crate::io::Purpose; +use crate::macros::{self, Macro, MacroKind}; +use crate::model::*; +use crate::ops::Clip; +use crate::render::{self, Draw, Ink}; +use crate::{plc, revision, strips, symbols}; +use egui::{vec2, Color32, RichText}; +use std::collections::BTreeMap; + +#[derive(Default)] +pub struct EngineeringUi { + pub show_macros: bool, + macro_filter: String, + /// Name of the selected macro. + macro_sel: Option, + /// Placeholder values for the next insertion. + macro_values: BTreeMap, + /// Macro waiting for its name (save dialog). + saving: Option, + pub show_strips: bool, + strip: String, + pub show_plc: bool, + card: String, + pub show_revisions: bool, + rev_name: String, + rev_date: String, + rev_author: String, + rev_description: String, + rev_release: bool, +} + +enum MacroAction { + Insert(usize), + Delete(usize), + Export, + Import, +} + +/// Scaled drawing of a macro's items. +fn clip_preview(ui: &mut egui::Ui, clip: &Clip, size: egui::Vec2) { + let (resp, painter) = ui.allocate_painter(size, egui::Sense::hover()); + let pal = Palette::new(ui.visuals().dark_mode); + painter.rect_filled(resp.rect, 4.0, pal.paper); + let b = clip.bounds().expand(4.0); + if !b.is_valid() { + return; + } + let zoom = ((size.x - 8.0) / b.width()).min((size.y - 8.0) / b.height()).min(4.0); + let origin = resp.rect.center() - vec2(b.center().x, b.center().y) * zoom; + let mut d = EguiDraw { painter: &painter, origin, zoom, pal: &pal, force: None }; + for w in &clip.wires { + d.line(w.a, w.b, render::WIRE_W, Ink::Wire, false); + } + for s in &clip.shapes { + render::draw_shape(&mut d, s, Ink::Line); + } + for s in &clip.symbols { + if let Some(def) = symbols::get(&s.sym) { + render::draw_symbol(&mut d, def, s, Ink::Line); + } + } + for t in &clip.texts { + d.text(t.pos, t.text.lines().next().unwrap_or(""), t.size, symbols::Anchor::Left, render::VAnchor::Middle, Ink::Text); + } +} + +impl App { + pub(super) fn engineering_windows(&mut self, ctx: &egui::Context) { + self.save_macro_dialog(ctx); + self.macros_window(ctx); + self.strips_window(ctx); + self.plc_window(ctx); + self.revisions_window(ctx); + } + + /// Opens the save dialog for the selection (window macro) or the page (page macro). + pub(super) fn save_as_macro(&mut self, whole_page: bool) { + let page = &self.prj.pages[self.page]; + let m = if whole_page { + macros::from_page(page, &page.description) + } else { + macros::from_selection(page, &self.editor.selection, "") + }; + self.eng.saving = Some(m); + } + + fn save_macro_dialog(&mut self, ctx: &egui::Context) { + let Some(m) = &mut self.eng.saving else { return }; + let (mut save, mut cancel) = (false, false); + egui::Window::new("Save as macro").collapsible(false).resizable(false).show(ctx, |ui| { + ui.label(format!("{} macro: {}", if m.kind == MacroKind::Page { "Page" } else { "Window" }, m.summary())); + egui::Grid::new("savemacro").num_columns(2).show(ui, |ui| { + ui.label("Name"); + ui.text_edit_singleline(&mut m.name); + ui.end_row(); + ui.label("Category"); + ui.add(egui::TextEdit::singleline(&mut m.category).hint_text("e.g. Motors")); + ui.end_row(); + ui.label("Description"); + ui.text_edit_multiline(&mut m.description); + ui.end_row(); + }); + ui.weak("Placeholders like {MOTOR} in tags, texts and function texts are filled in when inserting."); + ui.horizontal(|ui| { + save = ui.add_enabled(!m.name.trim().is_empty(), egui::Button::new("💾 Save")).clicked(); + cancel = ui.button("Cancel").clicked(); + }); + }); + if save { + let m = self.eng.saving.take().unwrap(); + let replaced = self.macro_lib.macros.iter().any(|x| x.name == m.name); + self.eng.macro_sel = Some(m.name.clone()); + self.notify(ctx, format!("Macro {} {}", m.name, if replaced { "replaced" } else { "saved" })); + self.macro_lib.upsert(m); + self.eng.show_macros = true; + } + if cancel { + self.eng.saving = None; + } + } + + fn macros_window(&mut self, ctx: &egui::Context) { + if !self.eng.show_macros { + return; + } + let mut open = true; + let mut action = None; + let can_save_selection = !self.editor.selection.is_empty() && self.prj.pages[self.page].kind == PageKind::Schematic; + let mut save = None; + egui::Window::new("Macros").open(&mut open).default_size([820.0, 480.0]).show(ctx, |ui| { + ui.horizontal_wrapped(|ui| { + ui.add(egui::TextEdit::singleline(&mut self.eng.macro_filter).hint_text("Filter…").desired_width(160.0)); + if ui.add_enabled(can_save_selection, egui::Button::new("💾 Save selection as macro…")).clicked() { + save = Some(false); + } + if ui.button("Save page as macro…").clicked() { + save = Some(true); + } + ui.menu_button("Library", |ui| { + if ui.button("Export macros (JSON)…").clicked() { + action = Some(MacroAction::Export); + } + if ui.button("Import macros…").clicked() { + action = Some(MacroAction::Import); + } + }); + }); + ui.separator(); + let h = ui.available_height(); + ui.horizontal_top(|ui| { + ui.allocate_ui_with_layout(vec2(240.0, h), egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().id_salt("macrolist").auto_shrink([false, false]).show(ui, |ui| { + let f = self.eng.macro_filter.to_lowercase(); + let mut categories: Vec<&str> = self.macro_lib.macros.iter().map(|m| m.category.as_str()).collect(); + categories.dedup(); + for cat in categories { + let title = if cat.is_empty() { "(no category)" } else { cat }; + egui::CollapsingHeader::new(RichText::new(title).strong()).id_salt(("mcat", cat)).default_open(true).show(ui, |ui| { + for m in self.macro_lib.macros.iter().filter(|m| m.category == cat) { + if !f.is_empty() && !m.name.to_lowercase().contains(&f) && !m.description.to_lowercase().contains(&f) { + continue; + } + let icon = if m.kind == MacroKind::Page { "🗋" } else { "☐" }; + let sel = self.eng.macro_sel.as_deref() == Some(m.name.as_str()); + if ui.selectable_label(sel, format!("{icon} {}", m.name)).on_hover_text(&m.description).clicked() { + self.eng.macro_sel = Some(m.name.clone()); + self.eng.macro_values.clear(); + } + } + }); + } + if self.macro_lib.macros.is_empty() { + ui.weak("No macros yet. Select items in a schematic and save them as a macro."); + } + }); + }); + ui.separator(); + ui.vertical(|ui| { + let Some(i) = self.eng.macro_sel.as_ref().and_then(|n| self.macro_lib.macros.iter().position(|m| &m.name == n)) else { + ui.weak("Select a macro."); + return; + }; + let values = &mut self.eng.macro_values; + let m = &mut self.macro_lib.macros[i]; + egui::ScrollArea::vertical().id_salt("macrodetail").auto_shrink([false, false]).show(ui, |ui| { + ui.horizontal(|ui| { + ui.heading(&m.name); + ui.weak(if m.kind == MacroKind::Page { "page macro" } else { "window macro" }); + }); + egui::Grid::new("macroprops").num_columns(2).show(ui, |ui| { + ui.label("Category"); + ui.text_edit_singleline(&mut m.category); + ui.end_row(); + ui.label("Description"); + ui.text_edit_multiline(&mut m.description); + ui.end_row(); + if m.kind == MacroKind::Page { + ui.label("Page description"); + ui.text_edit_singleline(&mut m.page_description); + ui.end_row(); + } + }); + ui.weak(m.summary()); + clip_preview(ui, &m.clip, vec2(420.0, 200.0)); + let placeholders = m.placeholders(); + if !placeholders.is_empty() { + ui.separator(); + ui.label(RichText::new("Value sets").strong()); + let mut remove = None; + egui::Grid::new("valuesets").striped(true).num_columns(placeholders.len() + 2).show(ui, |ui| { + ui.label(RichText::new("Name").strong()); + for ph in &placeholders { + ui.label(RichText::new(format!("{{{ph}}}")).strong()); + } + ui.label(""); + ui.end_row(); + for (vi, vs) in m.value_sets.iter_mut().enumerate() { + ui.add_sized([110.0, 20.0], egui::TextEdit::singleline(&mut vs.name)); + for ph in &placeholders { + ui.add_sized([100.0, 20.0], egui::TextEdit::singleline(vs.values.entry(ph.clone()).or_default())); + } + if ui.small_button("🗑").clicked() { + remove = Some(vi); + } + ui.end_row(); + } + }); + if let Some(vi) = remove { + m.value_sets.remove(vi); + } + if ui.button("➕ Value set").clicked() { + let name = format!("Set {}", m.value_sets.len() + 1); + m.value_sets.push(macros::ValueSet { name, values: values.clone() }); + } + ui.separator(); + ui.horizontal(|ui| { + ui.label(RichText::new("Insert with").strong()); + egui::ComboBox::from_id_salt("useset").selected_text("value set…").show_ui(ui, |ui| { + for vs in &m.value_sets { + if ui.button(&vs.name).clicked() { + *values = vs.values.clone(); + } + } + }); + }); + egui::Grid::new("insertvalues").num_columns(2).show(ui, |ui| { + for ph in &placeholders { + ui.label(format!("{{{ph}}}")); + ui.text_edit_singleline(values.entry(ph.clone()).or_default()); + ui.end_row(); + } + }); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + let label = if m.kind == MacroKind::Page { "➕ Insert as new page" } else { "➕ Insert (click into the page)" }; + if ui.button(label).clicked() { + action = Some(MacroAction::Insert(i)); + } + if ui.button("🗑 Delete macro").clicked() { + action = Some(MacroAction::Delete(i)); + } + }); + }); + }); + }); + }); + self.eng.show_macros = open; + if let Some(whole_page) = save { + self.save_as_macro(whole_page); + } + match action { + Some(MacroAction::Insert(i)) => { + let m = self.macro_lib.macros[i].clone(); + if m.kind == MacroKind::Page { + let at = macros::insert_page(&mut self.prj, self.page, &m, &self.eng.macro_values); + self.goto(at, 0); + self.notify(ctx, format!("Page macro {} inserted as page {}", m.name, self.prj.pages[at].name)); + } else { + self.editor.insert = Some(m.resolve(&self.eng.macro_values)); + self.editor.set_tool(Tool::Insert); + self.workspace = super::Workspace::Schematic; + } + } + Some(MacroAction::Delete(i)) => { + self.macro_lib.macros.remove(i); + self.eng.macro_sel = None; + } + Some(MacroAction::Export) => { + let json = serde_json::to_string_pretty(&self.macro_lib).unwrap_or_default(); + self.export(ctx, "macros.json".into(), ("JSON", "json"), json); + } + Some(MacroAction::Import) => self.io.open(ctx, Purpose::Macros), + None => {} + } + } + + fn strips_window(&mut self, ctx: &egui::Context) { + if !self.eng.show_strips { + return; + } + let tags = strips::strip_tags(&self.prj); + if !tags.contains(&self.eng.strip) { + self.eng.strip = tags.first().cloned().unwrap_or_default(); + } + let strip = self.eng.strip.clone(); + let rows = strips::rows(&self.prj, &strip, &self.analysis.netlist, &self.analysis.open); + let mut data = self.prj.strips.get(&strip).cloned().unwrap_or_default(); + let before = data.clone(); + let mut open = true; + let (mut renumber, mut sort) = (false, false); + let mut moved = None; + let mut relabel: Vec<(usize, usize, String, String)> = Vec::new(); + let mut jump = None; + egui::Window::new("Terminal strips").open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { + if tags.is_empty() { + ui.weak("No terminal strips: place terminals in a schematic first."); + return; + } + ui.horizontal_wrapped(|ui| { + ui.label("Strip"); + egui::ComboBox::from_id_salt("strip").selected_text(&strip).show_ui(ui, |ui| { + for t in &tags { + ui.selectable_value(&mut self.eng.strip, t.clone(), t); + } + }); + ui.separator(); + ui.label("Spare terminals"); + ui.add(egui::DragValue::new(&mut data.spares).range(0..=500)); + ui.separator(); + renumber = ui.button("Renumber 1 … n").on_hover_text("In strip order; PE and other non-numeric terminals keep their designation").clicked(); + sort = ui.button("Sort by designation").clicked(); + }); + ui.weak("Terminals with the same jumper number are bridged (same potential). Spare terminals are counted in the bill of materials."); + ui.separator(); + egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { + egui::Grid::new("strip").striped(true).num_columns(8).spacing([10.0, 4.0]).show(ui, |ui| { + for h in ["", "Terminal", "Jumper", "External (top)", "Internal (bottom)", "Potential", "Function text", "Location"] { + ui.label(RichText::new(h).strong()); + } + ui.end_row(); + let placed = rows.iter().filter(|r| r.terminal.is_some()).count(); + for (i, r) in rows.iter().enumerate() { + let Some(t) = &r.terminal else { + ui.label(""); + ui.weak(&r.label); + ui.label(""); + ui.weak("spare"); + ui.end_row(); + continue; + }; + ui.horizontal(|ui| { + if ui.add_enabled(i > 0, egui::Button::new("⏶").small()).clicked() { + moved = Some((i, true)); + } + if ui.add_enabled(i + 1 < placed, egui::Button::new("⏷").small()).clicked() { + moved = Some((i, false)); + } + }); + let mut label = r.label.clone(); + ui.add_sized([50.0, 20.0], egui::TextEdit::singleline(&mut label)); + if label != r.label { + relabel.push((t.page, t.sym, r.label.clone(), label)); + } + let mut j = data.jumpers.get(&r.label).copied().unwrap_or(0); + if ui.add(egui::DragValue::new(&mut j).range(0..=99)).on_hover_text("0 = no jumper").changed() { + if j == 0 { + data.jumpers.remove(&r.label); + } else { + data.jumpers.insert(r.label.clone(), j); + } + } + ui.label(&r.external); + ui.label(&r.internal); + ui.label(&r.potential); + ui.label(&r.function_text); + if ui.link(&r.location).clicked() { + jump = Some((t.page, t.id)); + } + ui.end_row(); + } + }); + }); + }); + self.eng.show_strips = open; + if data != before { + self.prj.strips.insert(strip.clone(), data); + } + for (page, sym, old, new) in relabel { + self.prj.pages[page].symbols[sym].label = new.clone(); + if let Some(d) = self.prj.strips.get_mut(&strip) { + if let Some(j) = d.jumpers.remove(&old) { + d.jumpers.insert(new.clone(), j); + } + for o in d.order.iter_mut().filter(|o| **o == old) { + *o = new.clone(); + } + } + } + if let Some((i, up)) = moved { + strips::move_terminal(&mut self.prj, &strip, i, up); + } + if sort { + if let Some(d) = self.prj.strips.get_mut(&strip) { + d.order.clear(); + } + } + if renumber { + let n = strips::renumber(&mut self.prj, &strip); + self.notify(ctx, format!("{strip}: {n} terminals renumbered")); + } + if let Some((pg, id)) = jump { + self.goto(pg, id); + } + } + + fn plc_window(&mut self, ctx: &egui::Context) { + if !self.eng.show_plc { + return; + } + let cards = plc::cards(&self.prj); + if !self.eng.card.is_empty() && !cards.contains(&self.eng.card) { + self.eng.card.clear(); + } + let card = self.eng.card.clone(); + let points: Vec = + plc::points(&self.prj, &self.analysis.netlist).into_iter().filter(|p| card.is_empty() || p.card == card).collect(); + let mut data = self.prj.plc_cards.get(&card).cloned().unwrap_or_default(); + let before = data.clone(); + let mut open = true; + let (mut readdress, mut export, mut import) = (false, false, false); + let mut edits: Vec<(usize, usize, Option, Option)> = Vec::new(); + let mut jump = None; + egui::Window::new("PLC overview").open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { + ui.horizontal_wrapped(|ui| { + ui.label("Card"); + egui::ComboBox::from_id_salt("plccard").selected_text(if card.is_empty() { "all cards" } else { &card }).show_ui(ui, |ui| { + ui.selectable_value(&mut self.eng.card, String::new(), "all cards"); + for c in &cards { + ui.selectable_value(&mut self.eng.card, c.clone(), c); + } + }); + ui.separator(); + export = ui.button("⬇ Export symbol table (CSV)…").on_hover_text("Name; Data Type; Logical Address; Comment – for PLC programming tools").clicked(); + import = ui.button("⬆ Import symbol table…").on_hover_text("Takes the comments as function texts (matched by address)").clicked(); + }); + if !card.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label("Start byte"); + ui.add(egui::DragValue::new(&mut data.start_byte).range(0..=65535)); + ui.label("Rack"); + ui.add(egui::TextEdit::singleline(&mut data.rack).desired_width(40.0)); + ui.label("Slot"); + ui.add(egui::TextEdit::singleline(&mut data.slot).desired_width(40.0)); + ui.label("Description"); + ui.add(egui::TextEdit::singleline(&mut data.description).desired_width(180.0)); + readdress = ui.button("Readdress card").on_hover_text("Consecutive addresses from the start byte, in schematic order").clicked(); + }); + } + ui.separator(); + egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { + egui::Grid::new("plcpoints").striped(true).num_columns(6).spacing([10.0, 4.0]).show(ui, |ui| { + for h in ["Card", "Address", "Type", "Function text", "Connected to", "Location"] { + ui.label(RichText::new(h).strong()); + } + ui.end_row(); + for p in &points { + ui.label(&p.card); + let mut addr = p.address.clone(); + ui.add_sized([60.0, 20.0], egui::TextEdit::singleline(&mut addr)); + ui.label(if p.input { "DI" } else { "DO" }); + let mut text = p.function_text.clone(); + ui.add_sized([200.0, 20.0], egui::TextEdit::singleline(&mut text)); + if addr != p.address || text != p.function_text { + edits.push((p.page, p.sym, (addr != p.address).then_some(addr), (text != p.function_text).then_some(text))); + } + ui.label(&p.connected); + if ui.link(&p.location).clicked() { + jump = Some((p.page, p.id)); + } + ui.end_row(); + } + }); + if points.is_empty() { + ui.weak("No PLC inputs / outputs placed."); + } + }); + }); + self.eng.show_plc = open; + if data != before { + self.prj.plc_cards.insert(card.clone(), data); + } + for (page, sym, addr, text) in edits { + let s = &mut self.prj.pages[page].symbols[sym]; + if let Some(a) = addr { + s.label = a; + } + if let Some(t) = text { + s.function_text = t; + } + } + if readdress { + let n = plc::readdress(&mut self.prj, &card); + self.notify(ctx, format!("{card}: {n} addresses changed")); + } + if export { + let csv = plc::symbol_table(&self.prj, &self.analysis.netlist); + self.export(ctx, "plc_symbols.csv".into(), ("CSV", "csv"), csv); + } + if import { + self.io.open(ctx, Purpose::PlcTable); + } + if let Some((pg, id)) = jump { + self.goto(pg, id); + } + } + + fn revisions_window(&mut self, ctx: &egui::Context) { + if !self.eng.show_revisions { + return; + } + let mut open = true; + let mut create = false; + let mut lock = None; + let mut jump = None; + let mut overview = false; + if self.eng.rev_name.is_empty() { + self.eng.rev_name = revision::next_name(&self.prj); + self.eng.rev_date = self.prj.info.date.clone(); + self.eng.rev_author = self.prj.info.creator.clone(); + } + let locked = self.prj.pages.iter().filter(|p| p.locked).count(); + egui::Window::new("Revisions").open(&mut open).default_size([640.0, 480.0]).show(ctx, |ui| { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.label(RichText::new("Revisions").strong()); + egui::Grid::new("revs").striped(true).num_columns(4).show(ui, |ui| { + for h in ["Index", "Date", "Author", "Description"] { + ui.label(RichText::new(h).strong()); + } + ui.end_row(); + for r in &self.prj.revisions { + ui.label(&r.name); + ui.label(&r.date); + ui.label(&r.author); + ui.label(&r.description); + ui.end_row(); + } + }); + if self.prj.revisions.is_empty() { + ui.weak("No revision yet. Changes are tracked from the first revision on."); + } + ui.separator(); + ui.label(RichText::new("New revision").strong()); + egui::Grid::new("newrev").num_columns(2).show(ui, |ui| { + ui.label("Index"); + ui.add(egui::TextEdit::singleline(&mut self.eng.rev_name).desired_width(60.0)); + ui.end_row(); + ui.label("Date"); + ui.add(egui::TextEdit::singleline(&mut self.eng.rev_date).hint_text("YYYY-MM-DD").desired_width(100.0)); + ui.end_row(); + ui.label("Author"); + ui.text_edit_singleline(&mut self.eng.rev_author); + ui.end_row(); + ui.label("Description"); + ui.text_edit_multiline(&mut self.eng.rev_description); + ui.end_row(); + }); + ui.checkbox(&mut self.eng.rev_release, "Release: lock all pages"); + create = ui.add_enabled(!self.eng.rev_name.trim().is_empty(), egui::Button::new("Create revision")).clicked(); + ui.separator(); + ui.horizontal_wrapped(|ui| { + ui.label(format!("{locked} of {} pages locked", self.prj.pages.len())); + if ui.button("Lock all").clicked() { + lock = Some(true); + } + if ui.button("Unlock all").clicked() { + lock = Some(false); + } + let pg = &mut self.prj.pages[self.page]; + ui.checkbox(&mut pg.locked, format!("Page {} locked", pg.name)); + }); + ui.separator(); + ui.horizontal(|ui| { + let since = self.prj.revisions.last().map(|r| r.name.clone()).unwrap_or_default(); + ui.label(RichText::new(if since.is_empty() { "Changes".to_string() } else { format!("Changes since revision {since}") }).strong()); + ui.checkbox(&mut self.editor.show_revision_marks, "Revision marks"); + overview = ui.button("📊 Revision overview").clicked(); + }); + for pc in &self.analysis.changes { + let title = match pc.page { + Some(_) => format!("Page {} ({})", pc.name, pc.changes.len()), + None => format!("Page {} (deleted)", pc.name), + }; + egui::CollapsingHeader::new(title).id_salt(("chg", pc.page_id)).show(ui, |ui| { + for c in &pc.changes { + let text = format!("{} {} {}", c.what, c.kind.title(), c.label); + match pc.page { + Some(pi) if c.kind != revision::ChangeKind::Removed => { + if ui.link(text.trim()).clicked() { + jump = Some((pi, if c.what == "Page" { 0 } else { c.id })); + } + } + _ => { + ui.label(RichText::new(text.trim()).color(Color32::from_rgb(200, 80, 80))); + } + } + } + }); + } + if self.analysis.changes.is_empty() && !self.prj.revisions.is_empty() { + ui.weak("No changes since the last revision."); + } + }); + }); + self.eng.show_revisions = open; + if create { + let e = &self.eng; + revision::create(&mut self.prj, e.rev_name.trim(), &e.rev_date, &e.rev_author, &e.rev_description, e.rev_release); + self.notify(ctx, format!("Revision {} created", self.eng.rev_name.trim())); + self.eng.rev_name.clear(); + self.eng.rev_description.clear(); + } + if let Some(l) = lock { + for pg in &mut self.prj.pages { + pg.locked = l; + } + } + if let Some((pg, id)) = jump { + self.goto(pg, id); + } + if overview { + self.report_kind = ReportKind::RevisionOverview; + self.show_reports = true; + } + } +} diff --git a/src/app/forms_ui.rs b/src/app/forms_ui.rs new file mode 100644 index 00000000..4be42334 --- /dev/null +++ b/src/app/forms_ui.rs @@ -0,0 +1,447 @@ +//! Forms window: title block editor (lines, rectangles, texts with placeholders) +//! and report forms (columns, order, rows per page). + +use super::App; +use crate::editor::{EguiDraw, Palette}; +use crate::forms::{self, Form, FormItem, FormLibrary, ReportForm}; +use crate::geom::{p, P}; +use crate::io::Purpose; +use crate::model::{ReportKind, FRAME_X0, TITLE_Y0}; +use crate::render::Ink; +use crate::symbols::Anchor; +use egui::{vec2, Color32, PointerButton, RichText, Sense, Stroke}; + +#[derive(Clone, Copy, PartialEq, Eq, Default)] +enum Tab { + #[default] + TitleBlocks, + Reports, +} + +#[derive(Default)] +pub struct FormsUi { + pub open: bool, + tab: Tab, + /// Name of the edited title block. + form: String, + item: Option, + drag: Option

, + report: Option, +} + +impl FormsUi { + pub fn busy(&self) -> bool { + self.drag.is_some() + } + + /// Opens the report form of a report. + pub fn open_report(&mut self, kind: ReportKind) { + self.open = true; + self.tab = Tab::Reports; + self.report = Some(kind); + } +} + +enum Action { + Import, + Export, +} + +impl App { + pub(super) fn forms_window(&mut self, ctx: &egui::Context) { + if !self.forms_ui.open { + return; + } + let mut open = true; + let mut action = None; + egui::Window::new("Forms – title blocks and reports").open(&mut open).default_size([1150.0, 560.0]).show(ctx, |ui| { + ui.horizontal(|ui| { + ui.selectable_value(&mut self.forms_ui.tab, Tab::TitleBlocks, RichText::new("Title blocks").strong()); + ui.selectable_value(&mut self.forms_ui.tab, Tab::Reports, RichText::new("Report forms").strong()); + }); + ui.separator(); + match self.forms_ui.tab { + Tab::TitleBlocks => action = self.title_block_tab(ui), + Tab::Reports => self.report_form_tab(ui), + } + }); + self.forms_ui.open = open; + match action { + Some(Action::Import) => self.io.open(ctx, Purpose::Forms), + Some(Action::Export) => { + let lib = FormLibrary { title_blocks: self.prj.forms.title_blocks.clone() }; + let json = serde_json::to_string_pretty(&lib).unwrap_or_default(); + self.export(ctx, "title_blocks.json".into(), ("OpenECraft title blocks", "json"), json); + } + None => {} + } + } + + fn title_block_tab(&mut self, ui: &mut egui::Ui) -> Option { + let mut action = None; + let names = forms::names(&self.prj); + let fu = &mut self.forms_ui; + let prj = &mut self.prj; + if !names.contains(&fu.form) { + fu.form = if prj.forms.default_title_block.is_empty() { forms::STANDARD.into() } else { prj.forms.default_title_block.clone() }; + fu.item = None; + } + let custom = prj.forms.title_blocks.iter().position(|f| f.name == fu.form); + ui.horizontal_wrapped(|ui| { + ui.label("Title block"); + egui::ComboBox::from_id_salt("tbsel").selected_text(&fu.form).width(180.0).show_ui(ui, |ui| { + for n in &names { + let tag = if prj.forms.title_blocks.iter().any(|f| &f.name == n) { "" } else { " (built-in)" }; + if ui.selectable_label(&fu.form == n, format!("{n}{tag}")).clicked() { + fu.form = n.clone(); + fu.item = None; + } + } + }); + if ui.button("Copy as new").on_hover_text("Editable copy of this title block").clicked() { + let mut f = forms::find(prj, &fu.form).into_owned(); + let mut name = format!("{} (copy)", f.name); + while names.contains(&name) { + name.push('+'); + } + f.name = name.clone(); + prj.forms.title_blocks.push(f); + fu.form = name; + fu.item = None; + } + if ui.button("New empty").clicked() { + let mut name = "My title block".to_string(); + while names.contains(&name) { + name.push('+'); + } + let line = FormItem::Line { a: p(0.0, 0.0), b: p(forms::AREA_W, 0.0), width: 0.5 }; + prj.forms.title_blocks.push(Form { name: name.clone(), items: vec![line] }); + fu.form = name; + fu.item = None; + } + let is_default = prj.forms.default_title_block == fu.form || (prj.forms.default_title_block.is_empty() && fu.form == forms::STANDARD); + if ui.add_enabled(!is_default, egui::Button::new("Use for all pages")).on_hover_text("Project default; pages can choose their own in the page properties").clicked() { + prj.forms.default_title_block = if fu.form == forms::STANDARD { String::new() } else { fu.form.clone() }; + } + if let Some(ci) = custom { + if ui.button("🗑 Delete").on_hover_text("Pages using it get the project default").clicked() { + let name = prj.forms.title_blocks.remove(ci).name; + for pg in prj.pages.iter_mut().filter(|pg| pg.title_block == name) { + pg.title_block.clear(); + } + if prj.forms.default_title_block == name { + prj.forms.default_title_block.clear(); + } + fu.item = None; + return; + } + } + ui.separator(); + if ui.button("⬆ Import…").clicked() { + action = Some(Action::Import); + } + if ui.add_enabled(!prj.forms.title_blocks.is_empty(), egui::Button::new("⬇ Export…")).on_hover_text("The project's own title blocks").clicked() { + action = Some(Action::Export); + } + }); + let used = (0..prj.pages.len()).filter(|&i| forms::title_block(prj, i).name == fu.form).count(); + ui.weak(format!("Used on {used} of {} pages", prj.pages.len())); + let custom = prj.forms.title_blocks.iter().position(|f| f.name == fu.form); + let page = self.page.min(prj.pages.len().saturating_sub(1)); + match custom { + None => { + ui.colored_label(Color32::from_rgb(220, 140, 0), "Built-in title blocks are read only – use “Copy as new” to make your own."); + let mut form = forms::find(prj, &fu.form).into_owned(); + preview(ui, fu, prj, page, &mut form, false); + } + Some(ci) => { + let mut form = prj.forms.title_blocks[ci].clone(); + let old_name = form.name.clone(); + ui.horizontal(|ui| { + ui.label("Name"); + ui.text_edit_singleline(&mut form.name); + }); + preview(ui, fu, prj, page, &mut form, true); + ui.separator(); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(380.0); + ui.horizontal_wrapped(|ui| { + let mid = p(forms::AREA_W / 2.0, forms::AREA_H / 2.0); + let new = [ + ("➕ Line", FormItem::Line { a: mid - p(20.0, 0.0), b: mid + p(20.0, 0.0), width: 0.25 }), + ("➕ Rectangle", FormItem::Rect { a: mid - p(20.0, 8.0), b: mid + p(20.0, 8.0), width: 0.25, fill: false }), + ("➕ Text", FormItem::Text { pos: mid, text: "{project}".into(), size: 2.5, anchor: Anchor::Left, label: false, max_width: 0.0 }), + ("➕ Label", FormItem::Text { pos: mid, text: "Label".into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }), + ]; + for (label, item) in new { + if ui.button(label).clicked() { + form.items.push(item); + fu.item = Some(form.items.len() - 1); + } + } + }); + egui::ScrollArea::vertical().id_salt("tbitems").max_height(220.0).show(ui, |ui| { + for (i, it) in form.items.iter().enumerate() { + let summary = match it { + FormItem::Text { text, .. } => format!("{}: {text}", it.kind_name()), + FormItem::Line { a, b, .. } | FormItem::Rect { a, b, .. } => format!("{}: {:.1},{:.1} – {:.1},{:.1}", it.kind_name(), a.x, a.y, b.x, b.y), + }; + if ui.selectable_label(fu.item == Some(i), summary).clicked() { + fu.item = Some(i); + } + } + }); + }); + ui.separator(); + ui.vertical(|ui| { + ui.set_width(330.0); + item_properties(ui, fu, &mut form); + }); + ui.separator(); + ui.vertical(|ui| { + ui.label(RichText::new("Placeholders").strong()); + ui.weak("Click to add to the selected text."); + egui::ScrollArea::vertical().id_salt("tbph").max_height(240.0).show(ui, |ui| { + for (ph, meaning) in forms::PLACEHOLDERS { + ui.horizontal(|ui| { + if ui.link(RichText::new(ph).monospace()).clicked() { + if let Some(FormItem::Text { text, .. }) = fu.item.and_then(|i| form.items.get_mut(i)) { + text.push_str(ph); + } + } + ui.weak(meaning); + }); + } + }); + }); + }); + // Renaming keeps the pages that use the title block. + if form.name != old_name && !form.name.trim().is_empty() && !names.contains(&form.name) { + for pg in prj.pages.iter_mut().filter(|pg| pg.title_block == old_name) { + pg.title_block = form.name.clone(); + } + if prj.forms.default_title_block == old_name { + prj.forms.default_title_block = form.name.clone(); + } + fu.form = form.name.clone(); + } else { + form.name = old_name; + } + if prj.forms.title_blocks[ci] != form { + prj.forms.title_blocks[ci] = form; + } + } + } + action + } + + fn report_form_tab(&mut self, ui: &mut egui::Ui) { + let fu = &mut self.forms_ui; + let kind = *fu.report.get_or_insert(ReportKind::DeviceList); + ui.horizontal(|ui| { + ui.label("Report"); + egui::ComboBox::from_id_salt("rfkind").selected_text(kind.title()).width(240.0).show_ui(ui, |ui| { + for k in ReportKind::ALL { + ui.selectable_value(&mut fu.report, Some(k), k.title()); + } + }); + }); + let Some(table) = self.analysis.reports.get(&kind) else { return }; + let headers: Vec<&str> = table.headers.clone(); + let mut form = self.prj.forms.reports.get(&kind).cloned().unwrap_or_default(); + egui::Grid::new("rform").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { + ui.label("Page heading"); + ui.add(egui::TextEdit::singleline(&mut form.title).hint_text(kind.title()).desired_width(320.0)); + ui.end_row(); + ui.label("Rows per page"); + let mut rows = if form.rows == 0 { crate::render::REPORT_ROWS_PER_PAGE } else { form.rows }; + if ui.add(egui::DragValue::new(&mut rows).range(5..=80)).changed() { + form.rows = if rows == crate::render::REPORT_ROWS_PER_PAGE { 0 } else { rows }; + } + ui.end_row(); + }); + ui.add_space(4.0); + ui.label(RichText::new("Columns").strong()); + // Shown columns in their order, then the hidden ones. + let shown: Vec = forms::report_columns(Some(&form), &headers); + let mut order: Vec<(usize, bool)> = shown.iter().map(|&c| (c, true)).collect(); + order.extend((0..headers.len()).filter(|c| !shown.contains(c)).map(|c| (c, false))); + let mut changed = false; + let n = order.len(); + let mut swap = None; + for (pos, (c, on)) in order.iter_mut().enumerate() { + ui.horizontal(|ui| { + changed |= ui.checkbox(on, headers[*c]).changed(); + if ui.add_enabled(pos > 0, egui::Button::new("⬆").small()).clicked() { + swap = Some((pos, pos - 1)); + } + if ui.add_enabled(pos + 1 < n, egui::Button::new("⬇").small()).clicked() { + swap = Some((pos, pos + 1)); + } + }); + } + if let Some((a, b)) = swap { + order.swap(a, b); + changed = true; + } + if changed { + let cols: Vec = order.iter().filter(|(_, on)| *on).map(|(c, _)| *c).collect(); + let all_in_order = cols.len() == headers.len() && cols.iter().enumerate().all(|(i, c)| i == *c); + form.columns = if all_in_order || cols.is_empty() { Vec::new() } else { cols.iter().map(|&c| headers[c].to_string()).collect() }; + } + ui.horizontal(|ui| { + if ui.button("Reset to standard").clicked() { + form = ReportForm::default(); + } + ui.weak("Applies to report pages, the PDF and the print export."); + }); + let stored = self.prj.forms.reports.get(&kind).cloned().unwrap_or_default(); + if form != stored { + if form == ReportForm::default() { + self.prj.forms.reports.remove(&kind); + } else { + self.prj.forms.reports.insert(kind, form); + } + } + } +} + +/// Title block drawn with the values of the current page; with `edit` its items +/// can be picked and dragged. +fn preview(ui: &mut egui::Ui, fu: &mut FormsUi, prj: &crate::model::Project, page: usize, form: &mut Form, edit: bool) { + let width = ui.available_width().clamp(400.0, 1400.0); + let zoom = width / forms::AREA_W; + let (resp, painter) = ui.allocate_painter(vec2(width, forms::AREA_H * zoom + 8.0), Sense::click_and_drag()); + let pal = Palette::new(ui.visuals().dark_mode); + painter.rect_filled(resp.rect, 2.0, pal.paper); + let origin = resp.rect.min + vec2(0.0, 4.0) - vec2(FRAME_X0, TITLE_Y0) * zoom; + if edit { + pick(fu, &resp, ui, form, origin, zoom); + } + let mut d = EguiDraw { painter: &painter, origin, zoom, pal: &pal, force: None }; + forms::draw(&mut d, form, prj, page); + if let Some(item) = fu.item.and_then(|i| form.items.get(i)) { + let mut s = EguiDraw { painter: &painter, origin, zoom, pal: &pal, force: Some(Ink::Selected) }; + forms::draw(&mut s, &Form { name: String::new(), items: vec![item.clone()] }, prj, page); + if let FormItem::Text { pos, .. } = item { + let c = origin + vec2(FRAME_X0 + pos.x, TITLE_Y0 + pos.y) * zoom; + painter.circle_stroke(c, 3.0, Stroke::new(1.0, pal.selected)); + } + } +} + +/// Properties of the selected title block element. +fn item_properties(ui: &mut egui::Ui, fu: &mut FormsUi, form: &mut Form) { + let Some(i) = fu.item.filter(|i| *i < form.items.len()) else { + ui.weak("Select an element in the list or the drawing."); + return; + }; + let mut delete = false; + let mut duplicate = false; + let pt = |ui: &mut egui::Ui, label: &str, q: &mut P| { + ui.label(label); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut q.x).speed(0.5).range(0.0..=forms::AREA_W).prefix("x ")); + ui.add(egui::DragValue::new(&mut q.y).speed(0.5).range(0.0..=forms::AREA_H).prefix("y ")); + }); + ui.end_row(); + }; + ui.label(RichText::new(form.items[i].kind_name()).strong()); + egui::Grid::new("tbitem").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| match &mut form.items[i] { + FormItem::Line { a, b, width } => { + pt(ui, "Start", a); + pt(ui, "End", b); + ui.label("Line width"); + ui.add(egui::DragValue::new(width).speed(0.05).range(0.05..=2.0).suffix(" mm")); + ui.end_row(); + } + FormItem::Rect { a, b, width, fill } => { + pt(ui, "Corner", a); + pt(ui, "Corner", b); + ui.label("Line width"); + ui.add(egui::DragValue::new(width).speed(0.05).range(0.0..=2.0).suffix(" mm")); + ui.end_row(); + ui.label("Filled"); + ui.checkbox(fill, ""); + ui.end_row(); + } + FormItem::Text { pos, text, size, anchor, label, max_width } => { + ui.label("Text"); + ui.add(egui::TextEdit::multiline(text).desired_rows(2).desired_width(220.0)); + ui.end_row(); + pt(ui, "Position", pos); + ui.label("Size"); + ui.add(egui::DragValue::new(size).speed(0.1).range(0.8..=20.0).suffix(" mm")); + ui.end_row(); + ui.label("Alignment"); + ui.horizontal(|ui| { + ui.selectable_value(anchor, Anchor::Left, "Left"); + ui.selectable_value(anchor, Anchor::Center, "Centre"); + ui.selectable_value(anchor, Anchor::Right, "Right"); + }); + ui.end_row(); + ui.label("Style"); + ui.horizontal(|ui| { + ui.selectable_value(label, false, "Value"); + ui.selectable_value(label, true, "Label (grey)"); + }); + ui.end_row(); + ui.label("Max. width"); + ui.add(egui::DragValue::new(max_width).speed(0.5).range(0.0..=forms::AREA_W).suffix(" mm")) + .on_hover_text("Longer values are drawn smaller (0 = no limit)"); + ui.end_row(); + } + }); + ui.horizontal(|ui| { + duplicate = ui.button("Duplicate").clicked(); + delete = ui.button("🗑 Delete").clicked(); + }); + if duplicate { + let mut copy = form.items[i].clone(); + copy.translate(p(2.0, 2.0)); + form.items.push(copy); + fu.item = Some(form.items.len() - 1); + } + if delete { + form.items.remove(i); + fu.item = None; + } +} + +/// Picking and dragging in the editable preview. +fn pick(fu: &mut FormsUi, resp: &egui::Response, ui: &egui::Ui, form: &mut Form, origin: egui::Pos2, zoom: f32) { + let to_mm = |s: egui::Pos2| p((s.x - origin.x) / zoom - FRAME_X0, (s.y - origin.y) / zoom - TITLE_Y0); + let tol = 6.0 / zoom; + let nearest = |form: &Form, q: P| { + form.items + .iter() + .enumerate() + .map(|(i, it)| (i, it.distance(q))) + .filter(|(_, d)| *d <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + }; + if resp.drag_started_by(PointerButton::Primary) { + if let Some(q) = ui.input(|i| i.pointer.press_origin()).map(to_mm) { + fu.item = nearest(form, q); + fu.drag = fu.item.map(|_| crate::symlib::snap(q, 0.5)); + } + } + if let (Some(last), Some(i), Some(q)) = (fu.drag, fu.item, resp.interact_pointer_pos().map(to_mm)) { + let q = crate::symlib::snap(q, 0.5); + let d = q - last; + if (d.x != 0.0 || d.y != 0.0) && i < form.items.len() { + form.items[i].translate(d); + fu.drag = Some(q); + } + } + if resp.drag_stopped() { + fu.drag = None; + } + if resp.clicked_by(PointerButton::Primary) { + if let Some(q) = resp.interact_pointer_pos().map(to_mm) { + fu.item = nearest(form, q); + } + } +} diff --git a/src/app/harness_ui.rs b/src/app/harness_ui.rs new file mode 100644 index 00000000..16fb55fc --- /dev/null +++ b/src/app/harness_ui.rs @@ -0,0 +1,155 @@ +//! Harness window: harnesses with their wires, connectors (pin assignment), lengths +//! and bundle diameter; KBL export. + +use super::App; +use crate::harness::{self, Harness}; +use crate::model::ReportKind; +use crate::structure; +use egui::{Color32, RichText}; + +#[derive(Default)] +pub struct HarnessUi { + pub open: bool, + /// Tag of the harness whose connectors are shown. + sel: Option, +} + +impl App { + pub(super) fn harness_window(&mut self, ctx: &egui::Context) { + if !self.harness_ui.open { + return; + } + let mut open = true; + let mut renamed: Vec<(String, String)> = Vec::new(); + let mut remove = None; + let mut unassign: Option<(String, [String; 2])> = None; + let (mut kbl, mut report) = (false, false); + let structure = structure::page_structure(&self.prj.pages[self.page]); + egui::Window::new("Harnesses").open(&mut open).default_size([900.0, 460.0]).show(ctx, |ui| { + ui.horizontal_wrapped(|ui| { + if ui.button("➕ New harness").on_hover_text("In the structure of the current page").clicked() { + let tag = self.prj.next_tag(&structure, "WH"); + let id = self.prj.new_id(); + self.harness_ui.sel = Some(tag.clone()); + self.prj.harnesses.push(Harness { id, tag, ..Default::default() }); + } + report = ui.button("📊 Harness data").on_hover_text("Report with all harness wires").clicked(); + kbl = ui.add_enabled(!self.prj.harnesses.is_empty(), egui::Button::new("⬇ Export KBL (XML)…")).on_hover_text("Simplified KBL (VDA 4964) for harness manufacturing").clicked(); + ui.weak("Assign connections: select the wires between two devices in the schematic › Assign to harness."); + }); + ui.separator(); + let an = &self.analysis; + // Wires, connectors and bundle diameter per harness. + let stats: Vec<(usize, usize, f32)> = self + .prj + .harnesses + .iter() + .map(|h| { + let ws = harness::wires(&self.prj, an, &h.tag); + (ws.len(), harness::connectors(&ws).len(), harness::bundle_diameter(&ws)) + }) + .collect(); + egui::Grid::new("harnesses").striped(true).num_columns(8).spacing([8.0, 4.0]).show(ui, |ui| { + for h in ["Harness", "Description", "Field length", "Part", "Wires", "Connectors", "Bundle Ø", ""] { + ui.label(RichText::new(h).strong()); + } + ui.end_row(); + for (i, h) in self.prj.harnesses.iter_mut().enumerate() { + let old = h.tag.clone(); + let sel = self.harness_ui.sel.as_deref() == Some(old.as_str()); + ui.horizontal(|ui| { + if ui.selectable_label(sel, "▶").on_hover_text("Show connectors").clicked() { + self.harness_ui.sel = Some(old.clone()); + } + ui.add_sized([100.0, 20.0], egui::TextEdit::singleline(&mut h.tag).font(egui::TextStyle::Monospace)); + }); + if h.tag != old { + renamed.push((old.clone(), h.tag.clone())); + } + ui.add_sized([180.0, 20.0], egui::TextEdit::singleline(&mut h.description)); + ui.add(egui::DragValue::new(&mut h.length).speed(0.1).range(0.0..=1000.0).suffix(" m")) + .on_hover_text("Length of wires that are not routed in the panel layout"); + ui.add_sized([110.0, 20.0], egui::TextEdit::singleline(&mut h.part).hint_text("part number")); + let (n, c, dia) = stats[i]; + ui.label(n.to_string()); + ui.label(c.to_string()); + ui.label(format!("{dia:.1} mm")); + if ui.small_button("🗑").on_hover_text("Delete harness (its wires are removed from it)").clicked() { + remove = Some(i); + } + ui.end_row(); + } + }); + if self.prj.harnesses.is_empty() { + ui.weak("No harnesses defined."); + } + // Connectors of the selected harness + if let Some(tag) = self.harness_ui.sel.clone().filter(|t| self.prj.harnesses.iter().any(|h| &h.tag == t)) { + ui.separator(); + let ws = harness::wires(&self.prj, an, &tag); + let total: f32 = ws.iter().map(|w| w.length).sum(); + ui.label(RichText::new(format!("{tag}: {} wires, {:.2} m wire in total", ws.len(), total / 1000.0)).strong()); + if ws.iter().any(|w| w.length <= 0.0) { + ui.colored_label(Color32::from_rgb(220, 140, 0), "Some wires have no length: place their devices in the panel layout or set the field length."); + } + let stale = harness::stale(&self.prj, an); + ui.collapsing(format!("Connections ({})", self.prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.connections.len()).unwrap_or(0)), |ui| { + egui::ScrollArea::vertical().id_salt("hlist").max_height(160.0).show(ui, |ui| { + for k in self.prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.connections.clone()).unwrap_or_default() { + ui.horizontal(|ui| { + ui.monospace(format!("{} – {}", k[0], k[1])); + if stale.iter().any(|(t, c)| *t == tag && *c == k) { + ui.colored_label(Color32::from_rgb(220, 140, 0), "not in the schematic"); + } + if ui.small_button("🗑").on_hover_text("Remove from the harness").clicked() { + unassign = Some((tag.clone(), k.clone())); + } + }); + } + }); + }); + egui::ScrollArea::vertical().id_salt("hconn").max_height(220.0).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + for c in harness::connectors(&ws) { + ui.group(|ui| { + ui.vertical(|ui| { + ui.label(RichText::new(&c.device).monospace().strong()); + egui::Grid::new(("hpins", &c.device)).striped(true).show(ui, |ui| { + for (pin, number, other) in &c.pins { + ui.monospace(if pin.is_empty() { "–" } else { pin }); + ui.monospace(number); + ui.label(format!("– {other}")); + ui.end_row(); + } + }); + }); + }); + } + }); + }); + } + }); + for (old, new) in renamed { + if self.harness_ui.sel.as_deref() == Some(old.as_str()) { + self.harness_ui.sel = Some(new); + } + } + if let Some(i) = remove { + self.prj.harnesses.remove(i); + } + if let Some((tag, k)) = unassign { + if let Some(h) = self.prj.harnesses.iter_mut().find(|h| h.tag == tag) { + h.connections.retain(|c| *c != k); + } + } + if report { + self.report_kind = ReportKind::HarnessData; + self.show_reports = true; + } + if kbl { + let xml = harness::kbl(&self.prj, &self.analysis); + self.export(ctx, self.suggested_name("kbl"), ("KBL harness data (XML)", "kbl"), xml); + } + self.harness_ui.open = open; + } +} diff --git a/src/app/symbol_editor.rs b/src/app/symbol_editor.rs new file mode 100644 index 00000000..2f792e6f --- /dev/null +++ b/src/app/symbol_editor.rs @@ -0,0 +1,559 @@ +//! Symbol editor: user symbols of the project (graphics, connection points, +//! function), copies of built-in symbols and symbol library files. + +use super::App; +use crate::editor::{EguiDraw, Palette, Tool}; +use crate::geom::{p, P, GRID}; +use crate::io::Purpose; +use crate::model::SymbolInst; +use crate::render::{self, Draw, Ink, VAnchor}; +use crate::symbols::{self, Anchor, FieldKind, Func, Prim}; +use crate::symlib::{self, Hit, SymbolLibrary, UserPin, UserSymbol, DRAW_SNAP}; +use egui::{pos2, vec2, Color32, Key, PointerButton, RichText, Sense, Stroke}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SymTool { + #[default] + Select, + Line, + Rect, + Circle, + Text, + Pin, + TagField, + LabelField, +} + +impl SymTool { + const ALL: [(SymTool, &'static str, &'static str); 8] = [ + (SymTool::Select, "⬉ Select", "Select and drag elements; Del deletes"), + (SymTool::Line, "— Line", "Click start and end point"), + (SymTool::Rect, "☐ Rect", "Click two corners"), + (SymTool::Circle, "○ Circle", "Click centre, then a point on the circle"), + (SymTool::Text, "T Text", "Click to place the text from the field below"), + (SymTool::Pin, "• Connection point", "Click on the 4 mm grid"), + (SymTool::TagField, "Tag field", "Position of the device tag (instead of the tag block)"), + (SymTool::LabelField, "Label field", "Position of the label (terminal number, address …)"), + ]; +} + +pub struct SymbolEditor { + pub open: bool, + /// Key of the edited symbol. + sel: Option, + tool: SymTool, + start: Option

, + hit: Option, + /// Pointer position of the running drag (symbol coordinates, snapped). + drag: Option

, + text: String, + /// Pixels per millimetre. + zoom: f32, +} + +impl Default for SymbolEditor { + fn default() -> Self { + SymbolEditor { open: false, sel: None, tool: SymTool::Select, start: None, hit: None, drag: None, text: "Text".into(), zoom: 12.0 } + } +} + +impl SymbolEditor { + /// True while a drag is running (the symbol is registered when it ends). + pub fn busy(&self) -> bool { + self.drag.is_some() + } + + fn set_tool(&mut self, t: SymTool) { + self.tool = t; + self.start = None; + } +} + +enum Action { + Import, + Export, + Place(String), + Duplicate(usize), + Delete(usize), +} + +impl App { + pub(super) fn symbol_editor_window(&mut self, ctx: &egui::Context) { + if !self.symed.open { + return; + } + let mut open = true; + let mut action = None; + let (prj, se) = (&mut self.prj, &mut self.symed); + if se.sel.as_ref().map(|k| !prj.symbols.iter().any(|u| &u.key == k)).unwrap_or(true) { + se.sel = prj.symbols.first().map(|u| u.key.clone()); + se.hit = None; + } + egui::Window::new("Symbol editor").open(&mut open).default_size([960.0, 520.0]).show(ctx, |ui| { + ui.horizontal_top(|ui| { + // ------------------------------------------------ symbol list + ui.vertical(|ui| { + ui.set_width(180.0); + ui.horizontal_wrapped(|ui| { + if ui.button("➕ New").clicked() { + let mut u = UserSymbol::default(); + u.key = symlib::new_key(&prj.symbols, &u.name); + u.prims.push(Prim::Poly { pts: vec![p(-4.0, -4.0), p(4.0, -4.0), p(4.0, 4.0), p(-4.0, 4.0)], closed: true, fill: false }); + u.pins = vec![UserPin { pos: p(0.0, -8.0), label: "1".into() }, UserPin { pos: p(0.0, 8.0), label: "2".into() }]; + u.prims.push(Prim::Line { a: p(0.0, -8.0), b: p(0.0, -4.0), dashed: false }); + u.prims.push(Prim::Line { a: p(0.0, 4.0), b: p(0.0, 8.0), dashed: false }); + se.sel = Some(u.key.clone()); + prj.symbols.push(u); + } + ui.menu_button("Copy built-in…", |ui| { + egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { + for cat in symbols::Category::ALL { + ui.menu_button(cat.title(), |ui| { + for def in symbols::library().iter().filter(|d| d.category == cat) { + if ui.button(def.name).clicked() { + let u = symlib::from_def(def, &prj.symbols); + se.sel = Some(u.key.clone()); + prj.symbols.push(u); + ui.close(); + } + } + }); + } + }); + }); + }); + ui.horizontal(|ui| { + if ui.button("⬆ Import…").on_hover_text("Merge a symbol library file").clicked() { + action = Some(Action::Import); + } + if ui.add_enabled(!prj.symbols.is_empty(), egui::Button::new("⬇ Export…")).on_hover_text("All user symbols as library file").clicked() { + action = Some(Action::Export); + } + }); + ui.separator(); + egui::ScrollArea::vertical().id_salt("symlist").max_height(420.0).show(ui, |ui| { + let mut libs: Vec<&str> = prj.symbols.iter().map(|u| u.library.as_str()).collect(); + libs.sort(); + libs.dedup(); + let mut pick = None; + for lib in libs { + ui.label(RichText::new(if lib.is_empty() { "(no library)" } else { lib }).strong()); + for u in prj.symbols.iter().filter(|u| u.library == lib) { + let n = symlib::usage(prj, &u.key); + let text = if n > 0 { format!("{} ({n}×)", u.name) } else { u.name.clone() }; + if ui.selectable_label(se.sel.as_ref() == Some(&u.key), text).clicked() { + pick = Some(u.key.clone()); + } + } + } + if let Some(k) = pick { + se.sel = Some(k); + se.hit = None; + se.start = None; + } + if prj.symbols.is_empty() { + ui.weak("No user symbols yet. Create one or copy a built-in symbol."); + } + }); + }); + ui.separator(); + let Some(si) = se.sel.as_ref().and_then(|k| prj.symbols.iter().position(|u| &u.key == k)) else { + return; + }; + // ------------------------------------------------ canvas + ui.vertical(|ui| { + ui.horizontal_wrapped(|ui| { + for (t, label, tip) in SymTool::ALL { + if ui.selectable_label(se.tool == t, label).on_hover_text(tip).clicked() { + se.set_tool(t); + } + } + }); + if se.tool == SymTool::Text { + ui.horizontal(|ui| { + ui.label("Text"); + ui.text_edit_singleline(&mut se.text); + }); + } + let u = &mut prj.symbols[si]; + canvas(ui, se, u); + ui.weak("Wheel: zoom · right click: cancel · graphics snap to 0.5 mm, connection points to the 4 mm grid"); + }); + ui.separator(); + // ------------------------------------------------ properties + ui.vertical(|ui| { + ui.set_width(270.0); + let usage = symlib::usage(prj, &prj.symbols[si].key); + let u = &mut prj.symbols[si]; + egui::ScrollArea::vertical().id_salt("symprops").show(ui, |ui| { + symbol_properties(ui, u); + ui.separator(); + element_properties(ui, se, u); + ui.separator(); + for msg in symlib::problems(u) { + ui.colored_label(Color32::from_rgb(220, 140, 0), format!("⚠ {msg}")); + } + ui.label(format!("Placed {usage}× in the project")); + ui.horizontal(|ui| { + if ui.add_enabled(symlib::problems(u).is_empty(), egui::Button::new("✏ Place in schematic")).clicked() { + action = Some(Action::Place(u.key.clone())); + } + if ui.button("Duplicate").clicked() { + action = Some(Action::Duplicate(si)); + } + let del = ui.add_enabled(usage == 0, egui::Button::new("🗑 Delete")).on_disabled_hover_text("The symbol is placed in the project"); + if del.clicked() { + action = Some(Action::Delete(si)); + } + }); + }); + }); + }); + }); + self.symed.open = open; + match action { + Some(Action::Import) => self.io.open(ctx, Purpose::Symbols), + Some(Action::Export) => { + let lib = SymbolLibrary { symbols: self.prj.symbols.clone() }; + let json = serde_json::to_string_pretty(&lib).unwrap_or_default(); + self.export(ctx, "symbols.json".into(), ("OpenECraft symbol library", "json"), json); + } + Some(Action::Place(key)) => { + symlib::register(&self.prj.symbols); + if let Some(def) = symbols::get(&key) { + self.workspace = super::Workspace::Schematic; + self.editor.set_tool(Tool::Place(def.key)); + self.notify(ctx, format!("Click into the page to place {}", def.name)); + } + } + Some(Action::Duplicate(si)) => { + let mut copy = self.prj.symbols[si].clone(); + copy.name = format!("{} (copy)", copy.name); + copy.key = symlib::new_key(&self.prj.symbols, ©.name); + self.symed.sel = Some(copy.key.clone()); + self.prj.symbols.push(copy); + } + Some(Action::Delete(si)) => { + self.prj.symbols.remove(si); + self.symed.sel = None; + self.symed.hit = None; + } + None => {} + } + } +} + +fn symbol_properties(ui: &mut egui::Ui, u: &mut UserSymbol) { + ui.label(RichText::new("Symbol").strong()); + egui::Grid::new("symprops_grid").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { + ui.label("Name"); + ui.text_edit_singleline(&mut u.name); + ui.end_row(); + ui.label("Library"); + ui.text_edit_singleline(&mut u.library).on_hover_text("Group in the symbol list, e.g. your company"); + ui.end_row(); + ui.label("Function"); + egui::ComboBox::from_id_salt("symfunc").selected_text(u.func.title()).width(200.0).show_ui(ui, |ui| { + for f in Func::ALL { + ui.selectable_value(&mut u.func, f, f.title()); + } + }); + ui.end_row(); + ui.label("Identifying letter"); + ui.add(egui::TextEdit::singleline(&mut u.letter).desired_width(60.0).hint_text("K, Q, MM …")); + ui.end_row(); + ui.label("Default label"); + ui.add(egui::TextEdit::singleline(&mut u.default_label).desired_width(80.0)).on_hover_text("Terminal number, PLC address, potential name …"); + ui.end_row(); + }); + ui.checkbox(&mut u.show_tag, "Show device tag and cross references"); + ui.checkbox(&mut u.show_pin_labels, "Show connection point designations"); + if matches!(u.func, Func::Aux(_)) { + ui.checkbox(&mut u.auto_number, "Number contacts automatically (13/14, 21/22 …)"); + } + if u.func == Func::Terminal && u.pins.len() >= 2 { + let mut bridged = u.bridges.contains(&(0, 1)); + if ui.checkbox(&mut bridged, "Connection points 1 and 2 are connected inside").changed() { + u.bridges.retain(|b| *b != (0, 1)); + if bridged { + u.bridges.push((0, 1)); + } + } + } + ui.weak(format!("Key: {}", u.key)); +} + +fn point_edit(ui: &mut egui::Ui, label: &str, q: &mut P, speed: f32) { + ui.label(label); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut q.x).speed(speed).prefix("x ")); + ui.add(egui::DragValue::new(&mut q.y).speed(speed).prefix("y ")); + }); + ui.end_row(); +} + +fn element_properties(ui: &mut egui::Ui, se: &mut SymbolEditor, u: &mut UserSymbol) { + let mut delete = false; + match se.hit { + Some(Hit::Pin(i)) if i < u.pins.len() => { + ui.label(RichText::new(format!("Connection point {}", i + 1)).strong()); + egui::Grid::new("pinprops").num_columns(2).show(ui, |ui| { + ui.label("Designation"); + ui.text_edit_singleline(&mut u.pins[i].label); + ui.end_row(); + point_edit(ui, "Position", &mut u.pins[i].pos, GRID); + }); + u.pins[i].pos = symlib::snap(u.pins[i].pos, GRID); + delete = ui.button("🗑 Delete connection point").clicked(); + } + Some(Hit::Prim(i)) if i < u.prims.len() => { + let prim = &mut u.prims[i]; + let kind = match prim { + Prim::Line { .. } => "Line", + Prim::Poly { .. } => "Polyline / rectangle", + Prim::Circle { .. } => "Circle", + Prim::Text { .. } => "Text", + Prim::Field { .. } => "Field", + }; + ui.label(RichText::new(kind).strong()); + egui::Grid::new("primprops").num_columns(2).show(ui, |ui| match prim { + Prim::Line { a, b, dashed } => { + point_edit(ui, "Start", a, 0.1); + point_edit(ui, "End", b, 0.1); + ui.label("Dashed"); + ui.checkbox(dashed, ""); + ui.end_row(); + } + Prim::Poly { pts, closed, fill } => { + ui.label("Points"); + ui.label(pts.len().to_string()); + ui.end_row(); + ui.label("Closed / filled"); + ui.horizontal(|ui| { + ui.checkbox(closed, ""); + ui.checkbox(fill, ""); + }); + ui.end_row(); + } + Prim::Circle { c, r, fill } => { + point_edit(ui, "Centre", c, 0.1); + ui.label("Radius"); + ui.add(egui::DragValue::new(r).speed(0.1).range(0.1..=100.0)); + ui.end_row(); + ui.label("Filled"); + ui.checkbox(fill, ""); + ui.end_row(); + } + Prim::Text { pos, text, size, anchor } => { + ui.label("Text"); + ui.text_edit_singleline(text); + ui.end_row(); + point_edit(ui, "Position", pos, 0.1); + ui.label("Size"); + ui.add(egui::DragValue::new(size).speed(0.1).range(0.5..=20.0)); + ui.end_row(); + anchor_edit(ui, anchor); + } + Prim::Field { kind, pos, size, anchor } => { + ui.label("Shows"); + ui.horizontal(|ui| { + ui.selectable_value(kind, FieldKind::Tag, "Device tag"); + ui.selectable_value(kind, FieldKind::Label, "Label"); + }); + ui.end_row(); + point_edit(ui, "Position", pos, 0.1); + ui.label("Size"); + ui.add(egui::DragValue::new(size).speed(0.1).range(0.5..=20.0)); + ui.end_row(); + anchor_edit(ui, anchor); + } + }); + delete = ui.button("🗑 Delete element").clicked(); + } + _ => { + ui.weak("Click an element in the drawing to edit it."); + } + } + if delete { + delete_hit(se, u); + } +} + +fn anchor_edit(ui: &mut egui::Ui, anchor: &mut Anchor) { + ui.label("Alignment"); + ui.horizontal(|ui| { + ui.selectable_value(anchor, Anchor::Left, "Left"); + ui.selectable_value(anchor, Anchor::Center, "Centre"); + ui.selectable_value(anchor, Anchor::Right, "Right"); + }); + ui.end_row(); +} + +fn delete_hit(se: &mut SymbolEditor, u: &mut UserSymbol) { + match se.hit.take() { + Some(Hit::Pin(i)) => symlib::remove_pin(u, i), + Some(Hit::Prim(i)) if i < u.prims.len() => { + u.prims.remove(i); + } + _ => {} + } +} + +fn canvas(ui: &mut egui::Ui, se: &mut SymbolEditor, u: &mut UserSymbol) { + let pal = Palette::new(ui.visuals().dark_mode); + let (resp, painter) = ui.allocate_painter(vec2(400.0, 340.0), Sense::click_and_drag()); + let rect = resp.rect; + painter.rect_filled(rect, 4.0, pal.paper); + let origin = rect.center(); + if resp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 { + se.zoom = (se.zoom * (scroll * 0.002).exp()).clamp(3.0, 60.0); + } + } + let zoom = se.zoom; + let to_mm = move |s: egui::Pos2| p((s.x - origin.x) / zoom, (s.y - origin.y) / zoom); + // Grid: millimetres and the 4 mm connection grid. + let painter = painter.with_clip_rect(rect); + let half = vec2(rect.width(), rect.height()) / 2.0 / se.zoom; + let (nx, ny) = (half.x.ceil() as i32, half.y.ceil() as i32); + for i in -nx..=nx { + let x = origin.x + i as f32 * se.zoom; + let major = i % GRID as i32 == 0; + if major || se.zoom >= 8.0 { + let c = if i == 0 { pal.frame } else if major { pal.grid } else { pal.grid.gamma_multiply(0.35) }; + painter.line_segment([pos2(x, rect.top()), pos2(x, rect.bottom())], Stroke::new(if i == 0 { 1.0 } else { 0.5 }, c)); + } + } + for j in -ny..=ny { + let y = origin.y + j as f32 * se.zoom; + let major = j % GRID as i32 == 0; + if major || se.zoom >= 8.0 { + let c = if j == 0 { pal.frame } else if major { pal.grid } else { pal.grid.gamma_multiply(0.35) }; + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(if j == 0 { 1.0 } else { 0.5 }, c)); + } + } + let ptr = resp.hover_pos().map(to_mm); + let step = if se.tool == SymTool::Pin || matches!(se.hit, Some(Hit::Pin(_))) && se.tool == SymTool::Select { GRID } else { DRAW_SNAP }; + let snapped = ptr.map(|q| symlib::snap(q, step)); + + // Keyboard + if resp.hovered() || resp.has_focus() { + let (esc, del) = ui.input(|i| (i.key_pressed(Key::Escape), i.key_pressed(Key::Delete))); + if esc { + if se.start.is_some() { + se.start = None; + } else { + se.set_tool(SymTool::Select); + } + } + if del && !ui.ctx().egui_wants_keyboard_input() { + delete_hit(se, u); + } + } + if resp.clicked_by(PointerButton::Secondary) { + if se.start.is_some() { + se.start = None; + } else { + se.set_tool(SymTool::Select); + } + } + + // Mouse + let clicked = resp.clicked_by(PointerButton::Primary); + match (se.tool, snapped) { + (SymTool::Select, _) => { + let tol = 6.0 / se.zoom; + if resp.drag_started_by(PointerButton::Primary) { + let press = ui.input(|i| i.pointer.press_origin()).map(to_mm); + if let Some(q) = press { + se.hit = symlib::hit(u, q, tol); + let step = if matches!(se.hit, Some(Hit::Pin(_))) { GRID } else { DRAW_SNAP }; + se.drag = se.hit.map(|_| symlib::snap(q, step)); + } + } + if let (Some(last), Some(q)) = (se.drag, resp.interact_pointer_pos().map(to_mm)) { + let step = if matches!(se.hit, Some(Hit::Pin(_))) { GRID } else { DRAW_SNAP }; + let q = symlib::snap(q, step); + let d = q - last; + if d.x != 0.0 || d.y != 0.0 { + match se.hit { + Some(Hit::Pin(i)) if i < u.pins.len() => u.pins[i].pos = u.pins[i].pos + d, + Some(Hit::Prim(i)) if i < u.prims.len() => symlib::translate(&mut u.prims[i], d), + _ => {} + } + se.drag = Some(q); + } + } + if resp.drag_stopped() { + se.drag = None; + } + if clicked { + se.hit = ptr.and_then(|q| symlib::hit(u, q, tol)); + } + } + (SymTool::Pin, Some(q)) if clicked => { + if !u.pins.iter().any(|x| x.pos.same(q)) { + let label = symlib::next_pin_label(u); + u.pins.push(UserPin { pos: q, label }); + se.hit = Some(Hit::Pin(u.pins.len() - 1)); + } + } + (SymTool::Text, Some(q)) if clicked => { + let text = if se.text.trim().is_empty() { "Text".to_string() } else { se.text.clone() }; + u.prims.push(Prim::Text { pos: q, text, size: 2.0, anchor: Anchor::Left }); + se.hit = Some(Hit::Prim(u.prims.len() - 1)); + } + (SymTool::TagField | SymTool::LabelField, Some(q)) if clicked => { + let kind = if se.tool == SymTool::TagField { FieldKind::Tag } else { FieldKind::Label }; + u.prims.push(Prim::Field { kind, pos: q, size: 2.2, anchor: Anchor::Left }); + se.hit = Some(Hit::Prim(u.prims.len() - 1)); + } + (SymTool::Line | SymTool::Rect | SymTool::Circle, Some(q)) if clicked => match se.start.take() { + None => se.start = Some(q), + Some(a) if !a.same(q) => { + let prim = match se.tool { + SymTool::Line => Prim::Line { a, b: q, dashed: false }, + SymTool::Rect => Prim::Poly { pts: vec![a, p(q.x, a.y), q, p(a.x, q.y)], closed: true, fill: false }, + _ => Prim::Circle { c: a, r: a.dist(q), fill: false }, + }; + u.prims.push(prim); + se.hit = Some(Hit::Prim(u.prims.len() - 1)); + } + Some(_) => {} + }, + _ => {} + } + + // Drawing + let mut d = EguiDraw { painter: &painter, origin, zoom: se.zoom, pal: &pal, force: None }; + let inst = SymbolInst { tag: "-K1".into(), label: if u.default_label.is_empty() { "1".into() } else { u.default_label.clone() }, ..Default::default() }; + render::draw_prims(&mut d, &u.prims, &inst, Ink::Line); + if let Some(Hit::Prim(i)) = se.hit { + if let Some(prim) = u.prims.get(i) { + render::draw_prims(&mut d, std::slice::from_ref(prim), &inst, Ink::Selected); + } + } + for (i, pin) in u.pins.iter().enumerate() { + let ink = if se.hit == Some(Hit::Pin(i)) { Ink::Selected } else { Ink::Pin }; + d.circle(pin.pos, 0.7, 0.2, ink, false); + d.text(pin.pos + p(1.0, -0.9), &pin.label, 1.6, Anchor::Left, VAnchor::Middle, Ink::CrossRef); + } + // Previews + let mut g = EguiDraw { painter: &painter, origin, zoom: se.zoom, pal: &pal, force: Some(Ink::Ghost) }; + if let (Some(a), Some(q)) = (se.start, snapped) { + match se.tool { + SymTool::Line => g.line(a, q, 0.25, Ink::Ghost, false), + SymTool::Rect => g.rect(a, q, 0.25, Ink::Ghost, false), + SymTool::Circle => g.circle(a, a.dist(q), 0.25, Ink::Ghost, false), + _ => {} + } + } + if let (Some(q), true) = (snapped, se.tool != SymTool::Select) { + let c = pos2(origin.x + q.x * se.zoom, origin.y + q.y * se.zoom); + painter.circle_stroke(c, 3.0, Stroke::new(1.0, pal.ghost)); + } + if let Some(q) = ptr { + painter.text(rect.left_top() + vec2(6.0, 6.0), egui::Align2::LEFT_TOP, format!("x {:.1} y {:.1} mm", q.x, q.y), egui::FontId::monospace(11.0), pal.frame); + } +} diff --git a/src/dxf.rs b/src/dxf.rs new file mode 100644 index 00000000..b41fe007 --- /dev/null +++ b/src/dxf.rs @@ -0,0 +1,154 @@ +//! DXF export (AutoCAD R12, millimetres): lines, polylines, circles and texts on +//! layers by kind (lines, wires, texts, frame, cross references …). Several pages +//! are placed side by side. + +use crate::geom::P; +use crate::index::Index; +use crate::model::{Project, PAGE_H, PAGE_W}; +use crate::render::{draw_page, Draw, Ink, Opts, VAnchor}; +use crate::reports::Analysis; +use crate::symbols::Anchor; +use std::fmt::Write; + +/// Layers: name and AutoCAD colour index. +const LAYERS: [(&str, u8); 7] = [ + ("OEC_LINES", 7), + ("OEC_WIRES", 5), + ("OEC_TEXT", 7), + ("OEC_FRAME", 8), + ("OEC_XREF", 4), + ("OEC_ERROR", 1), + ("OEC_FILL", 9), +]; + +fn layer(ink: Ink) -> &'static str { + match ink { + Ink::Wire | Ink::Highlight => "OEC_WIRES", + Ink::Text => "OEC_TEXT", + Ink::Frame | Ink::FrameText => "OEC_FRAME", + Ink::CrossRef => "OEC_XREF", + Ink::Error => "OEC_ERROR", + Ink::Plate | Ink::Fill => "OEC_FILL", + _ => "OEC_LINES", + } +} + +/// Text for DXF: non-ASCII characters as `\U+XXXX`. +fn dxf_text(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + if (' '..='~').contains(&c) { + out.push(c); + } else { + let _ = write!(out, "\\U+{:04X}", c as u32); + } + } + out +} + +pub struct DxfDraw { + out: String, + /// Horizontal offset of the current page. + dx: f32, +} + +impl DxfDraw { + fn pt(&mut self, code: u16, q: P) { + let _ = write!(self.out, "{}\n{:.3}\n{}\n{:.3}\n{}\n0.0\n", code, q.x + self.dx, code + 10, PAGE_H - q.y, code + 20); + } + + fn entity(&mut self, kind: &str, ink: Ink, dashed: bool) { + let _ = write!(self.out, "0\n{kind}\n8\n{}\n", layer(ink)); + if dashed { + self.out.push_str("6\nDASHED\n"); + } + } +} + +impl Draw for DxfDraw { + fn line(&mut self, a: P, b: P, _width: f32, ink: Ink, dashed: bool) { + self.entity("LINE", ink, dashed); + self.pt(10, a); + self.pt(11, b); + } + + fn poly(&mut self, pts: &[P], closed: bool, _width: f32, ink: Ink, fill: bool) { + if fill && (pts.len() == 3 || pts.len() == 4) { + // SOLID corners are given in the order 1, 2, 4, 3. + self.entity("SOLID", ink, false); + let order = if pts.len() == 4 { [0, 1, 3, 2] } else { [0, 1, 2, 2] }; + for (i, k) in order.into_iter().enumerate() { + self.pt(10 + i as u16, pts[k]); + } + return; + } + self.entity("POLYLINE", ink, false); + let _ = write!(self.out, "66\n1\n70\n{}\n10\n0.0\n20\n0.0\n30\n0.0\n", if closed || fill { 1 } else { 0 }); + for q in pts { + self.entity("VERTEX", ink, false); + self.pt(10, *q); + } + self.entity("SEQEND", ink, false); + } + + fn circle(&mut self, c: P, r: f32, _width: f32, ink: Ink, _fill: bool) { + self.entity("CIRCLE", ink, false); + self.pt(10, c); + let _ = write!(self.out, "40\n{r:.3}\n"); + } + + fn text(&mut self, pos: P, text: &str, size: f32, h: Anchor, v: VAnchor, ink: Ink) { + if text.is_empty() { + return; + } + self.entity("TEXT", ink, false); + self.pt(10, pos); + // Cap height of the SVG / screen text (font size 1.25 × size). + let _ = write!(self.out, "40\n{:.3}\n1\n{}\n", size * 0.9, dxf_text(text)); + let h = match h { + Anchor::Left => 0, + Anchor::Center => 1, + Anchor::Right => 2, + }; + let v = match v { + VAnchor::Middle => 2, + VAnchor::Bottom => 1, + }; + let _ = write!(self.out, "72\n{h}\n73\n{v}\n"); + self.pt(11, pos); + } +} + +/// DXF header with line types and the given layers (name, AutoCAD colour index). +pub fn header(out: &mut String, layers: &[(String, u8)]) { + out.push_str("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1009\n9\n$INSUNITS\n70\n4\n0\nENDSEC\n"); + out.push_str("0\nSECTION\n2\nTABLES\n"); + out.push_str("0\nTABLE\n2\nLTYPE\n70\n2\n"); + out.push_str("0\nLTYPE\n2\nCONTINUOUS\n70\n0\n3\nSolid line\n72\n65\n73\n0\n40\n0.0\n"); + out.push_str("0\nLTYPE\n2\nDASHED\n70\n0\n3\nDashed\n72\n65\n73\n2\n40\n2.5\n49\n1.5\n49\n-1.0\n"); + out.push_str("0\nENDTAB\n"); + let _ = write!(out, "0\nTABLE\n2\nLAYER\n70\n{}\n", layers.len()); + for (name, color) in layers { + let _ = write!(out, "0\nLAYER\n2\n{name}\n70\n0\n62\n{color}\n6\nCONTINUOUS\n"); + } + out.push_str("0\nENDTAB\n0\nENDSEC\n"); +} + +/// Pages as one DXF drawing, side by side with 20 mm gap. +pub fn pages_dxf(prj: &Project, pages: &[usize]) -> String { + let idx = Index::build(prj); + let an = Analysis::build(prj); + let mut d = DxfDraw { out: String::new(), dx: 0.0 }; + let layers: Vec<(String, u8)> = LAYERS.iter().map(|(n, c)| (n.to_string(), *c)).collect(); + header(&mut d.out, &layers); + d.out.push_str("0\nSECTION\n2\nENTITIES\n"); + for (n, &i) in pages.iter().enumerate() { + d.dx = n as f32 * (PAGE_W + 20.0); + draw_page(&mut d, prj, &idx, &an, i, &Opts::default()); + } + d.out.push_str("0\nENDSEC\n0\nEOF\n"); + d.out +} + +#[cfg(test)] +mod tests; diff --git a/src/dxf/tests.rs b/src/dxf/tests.rs new file mode 100644 index 00000000..02751255 --- /dev/null +++ b/src/dxf/tests.rs @@ -0,0 +1,41 @@ +use super::*; +use crate::sample::demo_project; + +/// (group code, value) pairs of a DXF file. +fn pairs(dxf: &str) -> Vec<(i32, &str)> { + let lines: Vec<&str> = dxf.lines().collect(); + assert_eq!(lines.len() % 2, 0, "odd number of lines"); + lines.chunks(2).map(|c| (c[0].trim().parse().expect("group code"), c[1])).collect() +} + +#[test] +fn page_as_dxf() { + let prj = demo_project(); + let dxf = pages_dxf(&prj, &[1]); + let p = pairs(&dxf); + assert_eq!(p.last(), Some(&(0, "EOF"))); + let count = |kind: &str| p.iter().filter(|x| **x == (0, kind)).count(); + assert_eq!(count("SECTION"), 3); + assert_eq!(count("ENDSEC"), 3); + assert!(count("LINE") > 50); + assert!(count("TEXT") > 20); + assert!(count("CIRCLE") > 0); + assert_eq!(count("POLYLINE"), count("SEQEND")); + // Every entity is on one of our layers. + let layers: Vec<&str> = p.windows(2).filter(|w| w[0].0 == 0 && w[1].0 == 8).map(|w| w[1].1).collect(); + assert!(layers.iter().all(|l| LAYERS.iter().any(|(n, _)| n == l)), "{layers:?}"); + assert!(layers.contains(&"OEC_WIRES") && layers.contains(&"OEC_XREF")); + // Device tags are texts; y is flipped (page top = PAGE_H). + assert!(p.contains(&(1, "-Q1"))); + let frame_top = p.windows(2).any(|w| w[0] == (20, "287.000") || w[1] == (20, "287.000")); + assert!(frame_top); +} + +#[test] +fn pages_side_by_side_and_unicode() { + let prj = demo_project(); + let dxf = pages_dxf(&prj, &[1, 2]); + let max_x = pairs(&dxf).iter().filter(|(c, _)| *c == 10).filter_map(|(_, v)| v.parse::().ok()).fold(0.0, f32::max); + assert!(max_x > PAGE_W + 20.0, "{max_x}"); + assert_eq!(dxf_text("1.5 mm²"), "1.5 mm\\U+00B2"); +} diff --git a/src/editor.rs b/src/editor.rs index 7875e529..d2a9bc1f 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -19,6 +19,8 @@ pub enum Tool { Text, Line, Rect, + /// Place the items of `Editor::insert` (macro). + Insert, } impl Tool { @@ -29,6 +31,7 @@ impl Tool { Tool::Wire => "Click start and corner points · Space toggles corner direction · ends automatically on a connection · Right click / Esc finish", Tool::Text => "Click to place a text", Tool::Line | Tool::Rect => "Click start point, click end point", + Tool::Insert => "Click to insert the macro · Esc cancel", } } } @@ -208,6 +211,9 @@ pub struct Editor { pub hover: Option

, pub status: String, pub center_on: Option

, + /// Items placed with `Tool::Insert`. + pub insert: Option, + pub show_revision_marks: bool, wire_start: Option

, wire_hfirst: bool, shape_start: Option

, @@ -231,6 +237,8 @@ impl Default for Editor { hover: None, status: String::new(), center_on: None, + insert: None, + show_revision_marks: true, wire_start: None, wire_hfirst: true, shape_start: None, @@ -397,7 +405,8 @@ impl Editor { } let page_kind = prj.pages[page_i].kind; - let editable = page_kind == PageKind::Schematic; + let locked = prj.pages[page_i].locked; + let editable = page_kind == PageKind::Schematic && !locked; let ptr = ui.input(|i| i.pointer.hover_pos()).filter(|p| rect.contains(*p)); let world = ptr.map(|s| self.s2w(rect, s)); let snapped = world.map(|w| w.snap(GRID)); @@ -425,7 +434,12 @@ impl Editor { self.draw_grid(&painter, rect, &pal); } - let mut opts = Opts { selected: self.selection.clone(), show_pins: self.show_pins || self.tool == Tool::Wire, ..Default::default() }; + let mut opts = Opts { + selected: self.selection.clone(), + show_pins: self.show_pins || self.tool == Tool::Wire, + hide_revision_marks: !self.show_revision_marks, + ..Default::default() + }; // Highlight the complete potential of a selected wire. if self.selection.len() == 1 { let id = *self.selection.iter().next().unwrap(); @@ -468,6 +482,24 @@ impl Editor { render::draw_shape(&mut g, &s, Ink::Ghost); } } + Tool::Insert => { + if let Some(clip) = &self.insert { + // Same offset as ops::paste + let d = (sn - clip.bounds().min).snap(GRID); + for s in &clip.symbols { + if let Some(def) = symbols::get(&s.sym) { + let inst = SymbolInst { pos: s.pos + d, ..s.clone() }; + render::draw_symbol(&mut g, def, &inst, Ink::Ghost); + } + } + for w in &clip.wires { + g.line(w.a + d, w.b + d, render::WIRE_W, Ink::Ghost, false); + } + for s in &clip.shapes { + render::draw_shape(&mut g, &Shape { a: s.a + d, b: s.b + d, ..s.clone() }, Ink::Ghost); + } + } + } _ => {} } if self.tool != Tool::Select { @@ -485,13 +517,8 @@ impl Editor { } } if !editable { - painter.text( - rect.left_top() + vec2(10.0, 10.0), - Align2::LEFT_TOP, - "Generated page – edit via page properties", - FontId::proportional(13.0), - pal.frame, - ); + let msg = if locked { "Released page – unlock it in Project › Revisions to change it" } else { "Generated page – edit via page properties" }; + painter.text(rect.left_top() + vec2(10.0, 10.0), Align2::LEFT_TOP, msg, FontId::proportional(13.0), pal.frame); } // Status line @@ -533,7 +560,7 @@ impl Editor { } fn keyboard(&mut self, ui: &egui::Ui, prj: &mut Project, page_i: usize, snapped: Option

) { - let editable = prj.pages[page_i].kind == PageKind::Schematic; + let editable = prj.pages[page_i].kind == PageKind::Schematic && !prj.pages[page_i].locked; let (esc, r, m, del, space, fit, all, arrows, events) = ui.input(|i| { let k = |key| i.key_pressed(key) && i.modifiers.is_none(); ( @@ -728,10 +755,18 @@ impl Editor { out.open_properties = true; } } + Tool::Insert => { + let click = resp.clicked_by(PointerButton::Primary).then_some(snapped).flatten(); + if let (Some(sn), Some(clip)) = (click, click.and_then(|_| self.insert.take())) { + let ids = ops::paste(prj, page_i, &clip, sn); + self.set_tool(Tool::Select); + self.selection = ids; + } + } Tool::Place(key) => { if let (true, Some(sn)) = (resp.clicked_by(PointerButton::Primary), snapped) { if let Some(def) = symbols::get(key) { - let s = ops::new_symbol(prj, &self.place_ctx, def, sn, self.place_rot, self.place_mirror); + let s = ops::new_symbol(prj, page_i, &self.place_ctx, def, sn, self.place_rot, self.place_mirror); self.place_ctx.remember(&s); prj.pages[page_i].symbols.push(s); } @@ -799,3 +834,6 @@ pub fn symbol_icon(ui: &mut egui::Ui, key: &str, size: Vec2) -> egui::Response { render::draw_symbol(&mut d, def, &inst, Ink::Line); resp } + +#[cfg(test)] +mod tests; diff --git a/src/editor/tests.rs b/src/editor/tests.rs new file mode 100644 index 00000000..5ad41ff1 --- /dev/null +++ b/src/editor/tests.rs @@ -0,0 +1,70 @@ +use super::*; +use crate::reports::Analysis; +use crate::sample::demo_project; +use egui::{Event, Modifiers, RawInput}; + +/// Runs one editor frame on page `page` with the given input events. +fn frame(ed: &mut Editor, ctx: &egui::Context, prj: &mut Project, page: usize, events: Vec) { + let idx = Index::build(prj); + let an = Analysis::build(prj); + let input = RawInput { + screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + ed.ui(ui, prj, page, &idx, &an); + }); + out.textures_delta.clear(); +} + +fn button(pos: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::default() } +} + +#[test] +fn macro_insertion_waits_for_the_click() { + let mut prj = demo_project(); + let page = 1; + let sel: BTreeSet = prj.pages[page].symbols.iter().filter(|s| s.tag == "-K1").map(|s| s.id).collect(); + let clip = ops::copy(&prj.pages[page], &sel); + let before = prj.pages[page].symbols.len(); + let ctx = egui::Context::default(); + let mut ed = Editor { insert: Some(clip), ..Default::default() }; + ed.set_tool(Tool::Insert); + // Frames without a click keep the macro (regression: it was taken on the first frame). + let at = pos2(600.0, 400.0); + frame(&mut ed, &ctx, &mut prj, page, vec![]); + frame(&mut ed, &ctx, &mut prj, page, vec![Event::PointerMoved(at)]); + assert!(ed.insert.is_some()); + assert_eq!(prj.pages[page].symbols.len(), before); + // A click inserts it once and returns to the select tool. + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, true)]); + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, false)]); + frame(&mut ed, &ctx, &mut prj, page, vec![]); + assert!(ed.insert.is_none()); + assert_eq!(ed.tool, Tool::Select); + assert_eq!(prj.pages[page].symbols.len(), before + sel.len()); + assert_eq!(ed.selection.len(), sel.len()); +} + +#[test] +fn released_pages_are_not_edited() { + let mut prj = demo_project(); + let page = 1; + prj.pages[page].locked = true; + let ctx = egui::Context::default(); + let mut ed = Editor::default(); + ed.set_tool(Tool::Place("coil")); + let before = prj.pages[page].symbols.len(); + let at = pos2(600.0, 400.0); + frame(&mut ed, &ctx, &mut prj, page, vec![Event::PointerMoved(at)]); + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, true)]); + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, false)]); + assert_eq!(prj.pages[page].symbols.len(), before); + // Unlocked, the same click places the coil. + prj.pages[page].locked = false; + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, true)]); + frame(&mut ed, &ctx, &mut prj, page, vec![button(at, false)]); + assert_eq!(prj.pages[page].symbols.len(), before + 1); +} diff --git a/src/forms.rs b/src/forms.rs new file mode 100644 index 00000000..3976e3d7 --- /dev/null +++ b/src/forms.rs @@ -0,0 +1,366 @@ +//! Forms: title blocks and report forms. A title block is a list of lines, +//! rectangles and texts with placeholders (`{project}`, `{page}`, `{sheet}` …) that +//! is drawn into the title block area at the bottom of a page. Companies define their +//! own title blocks and share them as files; report forms choose the columns, their +//! order and the rows per report page. + +use crate::geom::{p, P}; +use crate::model::{PageKind, Project, ReportKind, FRAME_X0, FRAME_X1, FRAME_Y1, TITLE_Y0}; +use crate::render::{Draw, Ink, VAnchor}; +use crate::symbols::Anchor; +use serde::{Deserialize, Serialize}; +use std::borrow::Cow; +use std::collections::BTreeMap; + +/// Size of the title block area (origin at its top left corner). +pub const AREA_W: f32 = FRAME_X1 - FRAME_X0; +pub const AREA_H: f32 = FRAME_Y1 - TITLE_Y0; + +pub const STANDARD: &str = "Standard"; +pub const COMPACT: &str = "Compact"; +pub const NONE: &str = "None"; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum FormItem { + Line { + a: P, + b: P, + width: f32, + }, + Rect { + a: P, + b: P, + width: f32, + #[serde(default)] + fill: bool, + }, + /// Text with placeholders. `label` texts are drawn in the frame colour; + /// `max_width` > 0 shrinks long values to fit. + Text { + pos: P, + text: String, + size: f32, + anchor: Anchor, + #[serde(default)] + label: bool, + #[serde(default)] + max_width: f32, + }, +} + +impl FormItem { + pub fn kind_name(&self) -> &'static str { + match self { + FormItem::Line { .. } => "Line", + FormItem::Rect { .. } => "Rectangle", + FormItem::Text { .. } => "Text", + } + } + + /// Distance from `q` (title block coordinates) for picking in the editor. + pub fn distance(&self, q: P) -> f32 { + match self { + FormItem::Line { a, b, .. } => crate::geom::dist_to_segment(q, *a, *b), + FormItem::Rect { a, b, .. } => { + let c = [*a, p(b.x, a.y), *b, p(a.x, b.y), *a]; + c.windows(2).map(|s| crate::geom::dist_to_segment(q, s[0], s[1])).fold(f32::INFINITY, f32::min) + } + FormItem::Text { pos, text, size, anchor, .. } => { + let w = text_width(text, *size); + let x0 = match anchor { + Anchor::Left => pos.x, + Anchor::Center => pos.x - w / 2.0, + Anchor::Right => pos.x - w, + }; + let dx = (x0 - q.x).max(q.x - (x0 + w)).max(0.0); + let dy = ((q.y - pos.y).abs() - size * 0.6).max(0.0); + (dx * dx + dy * dy).sqrt() + } + } + } + + pub fn translate(&mut self, d: P) { + match self { + FormItem::Line { a, b, .. } | FormItem::Rect { a, b, .. } => { + *a = *a + d; + *b = *b + d; + } + FormItem::Text { pos, .. } => *pos = *pos + d, + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Form { + pub name: String, + pub items: Vec, +} + +/// Layout of a report page. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ReportForm { + /// Heading of the page; empty: the name of the report. + pub title: String, + /// Columns shown, in this order (header names); empty: all columns. + pub columns: Vec, + /// Rows per page; 0: the default. + pub rows: usize, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Forms { + /// Title blocks defined for the project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub title_blocks: Vec

, + /// Title block of pages that do not choose one; empty: the standard one. + #[serde(skip_serializing_if = "String::is_empty")] + pub default_title_block: String, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub reports: BTreeMap, +} + +/// File format for exchanging title blocks. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FormLibrary { + pub title_blocks: Vec, +} + +fn label(items: &mut Vec, x: f32, y: f32, text: &str) { + items.push(FormItem::Text { pos: p(x + 1.0, y + 1.8), text: text.into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }); +} + +fn value(items: &mut Vec, x: f32, y: f32, text: &str, size: f32, max_width: f32) { + items.push(FormItem::Text { pos: p(x + 2.0, y), text: text.into(), size, anchor: Anchor::Left, label: false, max_width }); +} + +fn line(items: &mut Vec, a: P, b: P, width: f32) { + items.push(FormItem::Line { a, b, width }); +} + +/// The built-in title blocks. +pub fn builtin() -> Vec { + let (w, h) = (AREA_W, AREA_H); + let ym = h / 2.0; + let mut std = Vec::new(); + line(&mut std, p(0.0, 0.0), p(w, 0.0), 0.5); + for x in [80.0, 140.0, 200.0, 320.0, 360.0] { + line(&mut std, p(x, 0.0), p(x, h), 0.25); + } + for (x0, x1) in [(80.0, 140.0), (140.0, 200.0), (320.0, 360.0), (360.0, w)] { + line(&mut std, p(x0, ym), p(x1, ym), 0.25); + } + label(&mut std, 0.0, 0.0, "Company"); + value(&mut std, 0.0, ym + 2.0, "{company}", 4.0, 76.0); + label(&mut std, 80.0, 0.0, "Date"); + value(&mut std, 80.0, 9.0, "{date}", 2.5, 56.0); + label(&mut std, 80.0, ym, "Creator"); + value(&mut std, 80.0, ym + 9.0, "{creator}", 2.5, 56.0); + label(&mut std, 140.0, 0.0, "Revision"); + value(&mut std, 140.0, 9.0, "{revision}", 2.5, 56.0); + label(&mut std, 140.0, ym, "Software"); + value(&mut std, 140.0, ym + 9.0, "{software}", 2.5, 56.0); + label(&mut std, 200.0, 0.0, "Project / page description"); + value(&mut std, 200.0, 9.0, "{project}", 3.5, 116.0); + value(&mut std, 200.0, 21.0, "{page.description}", 3.0, 116.0); + label(&mut std, 320.0, 0.0, "Page"); + value(&mut std, 320.0, 9.5, "{page}", 4.0, 36.0); + label(&mut std, 320.0, ym, "Type"); + value(&mut std, 320.0, ym + 9.0, "{page.type}", 2.5, 36.0); + label(&mut std, 360.0, 0.0, "Sheet"); + value(&mut std, 360.0, 9.5, "{sheet} / {sheets}", 3.5, 36.0); + label(&mut std, 360.0, ym, "Project"); + value(&mut std, 360.0, ym + 9.0, "{project}", 2.2, 36.0); + + let mut compact = Vec::new(); + line(&mut compact, p(0.0, 0.0), p(w, 0.0), 0.5); + for x in [120.0, 300.0, 350.0] { + line(&mut compact, p(x, 0.0), p(x, h), 0.25); + } + value(&mut compact, 0.0, 10.0, "{company}", 3.5, 115.0); + value(&mut compact, 0.0, 22.0, "{project}", 3.0, 115.0); + value(&mut compact, 120.0, 10.0, "{page.description}", 3.5, 175.0); + value(&mut compact, 120.0, 22.0, "{page.structure}", 2.5, 175.0); + label(&mut compact, 300.0, 0.0, "Revision / date"); + value(&mut compact, 300.0, 12.0, "{revision}", 3.0, 46.0); + value(&mut compact, 300.0, 22.0, "{date}", 2.2, 46.0); + label(&mut compact, 350.0, 0.0, "Page"); + value(&mut compact, 350.0, 12.0, "{page}", 4.0, 46.0); + value(&mut compact, 350.0, 22.0, "{sheet} / {sheets}", 2.5, 46.0); + + vec![ + Form { name: STANDARD.into(), items: std }, + Form { name: COMPACT.into(), items: compact }, + Form { name: NONE.into(), items: Vec::new() }, + ] +} + +/// Names of all title blocks of a project (custom ones first). +pub fn names(prj: &Project) -> Vec { + let mut v: Vec = prj.forms.title_blocks.iter().map(|f| f.name.clone()).collect(); + for f in builtin() { + if !v.contains(&f.name) { + v.push(f.name); + } + } + v +} + +/// A title block by name: the project's own ones take precedence over the built-in +/// ones; unknown names give the standard title block. +pub fn find<'a>(prj: &'a Project, name: &str) -> Cow<'a, Form> { + if let Some(f) = prj.forms.title_blocks.iter().find(|f| f.name == name) { + return Cow::Borrowed(f); + } + let mut all = builtin(); + let i = all.iter().position(|f| f.name == name).unwrap_or(0); + Cow::Owned(all.swap_remove(i)) +} + +/// Title block used on a page. +pub fn title_block(prj: &Project, page_i: usize) -> Cow<'_, Form> { + let own = &prj.pages[page_i].title_block; + let name = if !own.is_empty() { own } else { &prj.forms.default_title_block }; + find(prj, if name.is_empty() { STANDARD } else { name }) +} + +/// Value of one placeholder (without braces); `None` for unknown names. +pub fn placeholder(prj: &Project, page_i: usize, name: &str) -> Option { + let info = &prj.info; + let page = &prj.pages[page_i]; + let rev = prj.revisions.last(); + let v = match name { + "project" => info.name.clone(), + "project.description" => info.description.lines().collect::>().join(" "), + "company" => info.company.clone(), + "creator" => info.creator.clone(), + "date" => info.date.clone(), + "revision" => info.revision.clone(), + "software" => "OpenECraft".into(), + "page" => crate::structure::page_full_name(page), + "page.name" => page.name.clone(), + "page.description" => page.description.clone(), + "page.structure" => crate::structure::page_structure(page), + "page.function" => page.function.clone(), + "page.location" => page.location.clone(), + "page.type" => match page.kind { + PageKind::Schematic => "Schematic", + PageKind::Cover => "Cover", + PageKind::Report(_) => "Report", + PageKind::Mounting(_) => "Mounting", + } + .into(), + "sheet" => (page_i + 1).to_string(), + "sheets" => prj.pages.len().to_string(), + "rev.name" => rev.map(|r| r.name.clone()).unwrap_or_default(), + "rev.date" => rev.map(|r| r.date.clone()).unwrap_or_default(), + "rev.author" => rev.map(|r| r.author.clone()).unwrap_or_default(), + "rev.description" => rev.map(|r| r.description.clone()).unwrap_or_default(), + _ => info.properties.get(name.strip_prefix("prop:")?).cloned().unwrap_or_default(), + }; + Some(v) +} + +/// Placeholders offered in the title block editor: (placeholder, meaning). +pub const PLACEHOLDERS: [(&str, &str); 22] = [ + ("{project}", "Project name"), + ("{project.description}", "Project description"), + ("{company}", "Company"), + ("{creator}", "Created by"), + ("{date}", "Date"), + ("{revision}", "Project revision"), + ("{software}", "OpenECraft"), + ("{page}", "Full page name (=A1+CAB1/3)"), + ("{page.name}", "Page number"), + ("{page.description}", "Page description"), + ("{page.structure}", "Page structure (=A1+CAB1)"), + ("{page.function}", "Function of the page"), + ("{page.location}", "Location of the page"), + ("{page.type}", "Page type"), + ("{sheet}", "Sheet number"), + ("{sheets}", "Number of sheets"), + ("{rev.name}", "Last revision"), + ("{rev.date}", "Date of the last revision"), + ("{rev.author}", "Author of the last revision"), + ("{rev.description}", "Description of the last revision"), + ("{prop:Name}", "Project property \"Name\""), + ("{{ }}", "Literal braces"), +]; + +/// Replaces the placeholders of a text; unknown ones stay as they are. +pub fn fill(text: &str, prj: &Project, page_i: usize) -> String { + let mut out = String::new(); + let mut i = 0; + while i < text.len() { + let rest = &text[i..]; + if rest.starts_with("{{") || rest.starts_with("}}") { + out.push_str(&rest[..1]); + i += 2; + continue; + } + if let (true, Some(end)) = (rest.starts_with('{'), rest.find('}')) { + match placeholder(prj, page_i, rest[1..end].trim()) { + Some(v) => out.push_str(&v), + None => out.push_str(&rest[..=end]), + } + i += end + 1; + continue; + } + let c = rest.chars().next().unwrap_or(' '); + out.push(c); + i += c.len_utf8(); + } + out +} + +/// Estimated width of a text (same estimate as the canvas hit tests). +pub fn text_width(text: &str, size: f32) -> f32 { + text.chars().count() as f32 * size * 0.62 +} + +/// Draws a title block for a page. +pub fn draw(d: &mut dyn Draw, form: &Form, prj: &Project, page_i: usize) { + let o = p(FRAME_X0, TITLE_Y0); + for item in &form.items { + match item { + FormItem::Line { a, b, width } => d.line(o + *a, o + *b, *width, Ink::Frame, false), + FormItem::Rect { a, b, width, fill } => { + if *fill { + d.rect(o + *a, o + *b, 0.0, Ink::Plate, true); + } + if *width > 0.0 { + d.rect(o + *a, o + *b, *width, Ink::Frame, false); + } + } + FormItem::Text { pos, text, size, anchor, label, max_width } => { + let ink = if *label { Ink::FrameText } else { Ink::Text }; + let value = fill(text, prj, page_i); + for (i, l) in value.lines().enumerate() { + let w = text_width(l, *size); + let size = if *max_width > 0.0 && w > *max_width { (size * max_width / w).max(1.0) } else { *size }; + d.text(o + *pos + p(0.0, i as f32 * size * 1.4), l, size, *anchor, VAnchor::Middle, ink); + } + } + } + } +} + +/// Indices of the report columns shown by a form (all if it chooses none or none +/// of its columns exist). +pub fn report_columns(form: Option<&ReportForm>, headers: &[&str]) -> Vec { + let chosen: Vec = form + .map(|f| f.columns.iter().filter_map(|c| headers.iter().position(|h| h == c)).collect()) + .unwrap_or_default(); + if chosen.is_empty() { + (0..headers.len()).collect() + } else { + chosen + } +} + +#[cfg(test)] +mod tests; diff --git a/src/forms/tests.rs b/src/forms/tests.rs new file mode 100644 index 00000000..ce5e3338 --- /dev/null +++ b/src/forms/tests.rs @@ -0,0 +1,112 @@ +use super::*; +use crate::sample::demo_project; + +#[test] +fn placeholders_are_filled() { + let mut prj = demo_project(); + prj.info.properties.insert("Customer".into(), "ACME".into()); + let n = prj.pages.len(); + assert_eq!(fill("{project} – {sheet}/{sheets}", &prj, 1), format!("Demo conveyor – 2/{n}")); + assert_eq!(fill("Customer: {prop:Customer}", &prj, 0), "Customer: ACME"); + assert_eq!(fill("{prop:Missing}", &prj, 0), ""); + // Unknown placeholders and escaped braces stay readable. + assert_eq!(fill("{nothing} {{x}} {", &prj, 0), "{nothing} {x} {"); + assert_eq!(fill("{page.type}", &prj, 0), "Cover"); + assert_eq!(fill("ä {company} ö", &prj, 0), "ä OpenECraft ö"); +} + +#[test] +fn every_offered_placeholder_is_known() { + let prj = demo_project(); + for (ph, _) in PLACEHOLDERS { + let name = ph.trim_start_matches('{').trim_end_matches('}'); + if name.starts_with('{') || name.trim().is_empty() { + continue; + } + let name = if name.starts_with("prop:") { "prop:Name" } else { name }; + assert!(placeholder(&prj, 0, name).is_some(), "{ph}"); + } +} + +#[test] +fn title_block_choice() { + let mut prj = demo_project(); + assert_eq!(title_block(&prj, 1).name, STANDARD); + let mut own = find(&prj, COMPACT).into_owned(); + own.name = "Company".into(); + prj.forms.title_blocks.push(own); + prj.forms.default_title_block = "Company".into(); + assert_eq!(title_block(&prj, 1).name, "Company"); + prj.pages[1].title_block = NONE.into(); + assert_eq!(title_block(&prj, 1).name, NONE); + assert!(title_block(&prj, 1).items.is_empty()); + // Unknown names fall back to the standard title block. + prj.pages[1].title_block = "Deleted".into(); + assert_eq!(title_block(&prj, 1).name, STANDARD); + assert_eq!(names(&prj), vec!["Company", STANDARD, COMPACT, NONE]); +} + +#[test] +fn title_blocks_are_drawn_with_page_values() { + let mut prj = demo_project(); + let svg = crate::svg::page_svg(&prj, 1); + assert!(svg.contains("Demo conveyor")); + assert!(svg.contains(&format!("2 / {}", prj.pages.len()))); + // A custom title block with a project property. + prj.info.properties.insert("Order".into(), "4711-XY".into()); + let item = FormItem::Text { pos: p(10.0, 10.0), text: "Order {prop:Order}".into(), size: 3.0, anchor: Anchor::Left, label: false, max_width: 0.0 }; + prj.forms.title_blocks.push(Form { name: "Mine".into(), items: vec![item] }); + prj.pages[1].title_block = "Mine".into(); + let svg = crate::svg::page_svg(&prj, 1); + assert!(svg.contains("Order 4711-XY")); + assert!(!svg.contains("Demo conveyor"), "standard title block is not drawn"); +} + +#[test] +fn long_values_shrink_to_their_width() { + struct Sizes(Vec); + impl Draw for Sizes { + fn line(&mut self, _: P, _: P, _: f32, _: Ink, _: bool) {} + fn poly(&mut self, _: &[P], _: bool, _: f32, _: Ink, _: bool) {} + fn circle(&mut self, _: P, _: f32, _: f32, _: Ink, _: bool) {} + fn text(&mut self, _: P, _: &str, size: f32, _: Anchor, _: VAnchor, _: Ink) { + self.0.push(size); + } + } + let mut prj = demo_project(); + prj.info.name = "A very long project name".into(); + let item = FormItem::Text { pos: p(0.0, 0.0), text: "{project}".into(), size: 4.0, anchor: Anchor::Left, label: false, max_width: 20.0 }; + let mut d = Sizes(Vec::new()); + draw(&mut d, &Form { name: "x".into(), items: vec![item] }, &prj, 0); + assert!(d.0[0] < 4.0); + assert!(text_width(&prj.info.name, d.0[0]) <= 20.01); +} + +#[test] +fn report_columns_follow_the_form() { + let headers = ["Tag", "Name", "Part"]; + assert_eq!(report_columns(None, &headers), vec![0, 1, 2]); + let f = ReportForm { columns: vec!["Part".into(), "Unknown".into(), "Tag".into()], ..Default::default() }; + assert_eq!(report_columns(Some(&f), &headers), vec![2, 0]); + let f = ReportForm { columns: vec!["Unknown".into()], ..Default::default() }; + assert_eq!(report_columns(Some(&f), &headers), vec![0, 1, 2]); +} + +#[test] +fn report_pages_use_their_form() { + let mut prj = demo_project(); + let id = prj.new_id(); + prj.pages.push(crate::model::Page::new(id, "99", "Devices", PageKind::Report(ReportKind::DeviceList))); + let page = prj.pages.len() - 1; + let form = ReportForm { title: "Our device list".into(), columns: vec!["Part number".into(), "Device tag".into()], rows: 10 }; + prj.forms.reports.insert(ReportKind::DeviceList, form); + let svg = crate::svg::page_svg(&prj, page); + assert!(svg.contains("Our device list")); + let (part, tag) = (svg.find(">Part number<").unwrap(), svg.find(">Device tag<").unwrap()); + assert!(part < tag, "columns in the order of the form"); + assert!(!svg.contains(">Function text<")); + // The forms are saved with the project (report kinds as keys). + let json = serde_json::to_string(&prj).unwrap(); + let back: Project = serde_json::from_str(&json).unwrap(); + assert_eq!(back.forms, prj.forms); +} diff --git a/src/harness.rs b/src/harness.rs new file mode 100644 index 00000000..bdd6ab00 --- /dev/null +++ b/src/harness.rs @@ -0,0 +1,271 @@ +//! Wire harnesses: connections (point-to-point, identified by their two connection +//! point designations) assigned to a harness are made as one assembly. The harness data lists its wires with lengths and end treatment, its +//! connectors (device ends with their pin assignment) and the bundle diameter, and +//! is exported as a simplified KBL file (VDA 4964) for harness manufacturing. + +use crate::model::{natural_cmp, Project}; +use crate::netlist::{pin_designation, PinRef}; +use crate::reports::Analysis; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; +use std::fmt::Write; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Harness { + pub id: u64, + /// Complete device tag, e.g. `=A1-WH1`. + pub tag: String, + pub description: String, + /// Length in metres of wires that are not routed in the panel layout (field + /// wiring); 0 = unknown. + pub length: f32, + /// Part number of the finished harness (bill of materials). + pub part: String, + /// Connections of the harness: both ends as connection point designations + /// (`-S1:13`), in [`key`] order. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub connections: Vec<[String; 2]>, +} + +/// Order independent key of a connection. +pub fn key(a: &str, b: &str) -> [String; 2] { + if natural_cmp(a, b) == std::cmp::Ordering::Greater { [b.into(), a.into()] } else { [a.into(), b.into()] } +} + +/// Harness of the connection between two connection points (empty: none). +pub fn of(prj: &Project, a: &str, b: &str) -> String { + let k = key(a, b); + prj.harnesses.iter().find(|h| h.connections.contains(&k)).map(|h| h.tag.clone()).unwrap_or_default() +} + +/// Assigns a connection to a harness (empty: to none). +pub fn assign(prj: &mut Project, a: &str, b: &str, tag: &str) { + let k = key(a, b); + for h in &mut prj.harnesses { + h.connections.retain(|c| *c != k); + } + if let Some(h) = prj.harnesses.iter_mut().find(|h| h.tag == tag) { + h.connections.push(k); + } +} + +/// Keeps the assignments when a device is renamed. +pub fn rename_device(prj: &mut Project, old: &str, new: &str) { + for h in &mut prj.harnesses { + for c in &mut h.connections { + for end in c.iter_mut() { + if end == old { + *end = new.to_string(); + } else if let Some(pin) = end.strip_prefix(old).and_then(|r| r.strip_prefix(':')) { + *end = format!("{new}:{pin}"); + } + } + *c = key(&c[0], &c[1]); + } + } +} + +/// Assigned connections that do not exist in the schematic (any more): (harness, ends). +pub fn stale(prj: &Project, an: &Analysis) -> Vec<(String, [String; 2])> { + let existing: Vec<[String; 2]> = an.connections.iter().map(|c| key(&pin_designation(prj, c.a), &pin_designation(prj, c.b))).collect(); + prj.harnesses + .iter() + .flat_map(|h| h.connections.iter().filter(|c| !existing.contains(c)).map(|c| (h.tag.clone(), c.clone()))) + .collect() +} + +/// Connections (indices into `an.connections`) whose two ends both lie on end +/// points of the given wires of a page: selecting the wires between two devices +/// selects their connection. +pub fn connections_at(prj: &Project, an: &Analysis, page: usize, wires: &BTreeSet) -> Vec { + let ends: Vec = prj.pages[page].wires.iter().filter(|w| wires.contains(&w.id)).flat_map(|w| [w.a, w.b]).collect(); + let pos = |pin: PinRef| { + let s = &prj.pages[pin.page].symbols[pin.sym]; + crate::symbols::get(&s.sym).map(|d| d.pin_world(pin.pin, s.pos, s.rot, s.mirror)) + }; + let touched = |pin: PinRef| pin.page == page && pos(pin).map(|q| ends.iter().any(|e| e.same(q))).unwrap_or(false); + (0..an.connections.len()).filter(|&i| touched(an.connections[i].a) && touched(an.connections[i].b)).collect() +} + +/// Connections of the net a wire belongs to (indices into `an.connections`). +pub fn connections_of_wire(an: &Analysis, wire: u64) -> Vec { + let Some(net) = an.open.wire_net.get(&wire).map(|&n| &an.open.nets[n]) else { return Vec::new() }; + (0..an.connections.len()).filter(|&i| net.pins.contains(&an.connections[i].a) && net.pins.contains(&an.connections[i].b)).collect() +} + +/// One wire of a harness. +#[derive(Clone, Debug, PartialEq)] +pub struct HarnessWire { + pub number: String, + /// Device tag and connection point of both ends. + pub from: (String, String), + pub to: (String, String), + pub color: String, + pub cross_section: String, + /// Length in mm (routed in the panel layout, or the harness length); 0 = unknown. + pub length: f32, + pub routed: bool, + pub target: Option<(usize, u64)>, +} + +/// A device end of a harness with its pin assignment: (pin, wire number, other end). +#[derive(Clone, Debug, PartialEq)] +pub struct Connector { + pub device: String, + pub pins: Vec<(String, String, String)>, +} + +fn end(prj: &Project, pin: PinRef) -> (String, String) { + let tag = prj.pages[pin.page].symbols[pin.sym].tag.clone(); + let d = pin_designation(prj, pin); + let pin_name = d.strip_prefix(tag.as_str()).unwrap_or(&d).trim_start_matches(':').to_string(); + (tag, pin_name) +} + +fn joined(e: &(String, String)) -> String { + if e.1.is_empty() { e.0.clone() } else { format!("{}:{}", e.0, e.1) } +} + +/// Wires of a harness, in wire number order. +pub fn wires(prj: &Project, an: &Analysis, tag: &str) -> Vec { + let default = prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.length * 1000.0).unwrap_or(0.0); + let mut v: Vec = an + .connections + .iter() + .filter(|c| c.harness == tag) + .map(|c| { + let (from, to) = (end(prj, c.a), end(prj, c.b)); + let (fa, fb) = (pin_designation(prj, c.a), pin_designation(prj, c.b)); + let routed = an.wiring.iter().find(|w| (w.from == fa && w.to == fb) || (w.from == fb && w.to == fa)).map(|w| w.length); + HarnessWire { + number: c.number.clone(), + from, + to, + color: c.color.clone(), + cross_section: c.cross_section.clone(), + length: routed.unwrap_or(default), + routed: routed.is_some(), + target: Some((c.a.page, prj.pages[c.a.page].symbols[c.a.sym].id)), + } + }) + .collect(); + v.sort_by(|a, b| natural_cmp(&a.number, &b.number).then(natural_cmp(&joined(&a.from), &joined(&b.from)))); + v +} + +/// Device ends of the wires with their pin assignment. +pub fn connectors(wires: &[HarnessWire]) -> Vec { + let mut v: Vec = Vec::new(); + let mut add = |dev: &str, pin: &str, number: &str, other: &(String, String)| { + let entry = (pin.to_string(), number.to_string(), joined(other)); + match v.iter_mut().find(|c| c.device == dev) { + Some(c) => c.pins.push(entry), + None => v.push(Connector { device: dev.to_string(), pins: vec![entry] }), + } + }; + for w in wires { + add(&w.from.0, &w.from.1, &w.number, &w.to); + add(&w.to.0, &w.to.1, &w.number, &w.from); + } + for c in &mut v { + c.pins.sort_by(|a, b| natural_cmp(&a.0, &b.0)); + } + v.sort_by(|a, b| natural_cmp(&a.device, &b.device)); + v +} + +/// Outer diameter of a single core wire (PVC insulated, H05V-K / H07V-K like). +pub fn outer_diameter(cross_section: &str) -> f32 { + let cs = crate::production::cross_section_mm2(cross_section).unwrap_or(1.0); + 1.0 + 1.6 * cs.sqrt() +} + +/// Diameter of the bundle (wires packed round, 15 % gaps). +pub fn bundle_diameter(wires: &[HarnessWire]) -> f32 { + let sum: f32 = wires.iter().map(|w| outer_diameter(&w.cross_section).powi(2)).sum(); + sum.sqrt() * 1.15 +} + +fn xml(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// Harness data as simplified KBL (VDA 4964): general wires (cross-section and +/// colour), and per harness its connector occurrences with contact points, wire +/// occurrences with lengths and the connections between contact points. +pub fn kbl(prj: &Project, an: &Analysis) -> String { + let mut out = String::from("\n"); + out.push_str("\n"); + out.push_str("\n"); + let all: Vec<(String, Vec)> = prj.harnesses.iter().map(|h| (h.tag.clone(), wires(prj, an, &h.tag))).collect(); + // General wires: one per cross-section and colour. + let mut general: Vec<(String, String)> = Vec::new(); + for w in all.iter().flat_map(|(_, ws)| ws) { + let key = (w.cross_section.clone(), w.color.clone()); + if !general.contains(&key) { + general.push(key); + } + } + let gw_id = |cs: &str, color: &str| general.iter().position(|g| g.0 == cs && g.1 == color).map(|i| format!("GW{}", i + 1)).unwrap_or_default(); + for (i, (cs, color)) in general.iter().enumerate() { + let area = crate::production::cross_section_mm2(cs).map(|v| v.to_string()).unwrap_or_default(); + let _ = writeln!( + out, + " {} {}{area}mm2{}{:.2}mm", + i + 1, + xml(cs), + xml(color), + xml(color), + outer_diameter(cs) + ); + } + for (hi, h) in prj.harnesses.iter().enumerate() { + let ws = &all[hi].1; + let _ = writeln!(out, " {}{}", hi + 1, xml(if h.part.is_empty() { &h.tag } else { &h.part }), xml(&h.description)); + let _ = writeln!(out, " {}", xml(&h.tag)); + let cons = connectors(ws); + let cp_id = |dev: &str, pin: &str| -> String { + let ci = cons.iter().position(|c| c.device == dev).unwrap_or(0); + let pi = cons.get(ci).and_then(|c| c.pins.iter().position(|p| p.0 == pin)).unwrap_or(0); + format!("H{}_C{}_P{}", hi + 1, ci + 1, pi + 1) + }; + for (ci, c) in cons.iter().enumerate() { + let _ = write!(out, " {}", hi + 1, ci + 1, xml(&c.device)); + let mut seen: Vec<&str> = Vec::new(); + for (pi, pin) in c.pins.iter().enumerate() { + if seen.contains(&pin.0.as_str()) { + continue; + } + seen.push(&pin.0); + let _ = write!(out, "{}", hi + 1, ci + 1, pi + 1, xml(&pin.0)); + } + out.push_str("\n"); + } + for (wi, w) in ws.iter().enumerate() { + let id = format!("H{}_W{}", hi + 1, wi + 1); + let _ = writeln!( + out, + " {}{}{}{:.0}mm", + gw_id(&w.cross_section, &w.color), + xml(&w.number), + if w.routed { "DMA" } else { "Nominal" }, + w.length + ); + let _ = writeln!( + out, + " {id}0{}1{}", + hi + 1, + wi + 1, + cp_id(&w.from.0, &w.from.1), + cp_id(&w.to.0, &w.to.1) + ); + } + out.push_str(" \n"); + } + out.push_str("\n"); + out +} + +#[cfg(test)] +mod tests; diff --git a/src/harness/tests.rs b/src/harness/tests.rs new file mode 100644 index 00000000..aa691fa4 --- /dev/null +++ b/src/harness/tests.rs @@ -0,0 +1,115 @@ +use super::*; +use crate::sample::demo_project; + +#[test] +fn door_harness_of_the_demo() { + let prj = demo_project(); + let an = Analysis::build(&prj); + let ws = wires(&prj, &an, "-WH1"); + assert!(!ws.is_empty()); + // Every wire has a door device at least on one connection of its potential, and + // all of them have a length (routed in the panel or the harness length). + assert!(ws.iter().all(|w| w.length > 0.0)); + assert!(ws.iter().any(|w| w.routed)); + let cons = connectors(&ws); + assert!(cons.iter().any(|c| c.device == "-S1")); + // Each wire appears at both of its ends. + assert_eq!(cons.iter().map(|c| c.pins.len()).sum::(), 2 * ws.len()); + let d = bundle_diameter(&ws); + assert!(d > outer_diameter("1.5 mm²") && d < 50.0); + // Report and check. + let t = &an.reports[&crate::model::ReportKind::HarnessData]; + assert_eq!(t.rows.len(), ws.len() + 1); + assert!(!an.issues.iter().any(|i| i.message.contains("harness"))); +} + +#[test] +fn wire_diameters() { + assert!((outer_diameter("1.5 mm²") - 2.96).abs() < 0.01); + assert!(outer_diameter("2.5") > outer_diameter("0.75")); +} + +#[test] +fn only_the_assigned_connections_belong_to_the_harness() { + let prj = demo_project(); + let an = Analysis::build(&prj); + let door = ["-S1", "-S2", "-S3", "-S4", "-P1", "-P2"]; + let ws = wires(&prj, &an, "-WH1"); + // Every harness wire has a door device at one end ... + assert!(ws.iter().all(|w| door.contains(&w.from.0.as_str()) || door.contains(&w.to.0.as_str()))); + // ... while other connections of the same potential sections stay outside. + let section_mates = an + .connections + .iter() + .filter(|c| c.harness.is_empty()) + .filter(|c| an.connections.iter().any(|d| d.harness == "-WH1" && (d.a == c.a || d.b == c.a || d.a == c.b || d.b == c.b))) + .count(); + assert!(section_mates > 0, "the demo has connections next to harness wires that are not in the harness"); +} + +#[test] +fn assignment_by_selected_wires() { + let mut prj = demo_project(); + for h in &mut prj.harnesses { + h.connections.clear(); + } + let an = Analysis::build(&prj); + // The wires of one connection that lies on a single page. + let ci = an.connections.iter().position(|c| c.a.page == c.b.page).unwrap(); + let c = an.connections[ci].clone(); + let page = c.a.page; + let sel: BTreeSet = prj.pages[page].wires.iter().map(|w| w.id).collect(); + let found = connections_at(&prj, &an, page, &sel); + assert!(found.contains(&ci)); + // No wires selected: no connection. + assert!(connections_at(&prj, &an, page, &BTreeSet::new()).is_empty()); + let (a, b) = (pin_designation(&prj, c.a), pin_designation(&prj, c.b)); + assign(&mut prj, &a, &b, "-WH1"); + assert_eq!(of(&prj, &b, &a), "-WH1"); + let an = Analysis::build(&prj); + assert_eq!(an.connections.iter().filter(|c| c.harness == "-WH1").count(), 1); + // The connections of a wire: those of its potential section. + let wire = prj.pages[page].wires[0].id; + assert!(!connections_of_wire(&an, wire).is_empty()); + assign(&mut prj, &a, &b, ""); + assert_eq!(of(&prj, &a, &b), ""); +} + +#[test] +fn renamed_devices_keep_and_stale_assignments_are_reported() { + let mut prj = demo_project(); + let before = wires(&prj, &Analysis::build(&prj), "-WH1").len(); + crate::ops::rename_device(&mut prj, "-S1", "-S11"); + let an = Analysis::build(&prj); + assert_eq!(wires(&prj, &an, "-WH1").len(), before); + assert!(stale(&prj, &an).is_empty()); + // An assignment of a connection that does not exist. + prj.harnesses[0].connections.push(key("-X9:1", "-K9:A1")); + let an = Analysis::build(&prj); + assert_eq!(stale(&prj, &an), vec![("-WH1".to_string(), key("-K9:A1", "-X9:1"))]); + assert!(an.issues.iter().any(|i| i.message.contains("-K9:A1 – -X9:1 does not exist"))); + // A harness without connections. + prj.harnesses.push(Harness { id: 999, tag: "-WH2".into(), ..Default::default() }); + let an = Analysis::build(&prj); + assert!(an.issues.iter().any(|i| i.message == "Harness -WH2 has no wires")); +} + +#[test] +fn kbl_export() { + let prj = demo_project(); + let an = Analysis::build(&prj); + let ws = wires(&prj, &an, "-WH1"); + let x = kbl(&prj, &an); + assert!(x.starts_with("-WH1")); + assert_eq!(x.matches("").skip(1) { + let id = &cap[..cap.find('<').unwrap()]; + assert!(x.contains(&format!("")), "{id}"); + } + assert_eq!(x.matches("").count()); + assert_eq!(xml("a String { - format!("/{}.{}", prj.pages[self.page].name, column_of(self.pos)) + let page = &prj.pages[self.page]; + format!("{}/{}.{}", structure::page_structure(page), page.name, column_of(self.pos)) + } + + /// Cross reference as shown on page `from`: the structure is left out if both + /// pages have the same. + pub fn reference_from(&self, prj: &Project, from: usize) -> String { + let (page, here) = (&prj.pages[self.page], &prj.pages[from]); + if structure::page_structure(page) == structure::page_structure(here) { + format!("/{}.{}", page.name, column_of(self.pos)) + } else { + self.reference(prj) + } } } @@ -24,6 +38,8 @@ pub struct DeviceEntry { pub auxs: Vec, /// Terminals, PLC points (no main / aux relation). pub others: Vec, + /// Single-line / overview representations. + pub overviews: Vec, } #[derive(Default)] @@ -49,6 +65,7 @@ impl Index { Func::Main { .. } => idx.devices.entry(s.tag.clone()).or_default().mains.push(loc), Func::Aux(_) => idx.devices.entry(s.tag.clone()).or_default().auxs.push(loc), Func::Terminal | Func::Plc => idx.devices.entry(s.tag.clone()).or_default().others.push(loc), + Func::Overview => idx.devices.entry(s.tag.clone()).or_default().overviews.push(loc), } } } diff --git a/src/io.rs b/src/io.rs index 141d8f99..d5e0749a 100644 --- a/src/io.rs +++ b/src/io.rs @@ -13,6 +13,14 @@ pub enum Purpose { Parts, /// 2D / 3D model of a part. Model(ModelKind), + /// Macro library (JSON) to merge. + Macros, + /// PLC symbol table (CSV). + PlcTable, + /// Symbol library (JSON) to merge into the project. + Symbols, + /// Title blocks (JSON) to add to the project. + Forms, } impl FileKind for Purpose { @@ -21,6 +29,10 @@ impl FileKind for Purpose { Purpose::Project => ("OpenECraft project", &[PROJECT_EXT, "json"]), Purpose::Parts => ("Parts (CSV, JSON)", &["csv", "json", "txt"]), Purpose::Model(kind) => kind.filter(), + Purpose::Macros => ("OpenECraft macros (JSON)", &["json"]), + Purpose::PlcTable => ("PLC symbol table (CSV)", &["csv", "txt"]), + Purpose::Symbols => ("OpenECraft symbol library (JSON)", &["json"]), + Purpose::Forms => ("OpenECraft title blocks (JSON)", &["json"]), } } } diff --git a/src/macros.rs b/src/macros.rs new file mode 100644 index 00000000..e262158c --- /dev/null +++ b/src/macros.rs @@ -0,0 +1,168 @@ +//! Macros: reusable circuit parts. A window macro is a selection of a page, a page +//! macro a complete page. Placeholders `{NAME}` in tags, texts, function texts, +//! designations and connection points are filled from value sets when inserting. + +use crate::model::*; +use crate::ops::{self, Clip}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum MacroKind { + #[default] + Window, + Page, +} + +/// Named values for the placeholders of a macro (e.g. "Pump 1.5 kW"). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ValueSet { + pub name: String, + pub values: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Macro { + pub name: String, + pub category: String, + pub description: String, + pub kind: MacroKind, + pub clip: Clip, + /// Page macros: description of the inserted page. + pub page_description: String, + pub value_sets: Vec, +} + +/// The macro library (stored with the application, like the parts database). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct MacroLibrary { + pub macros: Vec, +} + +impl MacroLibrary { + /// Adds a macro or replaces the one with the same name. + pub fn upsert(&mut self, m: Macro) { + match self.macros.iter_mut().find(|x| x.name == m.name) { + Some(x) => *x = m, + None => self.macros.push(m), + } + self.macros.sort_by(|a, b| natural_cmp(&a.category, &b.category).then_with(|| natural_cmp(&a.name, &b.name))); + } + + /// Adds the macros of another library (same names are replaced). Returns the count. + pub fn merge(&mut self, other: MacroLibrary) -> usize { + let n = other.macros.len(); + for m in other.macros { + self.upsert(m); + } + n + } +} + +fn scan(s: &str, out: &mut BTreeSet) { + let mut rest = s; + while let Some(start) = rest.find('{') { + let after = &rest[start + 1..]; + match after.find('}') { + Some(end) if end > 0 && after[..end].chars().all(|c| c.is_alphanumeric() || c == '_' || c == ' ' || c == '.') => { + out.insert(after[..end].to_string()); + rest = &after[end + 1..]; + } + _ => rest = after, + } + } +} + +fn fill(s: &str, values: &BTreeMap) -> String { + let mut out = s.to_string(); + for (k, v) in values { + out = out.replace(&format!("{{{k}}}"), v); + } + out +} + +/// Every text of a clip that may hold placeholders. +fn texts_mut(clip: &mut Clip) -> Vec<&mut String> { + let mut v: Vec<&mut String> = Vec::new(); + for s in &mut clip.symbols { + v.push(&mut s.tag); + v.push(&mut s.label); + v.push(&mut s.function_text); + v.extend(s.pins.iter_mut()); + } + for w in &mut clip.wires { + v.push(&mut w.color); + v.push(&mut w.cross_section); + } + v.extend(clip.texts.iter_mut().map(|t| &mut t.text)); + v +} + +impl Macro { + /// Placeholders used in the macro, sorted. + pub fn placeholders(&self) -> Vec { + let mut clip = self.clip.clone(); + let mut set = BTreeSet::new(); + for t in texts_mut(&mut clip) { + scan(t, &mut set); + } + scan(&self.page_description, &mut set); + set.into_iter().collect() + } + + /// The macro's items with the placeholders filled in (unknown ones stay). + pub fn resolve(&self, values: &BTreeMap) -> Clip { + let mut clip = self.clip.clone(); + for t in texts_mut(&mut clip) { + *t = fill(t, values); + } + clip + } + + /// Number of symbols / wires / texts and graphics. + pub fn summary(&self) -> String { + let c = &self.clip; + format!("{} symbols, {} wires, {} texts / graphics", c.symbols.len(), c.wires.len(), c.texts.len() + c.shapes.len()) + } +} + +/// Window macro from the selected items of a page. +pub fn from_selection(page: &Page, sel: &BTreeSet, name: &str) -> Macro { + Macro { name: name.into(), kind: MacroKind::Window, clip: ops::copy(page, sel), ..Default::default() } +} + +/// Page macro from a complete page. +pub fn from_page(page: &Page, name: &str) -> Macro { + let all = ops::all_ids(page).into_iter().collect(); + Macro { + name: name.into(), + kind: MacroKind::Page, + clip: ops::copy(page, &all), + page_description: page.description.clone(), + description: page.description.clone(), + ..Default::default() + } +} + +/// Inserts a page macro as a new schematic page after page `after`, in the structure +/// of the macro's page. Returns the index of the new page. +pub fn insert_page(prj: &mut Project, after: usize, m: &Macro, values: &BTreeMap) -> usize { + let clip = m.resolve(values); + let name = (prj.pages.iter().filter_map(|p| p.name.parse::().ok()).max().unwrap_or(0) + 1).to_string(); + let id = prj.new_id(); + let mut page = Page::new(id, &name, &fill(&m.page_description, values), PageKind::Schematic); + page.function = clip.function.clone(); + page.location = clip.location.clone(); + let at = (after + 1).min(prj.pages.len()); + prj.pages.insert(at, page); + // Items keep their position on the page. + let origin = clip.bounds().min; + ops::paste(prj, at, &clip, origin); + at +} + +#[cfg(test)] +mod tests; diff --git a/src/macros/tests.rs b/src/macros/tests.rs new file mode 100644 index 00000000..9022ce41 --- /dev/null +++ b/src/macros/tests.rs @@ -0,0 +1,76 @@ +use super::*; +use crate::geom::p; +use crate::sample::demo_project; + +/// Window macro of the motor feeder on page 2 with placeholders. +fn motor_macro(prj: &Project) -> Macro { + let page = &prj.pages[1]; + let sel: BTreeSet = page.symbols.iter().filter(|s| ["-Q1", "-K1", "-M1"].contains(&s.tag.as_str())).map(|s| s.id).collect(); + let mut m = from_selection(page, &sel, "DOL starter"); + for s in &mut m.clip.symbols { + if s.tag == "-M1" { + s.function_text = "{MOTOR}\n{POWER}".into(); + } + } + m.value_sets.push(ValueSet { name: "Pump".into(), values: BTreeMap::from([("MOTOR".into(), "Pump".into()), ("POWER".into(), "1.5 kW".into())]) }); + m +} + +#[test] +fn placeholders_are_found_and_filled() { + let prj = demo_project(); + let m = motor_macro(&prj); + assert_eq!(m.placeholders(), vec!["MOTOR".to_string(), "POWER".to_string()]); + let clip = m.resolve(&m.value_sets[0].values); + let motor = clip.symbols.iter().find(|s| s.tag == "-M1").unwrap(); + assert_eq!(motor.function_text, "Pump\n1.5 kW"); + // Unknown placeholders stay; braces without a name are not placeholders. + let mut set = BTreeSet::new(); + scan("{A} {} {not valid!} {B_2}", &mut set); + assert_eq!(set.into_iter().collect::>(), ["A", "B_2"]); + assert_eq!(fill("{A}-{C}", &BTreeMap::from([("A".into(), "x".into())])), "x-{C}"); +} + +#[test] +fn inserted_window_macros_get_new_tags() { + let mut prj = demo_project(); + let m = motor_macro(&prj); + let clip = m.resolve(&m.value_sets[0].values); + let ids = ops::paste(&mut prj, 1, &clip, p(240.0, 150.0)); + let tags: BTreeSet = prj.pages[1].symbols.iter().filter(|s| ids.contains(&s.id)).map(|s| s.tag.clone()).collect(); + assert_eq!(tags, BTreeSet::from(["-K2".to_string(), "-M2".to_string(), "-Q2".to_string()])); +} + +#[test] +fn page_macros_create_a_page() { + let mut prj = demo_project(); + prj.pages[2].function = "CONV".into(); + let mut m = from_page(&prj.pages[2], "Control circuit"); + m.page_description = "Control {NAME}".into(); + assert_eq!(m.kind, MacroKind::Page); + let pages = prj.pages.len(); + let at = insert_page(&mut prj, 3, &m, &BTreeMap::from([("NAME".into(), "pump".into())])); + assert_eq!((at, prj.pages.len()), (4, pages + 1)); + let new = &prj.pages[at]; + assert_eq!((new.description.as_str(), new.function.as_str(), new.name.as_str()), ("Control pump", "CONV", "9")); + assert_eq!(new.symbols.len(), prj.pages[2].symbols.len()); + // Same positions as on the source page. + let pos = |pg: &Page| pg.symbols.iter().map(|s| (s.pos.x as i32, s.pos.y as i32)).collect::>(); + assert_eq!(pos(new), pos(&prj.pages[2])); +} + +#[test] +fn library_upsert_and_merge() { + let prj = demo_project(); + let mut lib = MacroLibrary::default(); + lib.upsert(motor_macro(&prj)); + let mut changed = motor_macro(&prj); + changed.description = "new".into(); + lib.upsert(changed); + assert_eq!(lib.macros.len(), 1); + assert_eq!(lib.macros[0].description, "new"); + let other = MacroLibrary { macros: vec![from_page(&prj.pages[3], "PLC page")] }; + assert_eq!(lib.merge(other), 1); + let json = serde_json::to_string(&lib).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), lib); +} diff --git a/src/main.rs b/src/main.rs index 62d1199a..681870ef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,13 +8,17 @@ mod app; #[cfg(test)] mod conventions; +mod dxf; mod editor; +mod forms; mod geom; #[cfg(test)] mod glyphs; +mod harness; mod history; mod index; mod io; +mod macros; mod model; mod netlist; mod ops; @@ -22,11 +26,19 @@ mod panel; mod panel_ui; mod parts; mod parts_ui; +mod pdf; +mod plc; +mod production; mod render; mod reports; +mod revision; mod sample; +mod strips; +mod structure; mod svg; mod symbols; +mod symlib; +mod wirenum; #[cfg(not(target_arch = "wasm32"))] fn main() -> eframe::Result { diff --git a/src/model.rs b/src/model.rs index dbf9b9bf..3348bd5a 100644 --- a/src/model.rs +++ b/src/model.rs @@ -56,6 +56,25 @@ pub struct Project { pub devices: BTreeMap, /// Panel layout (enclosures, mounting plates, rails, ducts, devices). pub layout: Layout, + pub cables: Vec, + pub wire_numbering: WireNumbering, + /// Terminal strip data (order, jumpers, spare terminals) keyed by strip tag. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub strips: BTreeMap, + /// PLC card data (start address, rack / slot) keyed by card tag. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub plc_cards: BTreeMap, + /// Released revisions, oldest first. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub revisions: Vec, + /// Wire harnesses with the connections they contain. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub harnesses: Vec, + /// Project symbol library (user symbols). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub symbols: Vec, + /// Title blocks and report forms. + pub forms: crate::forms::Forms, pub next_id: u64, } @@ -67,6 +86,14 @@ impl Default for Project { parts: Vec::new(), devices: BTreeMap::new(), layout: Layout::default(), + cables: Vec::new(), + wire_numbering: WireNumbering::default(), + strips: BTreeMap::new(), + plc_cards: BTreeMap::new(), + revisions: Vec::new(), + harnesses: Vec::new(), + symbols: Vec::new(), + forms: Default::default(), next_id: 1, }; let id = prj.new_id(); @@ -84,6 +111,9 @@ pub struct ProjectInfo { pub creator: String, pub date: String, pub revision: String, + /// User defined project properties, shown in title blocks as `{prop:Name}`. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub properties: BTreeMap, } impl Default for ProjectInfo { @@ -95,6 +125,7 @@ impl Default for ProjectInfo { creator: String::new(), date: String::new(), revision: "A".into(), + properties: BTreeMap::new(), } } } @@ -129,10 +160,14 @@ pub enum ReportKind { PlcAssignment, PotentialList, PanelWiring, + CableOverview, + CableDiagram, + RevisionOverview, + HarnessData, } impl ReportKind { - pub const ALL: [ReportKind; 8] = [ + pub const ALL: [ReportKind; 12] = [ ReportKind::TableOfContents, ReportKind::DeviceList, ReportKind::BillOfMaterials, @@ -141,6 +176,10 @@ impl ReportKind { ReportKind::PlcAssignment, ReportKind::PotentialList, ReportKind::PanelWiring, + ReportKind::CableOverview, + ReportKind::CableDiagram, + ReportKind::RevisionOverview, + ReportKind::HarnessData, ]; pub fn title(self) -> &'static str { @@ -153,6 +192,10 @@ impl ReportKind { ReportKind::PlcAssignment => "PLC assignment list", ReportKind::PotentialList => "Potential overview", ReportKind::PanelWiring => "Wire list (panel routing)", + ReportKind::CableOverview => "Cable overview", + ReportKind::CableDiagram => "Cable diagram", + ReportKind::RevisionOverview => "Revision overview (changes)", + ReportKind::HarnessData => "Harness data", } } } @@ -164,6 +207,16 @@ pub struct Page { /// Page number / name as shown in cross references, e.g. "3". pub name: String, pub description: String, + /// Structure of the page (IEC 81346) without prefix signs: function (`=`) and + /// location (`+`). Devices placed on the page inherit it. + pub function: String, + pub location: String, + /// Released page: no changes until it is unlocked. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub locked: bool, + /// Title block of this page; empty = the project's default. + #[serde(skip_serializing_if = "String::is_empty")] + pub title_block: String, pub kind: PageKind, pub symbols: Vec, pub wires: Vec, @@ -183,6 +236,10 @@ impl Page { id, name: name.into(), description: description.into(), + function: String::new(), + location: String::new(), + locked: false, + title_block: String::new(), kind, symbols: Vec::new(), wires: Vec::new(), @@ -242,6 +299,107 @@ pub struct Wire { pub color: String, /// Optional cross-section (e.g. "1.5 mm²"). pub cross_section: String, + /// Wire (connection) number; all wires of a connection carry the same number. + #[serde(skip_serializing_if = "String::is_empty")] + pub number: String, + /// Set manually: automatic numbering keeps it. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub number_fixed: bool, + /// Tag of the cable this wire is a core of, and the core designation. + #[serde(skip_serializing_if = "String::is_empty")] + pub cable: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub core: String, +} + +/// A cable; its cores are assigned to wires (`Wire::cable` / `Wire::core`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Cable { + pub id: u64, + /// Complete device tag, e.g. `=A1-W1`. + pub tag: String, + /// Cable type, e.g. "H07RN-F 4G1.5". + pub cable_type: String, + /// Core designations separated by blanks, e.g. "BN BK GY GNYE" or "1 2 3 GNYE". + pub cores: String, + pub cross_section: String, + /// Length in metres. + pub length: f32, + /// Part number (bill of materials: length × part). + pub part: String, + pub description: String, +} + +impl Cable { + pub fn core_list(&self) -> Vec { + self.cores.split_whitespace().map(String::from).collect() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum NumberScheme { + /// 1, 2, 3 … in schematic order. + #[default] + Sequential, + /// Page, column and counter: `3.4.1`. + PageColumn, + /// Named potentials (L1, +24V …) keep their name, other connections are counted. + Potential, +} + +impl NumberScheme { + pub const ALL: [NumberScheme; 3] = [NumberScheme::Sequential, NumberScheme::PageColumn, NumberScheme::Potential]; + + pub fn title(self) -> &'static str { + match self { + NumberScheme::Sequential => "Sequential (1, 2, 3 …)", + NumberScheme::PageColumn => "Page / column (3.4.1)", + NumberScheme::Potential => "Potential name (L1, +24V, otherwise counted)", + } + } +} + +/// Terminal strip data beyond the placed terminals. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct StripData { + /// Terminal designations in strip order; terminals not listed follow sorted. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub order: Vec, + /// Terminal designation -> jumper (bridge) number; terminals with the same + /// number are connected. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub jumpers: BTreeMap, + /// Spare terminals (not in the schematic) at the end of the strip. + pub spares: u32, +} + +/// PLC card (I/O module) data. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct PlcCard { + /// First byte of the card's inputs / outputs (I.0, Q.0). + pub start_byte: u32, + pub rack: String, + pub slot: String, + pub description: String, +} + +/// Settings of the automatic wire numbering. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct WireNumbering { + pub scheme: NumberScheme, + /// Put in front of counted numbers, e.g. "W". + pub prefix: String, + pub start: u32, +} + +impl Default for WireNumbering { + fn default() -> Self { + WireNumbering { scheme: NumberScheme::Sequential, prefix: String::new(), start: 1 } + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -296,6 +454,7 @@ impl Project { /// Repairs ids after loading (e.g. hand-edited files). pub fn normalize(&mut self) { + crate::symlib::register(&self.symbols); let mut max = 0; for pg in &self.pages { max = max.max(pg.id); @@ -308,6 +467,8 @@ impl Project { max = max.max(e.id); max = e.items.iter().map(|i| i.id).fold(max, u64::max); } + max = self.cables.iter().map(|c| c.id).fold(max, u64::max); + max = self.harnesses.iter().map(|h| h.id).fold(max, u64::max); self.next_id = self.next_id.max(max + 1); // Make sure each symbol has a designation for each pin. for pg in &mut self.pages { @@ -370,21 +531,23 @@ impl Project { v } - /// Next free device tag for an identifying letter, e.g. `-K3`. - pub fn next_tag(&self, letter: &str) -> String { - let prefix = format!("-{letter}"); - let mut max = 0u32; - for pg in &self.pages { - for s in &pg.symbols { - if let Some(rest) = s.tag.strip_prefix(&prefix) { - if let Ok(n) = rest.parse::() { - max = max.max(n); - } - } - } - } + /// Next free device tag for an identifying letter within a structure, e.g. + /// `=A1-K3` (counted per structure, as `=A1-K1` and `=A2-K1` are different devices). + pub fn next_tag(&self, structure: &str, letter: &str) -> String { + let prefix = format!("{structure}-{letter}"); + let tags = self.pages.iter().flat_map(|pg| pg.symbols.iter().map(|s| s.tag.as_str())); + let max = tags + .chain(self.cables.iter().map(|c| c.tag.as_str())) + .chain(self.harnesses.iter().map(|h| h.tag.as_str())) + .filter_map(|t| t.strip_prefix(&prefix)?.parse::().ok()) + .max() + .unwrap_or(0); format!("{prefix}{}", max + 1) } + + pub fn cable(&self, tag: &str) -> Option<&Cable> { + self.cables.iter().find(|c| c.tag == tag) + } } diff --git a/src/model/tests.rs b/src/model/tests.rs index c47d839a..526f3a9d 100644 --- a/src/model/tests.rs +++ b/src/model/tests.rs @@ -6,3 +6,24 @@ fn columns() { assert_eq!(column_of(p(FRAME_X1 - 1.0, 50.0)), COLUMNS); assert_eq!(row_of(p(100.0, AREA_Y0 + 1.0)), 'A'); } + +#[test] +fn files_without_structure_cables_and_numbers_still_load() { + let old = r#"{"pages":[{"id":1,"name":"1","kind":"Schematic","wires":[{"id":2,"a":{"x":0,"y":0},"b":{"x":0,"y":8},"color":"","cross_section":""}]}],"next_id":3}"#; + let prj: Project = serde_json::from_str(old).unwrap(); + assert!(prj.cables.is_empty()); + assert_eq!(prj.wire_numbering, WireNumbering::default()); + assert!(prj.pages[0].function.is_empty() && prj.pages[0].wires[0].number.is_empty()); + // Empty new wire fields are not written. + let json = serde_json::to_string(&prj.pages[0].wires[0]).unwrap(); + assert!(!json.contains("number") && !json.contains("cable"), "{json}"); +} + +#[test] +fn next_tag_counts_per_structure_and_cables() { + let mut prj = Project::default(); + prj.cables.push(Cable { tag: "=A1-W1".into(), ..Default::default() }); + assert_eq!(prj.next_tag("=A1", "W"), "=A1-W2"); + assert_eq!(prj.next_tag("", "W"), "-W1"); + assert_eq!(prj.cable("=A1-W1").map(|c| c.core_list().len()), Some(0)); +} \ No newline at end of file diff --git a/src/netlist.rs b/src/netlist.rs index 3ef2cc74..0ac9e72c 100644 --- a/src/netlist.rs +++ b/src/netlist.rs @@ -121,13 +121,16 @@ pub fn junctions(page: &Page) -> Vec

{ impl Netlist { /// Builds the netlist. With `bridge_terminals == false` the two sides of a terminal - /// are kept as separate nets (used for terminal diagrams). + /// are kept as separate nets (used for terminal diagrams and wire numbers); with + /// `true` the jumpers of terminal strips connect their terminals as well. pub fn build(prj: &Project, bridge_terminals: bool) -> Netlist { let mut b = Builder { uf: Uf { parent: Vec::new() }, points: HashMap::new(), named: HashMap::new() }; let mut pin_nodes: Vec<(PinRef, u64, usize)> = Vec::new(); let mut wire_nodes: Vec<(usize, u64, usize)> = Vec::new(); // Number of things touching each point node (to find unconnected pins). let mut degree: HashMap = HashMap::new(); + // (strip, terminal designation) -> node, for jumpers + let mut terminals: HashMap<(String, String), usize> = HashMap::new(); for (pi, page) in prj.pages.iter().enumerate() { if page.kind != PageKind::Schematic { @@ -151,6 +154,9 @@ impl Netlist { } for (si, s) in page.symbols.iter().enumerate() { let Some(def) = symbols::get(&s.sym) else { continue }; + if def.func == Func::Overview { + continue; + } let mut nodes = Vec::new(); for i in 0..def.pins.len() { let q = def.pin_world(i, s.pos, s.rot, s.mirror); @@ -164,6 +170,9 @@ impl Netlist { b.uf.union(nodes[x], nodes[y]); } } + if def.func == Func::Terminal && !nodes.is_empty() { + terminals.insert((s.tag.clone(), s.label.clone()), nodes[0]); + } match def.func { Func::Potential if !s.label.is_empty() => { let n = b.named(format!("pot:{}", s.label)); @@ -178,6 +187,15 @@ impl Netlist { } } + if bridge_terminals { + for (strip, labels) in crate::strips::jumper_groups(prj) { + let nodes: Vec = labels.iter().filter_map(|l| terminals.get(&(strip.clone(), l.clone())).copied()).collect(); + for w in nodes.windows(2) { + b.uf.union(w[0], w[1]); + } + } + } + let mut nl = Netlist::default(); let mut root_net: HashMap = HashMap::new(); let mut net_for = |uf: &mut Uf, nets: &mut Vec, node: usize| -> usize { @@ -243,18 +261,26 @@ impl Netlist { /// A point-to-point connection between two device connection points. #[derive(Clone, Debug)] pub struct Connection { + /// Potential (from the netlist with bridged terminals). pub net: String, pub a: PinRef, pub b: PinRef, pub color: String, pub cross_section: String, + pub number: String, + /// Cable tag and core, if the wires are a cable core. + pub cable: String, + pub core: String, + /// Harness the connection belongs to. + pub harness: String, } -/// Point-to-point connections: the device connection points of each net are chained -/// in schematic order (potentials and connectors are not physical wire ends). -pub fn connections(prj: &Project, nl: &Netlist) -> Vec { +/// Point-to-point connections: the device connection points of each connection of +/// `open` (terminal sides apart) are chained in schematic order (potentials and +/// connectors are not physical wire ends). Potential names come from `nl`. +pub fn connections(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { let mut out = Vec::new(); - for net in &nl.nets { + for net in &open.nets { let mut pins: Vec<&PinRef> = net .pins .iter() @@ -266,25 +292,40 @@ pub fn connections(prj: &Project, nl: &Netlist) -> Vec { if pins.len() < 2 { continue; } + let at = |p: &PinRef| { + let s = &prj.pages[p.page].symbols[p.sym]; + symbols::get(&s.sym).map(|d| d.pin_world(p.pin, s.pos, s.rot, s.mirror)).unwrap_or(s.pos) + }; pins.sort_by(|a, b| { - let (sa, sb) = (&prj.pages[a.page].symbols[a.sym], &prj.pages[b.page].symbols[b.sym]); - a.page.cmp(&b.page).then(sa.pos.x.total_cmp(&sb.pos.x)).then(sa.pos.y.total_cmp(&sb.pos.y)) + let (qa, qb) = (at(a), at(b)); + a.page.cmp(&b.page).then(qa.x.total_cmp(&qb.x)).then(qa.y.total_cmp(&qb.y)) }); - let (color, cross_section) = net - .wires + let wires = crate::wirenum::wires_of(prj, net); + let (color, cross_section) = wires .iter() - .find_map(|(pi, wid)| { - prj.pages[*pi].wires.iter().find(|w| w.id == *wid && (!w.color.is_empty() || !w.cross_section.is_empty())) - }) + .find(|w| !w.color.is_empty() || !w.cross_section.is_empty()) .map(|w| (w.color.clone(), w.cross_section.clone())) .unwrap_or_default(); + let (cable, core) = wires.iter().find(|w| !w.cable.is_empty()).map(|w| (w.cable.clone(), w.core.clone())).unwrap_or_default(); + let number = crate::wirenum::number_of(prj, net); + let first = pins[0]; + let potential = nl + .pin_net + .get(&(prj.pages[first.page].symbols[first.sym].id, first.pin)) + .map(|&n| nl.nets[n].name.clone()) + .unwrap_or_else(|| net.name.clone()); for pair in pins.windows(2) { + let harness = crate::harness::of(prj, &pin_designation(prj, *pair[0]), &pin_designation(prj, *pair[1])); out.push(Connection { - net: net.name.clone(), + net: potential.clone(), a: *pair[0], b: *pair[1], color: color.clone(), cross_section: cross_section.clone(), + number: number.clone(), + cable: cable.clone(), + core: core.clone(), + harness, }); } } diff --git a/src/ops.rs b/src/ops.rs index b8993b78..9551e87e 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -94,8 +94,10 @@ fn next_plc_address(prj: &Project, card: &str, prefix: char) -> String { format!("{prefix}{}.{}", n / 8, n % 8) } -/// Creates a symbol instance with sensible defaults (tag, numbering, ...). -pub fn new_symbol(prj: &mut Project, ctx: &PlaceCtx, def: &SymbolDef, pos: P, rot: u8, mirror: bool) -> SymbolInst { +/// Creates a symbol instance for a page with sensible defaults (tag in the page's +/// structure, numbering, ...). +pub fn new_symbol(prj: &mut Project, page: usize, ctx: &PlaceCtx, def: &SymbolDef, pos: P, rot: u8, mirror: bool) -> SymbolInst { + let structure = crate::structure::page_structure(&prj.pages[page]); let mut s = SymbolInst { id: prj.new_id(), sym: def.key.into(), @@ -107,21 +109,22 @@ pub fn new_symbol(prj: &mut Project, ctx: &PlaceCtx, def: &SymbolDef, pos: P, ro ..Default::default() }; match def.func { - Func::Main { .. } => s.tag = prj.next_tag(def.letter), + Func::Main { .. } => s.tag = prj.next_tag(&structure, def.letter), + Func::Overview => s.tag = ctx.last_main.get(def.letter).cloned().unwrap_or_else(|| prj.next_tag(&structure, def.letter)), Func::Aux(kind) => { - s.tag = ctx.last_main.get(def.letter).cloned().unwrap_or_else(|| prj.next_tag(def.letter)); + s.tag = ctx.last_main.get(def.letter).cloned().unwrap_or_else(|| prj.next_tag(&structure, def.letter)); if def.auto_number { s.pins = next_contact_pins(prj, &s.tag, kind, None); } } Func::Terminal => { - s.tag = ctx.last_strip.clone().unwrap_or_else(|| "-X1".into()); + s.tag = ctx.last_strip.clone().unwrap_or_else(|| format!("{structure}-X1")); if def.default_label.chars().all(|c| c.is_ascii_digit()) { s.label = next_terminal(prj, &s.tag); } } Func::Plc => { - s.tag = ctx.last_plc.get(def.key).cloned().unwrap_or_else(|| prj.next_tag(def.letter)); + s.tag = ctx.last_plc.get(def.key).cloned().unwrap_or_else(|| prj.next_tag(&structure, def.letter)); let prefix = def.default_label.chars().next().unwrap_or('I'); s.label = next_plc_address(prj, &s.tag, prefix); } @@ -291,9 +294,13 @@ pub fn cleanup_wires(page: &mut Page) { }); } -#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] pub struct Clip { pub magic: String, + /// Function and location of the page the clip was copied from. + pub function: String, + pub location: String, pub symbols: Vec, pub wires: Vec, pub texts: Vec, @@ -305,6 +312,8 @@ const CLIP_MAGIC: &str = "openecraft-clipboard-v1"; pub fn copy(page: &Page, sel: &BTreeSet) -> Clip { Clip { magic: CLIP_MAGIC.into(), + function: page.function.clone(), + location: page.location.clone(), symbols: page.symbols.iter().filter(|s| sel.contains(&s.id)).cloned().collect(), wires: page.wires.iter().filter(|s| sel.contains(&s.id)).cloned().collect(), texts: page.texts.iter().filter(|s| sel.contains(&s.id)).cloned().collect(), @@ -326,7 +335,7 @@ impl Clip { self.symbols.is_empty() && self.wires.is_empty() && self.texts.is_empty() && self.shapes.is_empty() } - fn bounds(&self) -> R { + pub fn bounds(&self) -> R { let mut r = R::nothing(); for s in &self.symbols { r.extend(s.pos); @@ -346,9 +355,13 @@ impl Clip { } } -/// Pastes the clip so that its top-left corner lands on `at`. Device tags of main -/// functions that already exist get new numbers (consistently for coil + contacts). +/// Pastes the clip so that its top-left corner lands on `at`. Tags move into the +/// structure of the target page; device tags of main functions that already exist +/// get new numbers (consistently for coil + contacts). Wire numbers and cable cores +/// are not copied. pub fn paste(prj: &mut Project, page_i: usize, clip: &Clip, at: P) -> BTreeSet { + let source = Page { function: clip.function.clone(), location: clip.location.clone(), ..Default::default() }; + let target = prj.pages[page_i].clone(); let b = clip.bounds(); if !b.is_valid() { return BTreeSet::new(); @@ -362,13 +375,16 @@ pub fn paste(prj: &mut Project, page_i: usize, clip: &Clip, at: P) -> BTreeSet { if let Some(n) = rename.get(&s.tag) { s.tag = n.clone(); } else { - let n = prj.next_tag(def.letter); + let n = prj.next_tag(&crate::structure::Dt::parse(&s.tag).structure(), def.letter); // Reserve the tag by temporarily recording it. rename.insert(s.tag.clone(), n.clone()); s.tag = n; @@ -390,6 +406,10 @@ pub fn paste(prj: &mut Project, page_i: usize, clip: &Clip, at: P) -> BTreeSet, cable: &str) -> usize { + let Some(c) = prj.cable(cable) else { return 0 }; + let cores = c.core_list(); + let used: Vec = prj + .pages + .iter() + .enumerate() + .flat_map(|(pi, pg)| pg.wires.iter().map(move |w| (pi, w))) + .filter(|(pi, w)| w.cable == cable && !(*pi == page && wires.contains(&w.id))) + .map(|(_, w)| w.core.clone()) + .collect(); + let mut free = cores.into_iter().filter(|c| !used.contains(c)); + let mut sel: Vec<&mut Wire> = prj.pages[page].wires.iter_mut().filter(|w| wires.contains(&w.id)).collect(); + sel.sort_by(|a, b| a.a.x.min(a.b.x).total_cmp(&b.a.x.min(b.b.x)).then(a.a.y.min(a.b.y).total_cmp(&b.a.y.min(b.b.y)))); + let mut n = 0; + for w in sel { + let Some(core) = free.next() else { break }; + w.cable = cable.to_string(); + w.core = core; + n += 1; + } + n +} + +/// Changes the structure of a page; with `move_devices` the devices on the page +/// move along (all their functions, also on other pages, see [`rename_device`]). +pub fn set_page_structure(prj: &mut Project, page: usize, function: &str, location: &str, move_devices: bool) { + let old = prj.pages[page].clone(); + prj.pages[page].function = crate::structure::clean_aspect(function); + prj.pages[page].location = crate::structure::clean_aspect(location); + if !move_devices { + return; + } + let new = prj.pages[page].clone(); + let mut tags: Vec = old.symbols.iter().filter(|s| !s.tag.is_empty()).map(|s| s.tag.clone()).collect(); + tags.sort(); + tags.dedup(); + for tag in tags { + let moved = crate::structure::complete(&new, &crate::structure::relative(&old, &tag)); + if moved != tag && !prj.all_tags().contains(&moved) { + rename_device(prj, &tag, &moved); + } + } } #[cfg(test)] diff --git a/src/ops/tests.rs b/src/ops/tests.rs index b9c7b07c..11c4f1f6 100644 --- a/src/ops/tests.rs +++ b/src/ops/tests.rs @@ -5,17 +5,17 @@ fn contact_numbering_and_tag_follow_coil() { let mut prj = Project::default(); let mut ctx = PlaceCtx::default(); let coil = symbols::get("coil").unwrap(); - let s = new_symbol(&mut prj, &ctx, coil, p(40.0, 40.0), 0, false); + let s = new_symbol(&mut prj, 0, &ctx, coil, p(40.0, 40.0), 0, false); assert_eq!(s.tag, "-K1"); ctx.remember(&s); prj.pages[0].symbols.push(s); let no = symbols::get("no").unwrap(); - let c1 = new_symbol(&mut prj, &ctx, no, p(80.0, 40.0), 0, false); + let c1 = new_symbol(&mut prj, 0, &ctx, no, p(80.0, 40.0), 0, false); assert_eq!(c1.tag, "-K1"); assert_eq!(c1.pins, vec!["13", "14"]); prj.pages[0].symbols.push(c1); let nc = symbols::get("nc").unwrap(); - let c2 = new_symbol(&mut prj, &ctx, nc, p(120.0, 40.0), 0, false); + let c2 = new_symbol(&mut prj, 0, &ctx, nc, p(120.0, 40.0), 0, false); assert_eq!(c2.pins, vec!["21", "22"]); } @@ -25,7 +25,7 @@ fn plc_addresses_increment() { let mut ctx = PlaceCtx::default(); let di = symbols::get("plc_in").unwrap(); for expect in ["I0.0", "I0.1"] { - let s = new_symbol(&mut prj, &ctx, di, p(40.0, 40.0), 0, false); + let s = new_symbol(&mut prj, 0, &ctx, di, p(40.0, 40.0), 0, false); assert_eq!(s.label, expect); ctx.remember(&s); prj.pages[0].symbols.push(s); @@ -37,7 +37,7 @@ fn paste_renames_existing_devices() { let mut prj = Project::default(); let ctx = PlaceCtx::default(); let coil = symbols::get("coil").unwrap(); - let s = new_symbol(&mut prj, &ctx, coil, p(40.0, 40.0), 0, false); + let s = new_symbol(&mut prj, 0, &ctx, coil, p(40.0, 40.0), 0, false); let id = s.id; prj.pages[0].symbols.push(s); let clip = copy(&prj.pages[0], &BTreeSet::from([id])); @@ -50,10 +50,107 @@ fn paste_renames_existing_devices() { fn rotate_single_symbol_keeps_origin() { let mut prj = Project::default(); let ctx = PlaceCtx::default(); - let s = new_symbol(&mut prj, &ctx, symbols::get("no").unwrap(), p(40.0, 40.0), 0, false); + let s = new_symbol(&mut prj, 0, &ctx, symbols::get("no").unwrap(), p(40.0, 40.0), 0, false); let id = s.id; prj.pages[0].symbols.push(s); rotate(&mut prj.pages[0], &BTreeSet::from([id])); let s = &prj.pages[0].symbols[0]; assert_eq!((s.pos, s.rot), (p(40.0, 40.0), 1)); } + +/// Project with a second page in structure =A1+CAB1. +fn structured() -> Project { + let mut prj = Project::default(); + let id = prj.new_id(); + let mut pg = Page::new(id, "2", "", PageKind::Schematic); + pg.function = "A1".into(); + pg.location = "CAB1".into(); + prj.pages.push(pg); + prj +} + +#[test] +fn devices_get_the_page_structure() { + let mut prj = structured(); + let ctx = PlaceCtx::default(); + let coil = symbols::get("coil").unwrap(); + let a = new_symbol(&mut prj, 1, &ctx, coil, p(40.0, 40.0), 0, false); + assert_eq!(a.tag, "=A1+CAB1-K1"); + prj.pages[1].symbols.push(a); + // Numbering is per structure. + assert_eq!(new_symbol(&mut prj, 1, &ctx, coil, p(80.0, 40.0), 0, false).tag, "=A1+CAB1-K2"); + assert_eq!(new_symbol(&mut prj, 0, &ctx, coil, p(80.0, 40.0), 0, false).tag, "-K1"); + let term = symbols::get("term").unwrap(); + assert_eq!(new_symbol(&mut prj, 1, &ctx, term, p(80.0, 40.0), 0, false).tag, "=A1+CAB1-X1"); +} + +#[test] +fn paste_moves_devices_into_the_target_structure() { + let mut prj = structured(); + let ctx = PlaceCtx::default(); + let s = new_symbol(&mut prj, 0, &ctx, symbols::get("coil").unwrap(), p(40.0, 40.0), 0, false); + let id = s.id; + prj.pages[0].symbols.push(s); + let clip = copy(&prj.pages[0], &BTreeSet::from([id])); + let ids = paste(&mut prj, 1, &clip, p(80.0, 40.0)); + let new = prj.pages[1].symbols.iter().find(|s| ids.contains(&s.id)).unwrap(); + assert_eq!(new.tag, "=A1+CAB1-K1"); +} + +#[test] +fn page_structure_change_renames_its_devices() { + let mut prj = structured(); + let ctx = PlaceCtx::default(); + let s = new_symbol(&mut prj, 1, &ctx, symbols::get("coil").unwrap(), p(40.0, 40.0), 0, false); + prj.pages[1].symbols.push(s); + // A contact of the coil on the other page follows the device. + let mut contact = new_symbol(&mut prj, 0, &ctx, symbols::get("no").unwrap(), p(80.0, 40.0), 0, false); + contact.tag = "=A1+CAB1-K1".into(); + prj.pages[0].symbols.push(contact); + prj.devices.insert("=A1+CAB1-K1".into(), DeviceData { description: "pump".into(), ..Default::default() }); + set_page_structure(&mut prj, 1, "=A2", "+CAB1", true); + assert_eq!((prj.pages[1].function.as_str(), prj.pages[1].location.as_str()), ("A2", "CAB1")); + assert_eq!(prj.all_tags(), vec!["=A2+CAB1-K1".to_string()]); + assert_eq!(prj.devices["=A2+CAB1-K1"].description, "pump"); + // Without moving, the tags stay. + set_page_structure(&mut prj, 1, "A3", "", false); + assert_eq!(prj.all_tags(), vec!["=A2+CAB1-K1".to_string()]); +} + +#[test] +fn wires_get_free_cores_in_order() { + let mut prj = Project::default(); + let id = prj.new_id(); + prj.cables.push(Cable { id, tag: "-W1".into(), cores: "BN BK GY GNYE".into(), ..Default::default() }); + for (id, x) in [(10, 60.0), (11, 40.0), (12, 50.0)] { + prj.pages[0].wires.push(Wire { id, a: p(x, 10.0), b: p(x, 30.0), ..Default::default() }); + } + // BK is already used by another wire. + prj.pages[0].wires.push(Wire { id: 13, a: p(0.0, 0.0), b: p(0.0, 9.0), cable: "-W1".into(), core: "BK".into(), ..Default::default() }); + assert_eq!(assign_cores(&mut prj, 0, &BTreeSet::from([10, 11, 12]), "-W1"), 3); + let core = |id: u64| prj.pages[0].wires.iter().find(|w| w.id == id).unwrap().core.clone(); + assert_eq!((core(11), core(12), core(10)), ("BN".into(), "GY".into(), "GNYE".into())); + // No free core left, unknown cable. + prj.pages[0].wires.push(Wire { id: 14, a: p(70.0, 10.0), b: p(70.0, 30.0), ..Default::default() }); + assert_eq!(assign_cores(&mut prj, 0, &BTreeSet::from([14]), "-W1"), 0); + assert_eq!(assign_cores(&mut prj, 0, &BTreeSet::from([14]), "-W9"), 0); +} + +#[test] +fn paste_drops_numbers_and_cores() { + let mut prj = Project::default(); + prj.pages[0].wires.push(Wire { id: 5, a: p(0.0, 0.0), b: p(0.0, 20.0), number: "7".into(), cable: "-W1".into(), core: "BN".into(), ..Default::default() }); + prj.next_id = 6; + let clip = copy(&prj.pages[0], &BTreeSet::from([5])); + let ids = paste(&mut prj, 0, &clip, p(40.0, 0.0)); + let w = prj.pages[0].wires.iter().find(|w| ids.contains(&w.id)).unwrap(); + assert!(w.number.is_empty() && w.cable.is_empty() && w.core.is_empty()); +} + +#[test] +fn rename_device_updates_the_panel_layout() { + let mut prj = crate::sample::demo_project(); + rename_device(&mut prj, "-K1", "-K10"); + assert!(prj.layout.find_device("-K10").is_some()); + assert!(prj.layout.find_device("-K1").is_none()); +} \ No newline at end of file diff --git a/src/panel.rs b/src/panel.rs index f2a151e2..6dfec4f8 100644 --- a/src/panel.rs +++ b/src/panel.rs @@ -4,11 +4,14 @@ //! //! Coordinates on the mounting plate are millimetres, origin at the top left corner //! of the plate, x to the right, y downwards (like schematic pages). `z` is the height -//! above the plate surface. +//! above the plate surface. Items on the door (door devices, door cutouts) use the +//! door's front view: origin at the top left corner of the enclosure front, `z` is the +//! distance behind the door. use crate::geom::{p, P, R}; use crate::model::Project; use crate::netlist::{connections, Netlist}; +use crate::parts::vec3::{box_triangles, surfaces_intersect, Tri, V3}; use crate::parts::{self, FnKind}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeSet, HashSet}; @@ -24,12 +27,48 @@ pub const SNAP: f32 = 5.0; pub const RAIL_PROFILE: (f32, f32) = (35.0, 7.5); /// Cable duct profile (width × depth) if the part has no data. pub const DUCT_PROFILE: (f32, f32) = (40.0, 60.0); +/// Busbar system profile (width × height) if the part has no data. +pub const BUSBAR_PROFILE: (f32, f32) = (75.0, 40.0); /// Device size if the part has no mounting data. pub const DEFAULT_DEVICE: (f32, f32, f32) = (40.0, 40.0, 40.0); pub const RAIL_PART: &str = "GEN.RAIL-TS35-1M"; pub const DUCT_PART: &str = "GEN.DUCT-40X60"; pub const ENCLOSURE_PART: &str = "GEN.ENC-600X800"; +pub const BUSBAR_PART: &str = "GEN.BB-3X12X5"; +/// Door frame: door devices keep this distance from the door edges. +pub const DOOR_FRAME: f32 = 20.0; +/// Wire loop across the door hinge. +pub const DOOR_LOOP: f32 = 150.0; + +/// Mounting surface of an item. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Face { + #[default] + Plate, + Door, +} + +impl Face { + pub fn title(self) -> &'static str { + match self { + Face::Plate => "Mounting plate", + Face::Door => "Door", + } + } + + /// Distance of the face's origin from the top left corner of the enclosure. + pub fn origin(self) -> f32 { + match self { + Face::Plate => PLATE_MARGIN, + Face::Door => 0.0, + } + } +} + +fn is_plate(f: &Face) -> bool { + *f == Face::Plate +} #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ItemKind { @@ -37,6 +76,10 @@ pub enum ItemKind { Device, Rail, Duct, + /// Copper busbar system (several parallel bars on holders). + Busbar, + /// Opening in the mounting plate (rectangular or round). + Cutout, } impl ItemKind { @@ -45,8 +88,26 @@ impl ItemKind { ItemKind::Device => "Device", ItemKind::Rail => "Mounting rail", ItemKind::Duct => "Cable duct", + ItemKind::Busbar => "Busbar system", + ItemKind::Cutout => "Cutout", } } + + /// Drawing / picking order: higher is on top. + pub fn layer(self) -> u8 { + match self { + ItemKind::Cutout => 0, + ItemKind::Rail => 1, + ItemKind::Duct => 2, + ItemKind::Busbar => 3, + ItemKind::Device => 4, + } + } + + /// Profiles drawn from a start to an end point. + pub fn is_profile(self) -> bool { + matches!(self, ItemKind::Rail | ItemKind::Duct | ItemKind::Busbar) + } } #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -65,6 +126,11 @@ pub struct PanelItem { pub d: f32, /// Base height above the plate (devices on a rail sit on the rail). pub z: f32, + /// Round cutout (diameter = width). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub round: bool, + #[serde(skip_serializing_if = "is_plate")] + pub face: Face, } impl PanelItem { @@ -115,6 +181,8 @@ pub struct Enclosure { pub width: f32, pub height: f32, pub depth: f32, + /// Space kept free behind the door (door-mounted devices, handles), mm. + pub door_clearance: f32, pub items: Vec, } @@ -127,6 +195,7 @@ impl Default for Enclosure { width: 600.0, height: 800.0, depth: 250.0, + door_clearance: 0.0, items: Vec::new(), } } @@ -145,6 +214,47 @@ impl Enclosure { pub fn item(&self, id: u64) -> Option<&PanelItem> { self.items.iter().find(|i| i.id == id) } + + /// Size of a face (mounting plate or door). + pub fn face_size(&self, face: Face) -> (f32, f32) { + match face { + Face::Plate => self.plate_size(), + Face::Door => (self.width, self.height), + } + } +} + +/// 3D box of an item in enclosure coordinates: x to the right and y downwards from +/// the top left corner of the enclosure front, z from the rear wall towards the door. +pub fn item_box(e: &Enclosure, it: &PanelItem) -> (V3, V3) { + match it.face { + Face::Plate => { + let (x, y, z) = (PLATE_MARGIN + it.x, PLATE_MARGIN + it.y, PLATE_Z + it.z); + ([x, y, z], [x + it.w, y + it.h, z + it.d]) + } + Face::Door => ([it.x, it.y, e.depth - it.z - it.d], [it.x + it.w, it.y + it.h, e.depth - it.z]), + } +} + +/// Point of a placed model ([`place_mesh`] coordinates) in enclosure coordinates. +/// Door devices face outwards: their front is at the door. +pub fn to_enclosure(e: &Enclosure, it: &PanelItem, v: V3) -> V3 { + match it.face { + Face::Plate => [PLATE_MARGIN + v[0], PLATE_MARGIN + v[1], PLATE_Z + v[2]], + Face::Door => [v[0], v[1], e.depth - 2.0 * it.z - it.d + v[2]], + } +} + +/// Surface of an item in enclosure coordinates: the part's 3D model, or its box. +pub fn item_surface(e: &Enclosure, it: &PanelItem, parts: &[crate::parts::Part]) -> Vec { + let mesh = parts.iter().find(|p| it.kind == ItemKind::Device && p.number == it.part).and_then(|p| p.model_3d.as_ref()); + match mesh.map(|m| place_mesh(m, it)).filter(|t| !t.is_empty()) { + Some(tris) => tris.into_iter().map(|t| t.map(|v| to_enclosure(e, it, v))).collect(), + None => { + let (min, max) = item_box(e, it); + box_triangles(min, max) + } + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -153,11 +263,13 @@ pub struct Layout { pub enclosures: Vec, /// Additional wire length per connection (stripping, reserve loops) in mm. pub wire_reserve: f32, + /// Wire ends get ferrules (production wire list, bill of materials). + pub ferrules: bool, } impl Default for Layout { fn default() -> Self { - Layout { enclosures: Vec::new(), wire_reserve: 100.0 } + Layout { enclosures: Vec::new(), wire_reserve: 100.0, ferrules: true } } } @@ -213,7 +325,11 @@ pub fn new_profile(prj: &mut Project, kind: ItemKind, part: &str, a: P, b: P) -> /// Profile width and height of rails / ducts (from the part or the defaults). pub fn profile(prj: &Project, kind: ItemKind, part: &str) -> (f32, f32) { - let def = if kind == ItemKind::Rail { RAIL_PROFILE } else { DUCT_PROFILE }; + let def = match kind { + ItemKind::Rail => RAIL_PROFILE, + ItemKind::Busbar => BUSBAR_PROFILE, + _ => DUCT_PROFILE, + }; match prj.parts.iter().find(|x| x.number == part) { Some(pd) if pd.height > 0.0 && pd.depth > 0.0 => (pd.height, pd.depth), _ => def, @@ -332,8 +448,14 @@ pub fn devices_to_place(prj: &Project) -> Vec { v } -/// Places a device with its top left corner at `at` (snapped, rail aware). +/// Places a device on the mounting plate with its top left corner at `at` (snapped, +/// rail aware). pub fn place_device(prj: &mut Project, enc: usize, tag: &str, at: P) -> Option { + place_device_on(prj, enc, tag, at, Face::Plate) +} + +/// Places a device on the mounting plate or the door. +pub fn place_device_on(prj: &mut Project, enc: usize, tag: &str, at: P, face: Face) -> Option { let size = device_size(prj, tag).unwrap_or(DeviceSize { tag: tag.into(), part: String::new(), @@ -354,6 +476,8 @@ pub fn place_device(prj: &mut Project, enc: usize, tag: &str, at: P) -> Option Option= r.x && c.x <= r.x + r.w @@ -386,8 +511,11 @@ pub fn snap_to_rail(e: &Enclosure, item: &mut PanelItem) { // ---------------------------------------------------------------------- checks -/// Pairs of items that occupy the same space. -pub fn collisions(e: &Enclosure) -> Vec<(u64, u64)> { +/// Pairs of items that occupy the same space (or are mounted over a cutout). Boxes +/// are checked first; where a device with a 3D model is involved, the models +/// themselves must penetrate each other (also door devices against the equipment +/// of the mounting plate). +pub fn collisions(e: &Enclosure, parts: &[crate::parts::Part]) -> Vec<(u64, u64)> { let mut v = Vec::new(); for (i, a) in e.items.iter().enumerate() { for b in &e.items[i + 1..] { @@ -395,24 +523,45 @@ pub fn collisions(e: &Enclosure) -> Vec<(u64, u64)> { let rb = b.rect(); let eps = 0.01; let xy = ra.min.x < rb.max.x - eps && rb.min.x < ra.max.x - eps && ra.min.y < rb.max.y - eps && rb.min.y < ra.max.y - eps; - let z = a.z < b.z + b.d - eps && b.z < a.z + a.d - eps; + if a.kind == ItemKind::Cutout || b.kind == ItemKind::Cutout { + // Anything fastened to the plate / door must not sit over an opening. + let other = if a.kind == ItemKind::Cutout { b } else { a }; + if a.face == b.face && xy && other.kind != ItemKind::Cutout && other.z <= eps { + v.push((a.id, b.id)); + } + continue; + } + let (ba, bb) = (item_box(e, a), item_box(e, b)); + if !(0..3).all(|k| ba.0[k] < bb.1[k] - eps && bb.0[k] < ba.1[k] - eps) { + continue; + } // Crossing rails / ducts of the same kind are joined, not colliding. - let joint = a.kind == b.kind && a.kind != ItemKind::Device && a.horizontal() != b.horizontal(); - if xy && z && !joint { - v.push((a.id, b.id)); + let joint = a.face == b.face && a.kind == b.kind && a.kind != ItemKind::Device && a.horizontal() != b.horizontal(); + if joint { + continue; + } + let modelled = |it: &PanelItem| it.kind == ItemKind::Device && parts.iter().any(|p| p.number == it.part && p.model_3d.is_some()); + if (modelled(a) || modelled(b)) && !surfaces_intersect(&item_surface(e, a, parts), &item_surface(e, b, parts)) { + continue; } + v.push((a.id, b.id)); } } v } -/// Items that leave the mounting plate or are higher than the enclosure allows. +/// Items that leave the mounting plate (door: the door inside its frame) or are +/// higher than the enclosure allows (door devices: reaching the mounting plate). pub fn outside(e: &Enclosure) -> Vec { let plate = e.plate_rect().expand(0.01); - let max_z = e.depth - PLATE_Z - PLATE_THICKNESS; + let door = R::from_points(p(DOOR_FRAME, DOOR_FRAME), p(e.width - DOOR_FRAME, e.height - DOOR_FRAME)).expand(0.01); + let max_z = e.depth - PLATE_Z - PLATE_THICKNESS - e.door_clearance; e.items .iter() - .filter(|i| !plate.contains_rect(&i.rect()) || i.z + i.d > max_z) + .filter(|i| match i.face { + Face::Plate => !plate.contains_rect(&i.rect()) || i.z + i.d > max_z, + Face::Door => !door.contains_rect(&i.rect()) || item_box(e, i).0[2] < PLATE_Z, + }) .map(|i| i.id) .collect() } @@ -587,6 +736,8 @@ pub struct RoutedWire { pub net: String, pub color: String, pub cross_section: String, + /// Wire number of the connection. + pub number: String, pub route: Route, /// Total length including the way down to the plate and the reserve. pub length: f32, @@ -639,11 +790,12 @@ pub struct OpenWire { } /// Virtual wiring: routes every point-to-point connection of the schematic between -/// placed devices through the cable ducts. -pub fn virtual_wiring(prj: &Project, nl: &Netlist) -> (Vec, Vec) { +/// placed devices through the cable ducts (`nl`: potentials, `wired`: netlist with +/// the terminal sides apart, see [`connections`]). +pub fn virtual_wiring(prj: &Project, nl: &Netlist, wired: &Netlist) -> (Vec, Vec) { let mut routed = Vec::new(); let mut open = Vec::new(); - for c in connections(prj, nl) { + for c in connections(prj, nl, wired) { let sa = &prj.pages[c.a.page].symbols[c.a.sym]; let sb = &prj.pages[c.b.page].symbols[c.b.sym]; let from = crate::netlist::pin_designation(prj, c.a); @@ -660,9 +812,9 @@ pub fn virtual_wiring(prj: &Project, nl: &Netlist) -> (Vec, Vec (Vec, Vec (Vec, Vec (P, f32) { + match it.face { + Face::Plate => (it.center(), it.z + it.d), + Face::Door => { + let (_, ph) = e.plate_size(); + let c = it.center(); + (p(0.0, (c.y - PLATE_MARGIN).clamp(0.0, ph)), c.x + it.d + DOOR_LOOP + (e.depth - PLATE_Z)) + } + } +} + /// Material for the BOM: (part number, quantity, quantity unit) of rails, ducts and /// enclosures. Rails / ducts are counted by cut length. pub fn layout_material(prj: &Project) -> Vec<(String, f32, Vec)> { @@ -699,7 +866,7 @@ pub fn layout_material(prj: &Project) -> Vec<(String, f32, Vec)> { for e in &prj.layout.enclosures { add(&mut out, &e.part, 1.0, e.name.clone()); let mut lengths: Vec<(String, f32)> = Vec::new(); - for i in e.items.iter().filter(|i| i.kind != ItemKind::Device) { + for i in e.items.iter().filter(|i| i.kind.is_profile()) { match lengths.iter_mut().find(|x| x.0 == i.part) { Some(x) => x.1 += i.length(), None => lengths.push((i.part.clone(), i.length())), @@ -715,14 +882,19 @@ pub fn layout_material(prj: &Project) -> Vec<(String, f32, Vec)> { }; add(&mut out, &part, qty, e.name.clone()); } + let holders = crate::production::busbar_holders(e); + if holders > 0 { + add(&mut out, crate::production::BUSBAR_HOLDER, holders as f32, e.name.clone()); + } } out } /// Item ids involved in any problem (for highlighting). -pub fn problem_items(e: &Enclosure) -> BTreeSet { - let mut s: BTreeSet = collisions(e).into_iter().flat_map(|(a, b)| [a, b]).collect(); +pub fn problem_items(e: &Enclosure, parts: &[crate::parts::Part]) -> BTreeSet { + let mut s: BTreeSet = collisions(e, parts).into_iter().flat_map(|(a, b)| [a, b]).collect(); s.extend(outside(e)); + s.extend(crate::production::clearance_violations(e, parts).into_iter().flat_map(|(a, b)| [a, b])); s } diff --git a/src/panel/tests.rs b/src/panel/tests.rs index be2fde66..8a7f3b2b 100644 --- a/src/panel/tests.rs +++ b/src/panel/tests.rs @@ -46,7 +46,7 @@ fn collisions_and_outside() { // Device beyond the plate edge let (pw, _) = e.plate_size(); e.items.push(device(6, pw - 10.0, 400.0, 40.0, 40.0, 0.0, 50.0)); - assert_eq!(collisions(&e), vec![(1, 2)]); + assert_eq!(collisions(&e, &[]), vec![(1, 2)]); assert_eq!(outside(&e), vec![6]); // Too deep for the enclosure e.items.push(device(7, 100.0, 400.0, 40.0, 40.0, 0.0, 400.0)); @@ -89,7 +89,7 @@ fn virtual_wiring_of_demo() { assert!(an.wiring.iter().any(|w| w.from.starts_with("-Q1") && w.to.starts_with("-K1"))); // The motor is in the field: its connections stay open. let report = &an.reports[&crate::model::ReportKind::PanelWiring]; - assert!(report.rows.iter().any(|r| r[2].starts_with("-M1") && r[7] == "device not placed")); + assert!(report.rows.iter().any(|r| r[3].starts_with("-M1") && r[8] == "device not placed")); } #[test] @@ -241,3 +241,70 @@ fn mounting_page_draws_part_models() { // Terminal screws of the generated front views are circles. assert!(with.matches(" without.matches(" DOOR_LOOP + e.depth - PLATE_Z); + assert!(w.length > extra); + // The mounting layout page shows the door next to the plate. + let page = prj.pages.iter().position(|p| matches!(p.kind, crate::model::PageKind::Mounting(_))).unwrap(); + assert!(crate::svg::page_svg(&prj, page).contains("Door (front view)")); +} diff --git a/src/panel_ui.rs b/src/panel_ui.rs index b93e4141..e52648b0 100644 --- a/src/panel_ui.rs +++ b/src/panel_ui.rs @@ -4,7 +4,7 @@ use crate::editor::{EguiDraw, Palette}; use crate::geom::{p, P}; use crate::model::{natural_cmp, Project}; -use crate::panel::{self, Enclosure, ItemKind, PanelItem, PLATE_MARGIN, PLATE_THICKNESS, PLATE_Z}; +use crate::panel::{self, Enclosure, Face, ItemKind, PanelItem, PLATE_MARGIN, PLATE_THICKNESS, PLATE_Z}; use crate::parts::{self, PartsDb}; use crate::parts::vec3::{cross, dot, norm, sub, Orbit}; use crate::render::{self, Draw, Ink}; @@ -17,9 +17,23 @@ pub enum Tool { Select, Rail, Duct, + Busbar, + Cutout, PlaceDevice(String), } +impl Tool { + /// Item kind and default part of the profile tools. + fn profile(&self) -> Option<(ItemKind, &'static str)> { + match self { + Tool::Rail => Some((ItemKind::Rail, panel::RAIL_PART)), + Tool::Duct => Some((ItemKind::Duct, panel::DUCT_PART)), + Tool::Busbar => Some((ItemKind::Busbar, panel::BUSBAR_PART)), + _ => None, + } + } +} + #[derive(Clone, Copy, PartialEq, Eq)] pub enum View { Front, @@ -43,6 +57,8 @@ pub struct PanelUi { pub enclosure: usize, pub tool: Tool, pub view: View, + /// Face shown in the front view (mounting plate or door). + pub face: Face, pub selection: BTreeSet, /// Selected wire of the virtual wiring (from, to). pub selected_wire: Option<(String, String)>, @@ -59,6 +75,8 @@ pub struct PanelUi { /// Requests for the application. pub goto_schematic: Option, pub add_page: Option, + /// NC export of an enclosure face (DXF = true, CSV = false). + pub export: Option<(usize, Face, bool)>, } impl Default for PanelUi { @@ -67,6 +85,7 @@ impl Default for PanelUi { enclosure: 0, tool: Tool::Select, view: View::Front, + face: Face::Plate, selection: BTreeSet::new(), selected_wire: None, show_wires: true, @@ -81,6 +100,7 @@ impl Default for PanelUi { status: String::new(), goto_schematic: None, add_page: None, + export: None, } } } @@ -147,6 +167,7 @@ impl PanelUi { match prj.layout.find_device(tag) { Some((ei, item)) => { self.enclosure = ei; + self.face = item.face; self.select_item(item.id); true } @@ -221,7 +242,9 @@ impl PanelUi { placed.sort_by(|a, b| natural_cmp(&a.tag, &b.tag)); egui::ScrollArea::vertical().id_salt("placed").auto_shrink([false, false]).show(ui, |ui| { for it in placed { - if ui.selectable_label(self.selection.contains(&it.id), &it.tag).clicked() { + let text = if it.face == Face::Door { format!("{} (door)", it.tag) } else { it.tag.clone() }; + if ui.selectable_label(self.selection.contains(&it.id), text).clicked() { + self.face = it.face; self.select_item(it.id); } } @@ -286,12 +309,50 @@ impl PanelUi { ui.add(egui::DragValue::new(&mut it.h).speed(0.5).range(1.0..=5000.0)); }); ui.end_row(); + ui.label("Mounted on"); + let before = it.face; + ui.horizontal(|ui| { + ui.selectable_value(&mut it.face, Face::Plate, "Mounting plate"); + ui.selectable_value(&mut it.face, Face::Door, "Door"); + }); + if it.face != before { + // Keep the position in front view; door devices sit directly on the door. + let shift = it.face.origin() - before.origin(); + it.x -= shift; + it.y -= shift; + it.z = 0.0; + self.face = it.face; + } + ui.end_row(); ui.label("Depth / mounted at"); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut it.d).speed(0.5).range(1.0..=2000.0)); ui.add(egui::DragValue::new(&mut it.z).speed(0.5).range(0.0..=2000.0).prefix("z ")); }); ui.end_row(); + } else if it.kind == ItemKind::Cutout { + ui.label("Shape"); + ui.horizontal(|ui| { + ui.selectable_value(&mut it.round, false, "Rectangular"); + ui.selectable_value(&mut it.round, true, "Round"); + }); + ui.end_row(); + if it.round { + ui.label("Diameter"); + if ui.add(egui::DragValue::new(&mut it.w).speed(0.5).range(1.0..=2000.0).suffix(" mm")).changed() { + it.h = it.w; + } + } else { + ui.label("Width × height"); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut it.w).speed(0.5).range(1.0..=5000.0)); + ui.add(egui::DragValue::new(&mut it.h).speed(0.5).range(1.0..=5000.0)); + }); + } + ui.end_row(); + if it.round { + it.h = it.w; + } } else { ui.label("Length"); let mut len = it.length(); @@ -363,6 +424,10 @@ impl PanelUi { ui.label("Depth"); ui.add(egui::DragValue::new(&mut e.depth).speed(5.0).range(60.0..=2000.0).suffix(" mm")); ui.end_row(); + ui.label("Door clearance"); + ui.add(egui::DragValue::new(&mut e.door_clearance).speed(1.0).range(0.0..=500.0).suffix(" mm")) + .on_hover_text("Space behind the door that devices must keep free (door-mounted devices, handles)"); + ui.end_row(); let (pw, ph) = e.plate_size(); ui.label("Mounting plate"); ui.label(format!("{pw:.0} × {ph:.0} mm")); @@ -372,13 +437,35 @@ impl PanelUi { ui.label("Wire reserve per connection"); ui.add(egui::DragValue::new(&mut prj.layout.wire_reserve).speed(5.0).range(0.0..=2000.0).suffix(" mm")); }); + ui.checkbox(&mut prj.layout.ferrules, "Wire ends with ferrules").on_hover_text("Production wire list and bill of materials"); let e = &prj.layout.enclosures[ei]; let devices = e.items.iter().filter(|i| i.kind == ItemKind::Device).count(); let wires: Vec<_> = an.wiring.iter().filter(|w| w.enclosure == ei).collect(); let total: f32 = wires.iter().map(|w| w.length).sum(); ui.separator(); ui.label(format!("{devices} devices placed, {} wires routed ({:.1} m)", wires.len(), total / 1000.0)); - let problems = panel::collisions(e).len() + panel::outside(e).len(); + let problems = panel::collisions(e, &prj.parts).len() + panel::outside(e).len() + crate::production::clearance_violations(e, &prj.parts).len(); + let holes = crate::production::holes(e, &prj.parts).len(); + let cutouts = e.items.iter().filter(|i| i.kind == ItemKind::Cutout).count(); + ui.label(format!("Mounting plate: {holes} holes, {cutouts} cutouts")); + ui.horizontal(|ui| { + if ui.button("⬇ NC data (DXF)").on_hover_text("Plate outline, holes per diameter, cutouts").clicked() { + self.export = Some((ei, Face::Plate, true)); + } + if ui.button("⬇ Drilling list (CSV)").clicked() { + self.export = Some((ei, Face::Plate, false)); + } + }); + let door_devices = e.items.iter().filter(|i| i.face == Face::Door && i.kind == ItemKind::Device).count(); + ui.label(format!("Door: {door_devices} devices, {} cutouts", crate::production::openings(e, &prj.parts, Face::Door).len())); + ui.horizontal(|ui| { + if ui.button("⬇ Door NC data (DXF)").clicked() { + self.export = Some((ei, Face::Door, true)); + } + if ui.button("⬇ Door cutouts (CSV)").clicked() { + self.export = Some((ei, Face::Door, false)); + } + }); if problems > 0 { ui.colored_label(Color32::from_rgb(220, 60, 60), format!("{problems} placement problems (red) – see Check")); } @@ -518,12 +605,29 @@ impl PanelUi { ui.selectable_value(&mut self.view, View::ThreeD, "3D"); ui.separator(); if self.view == View::Front { + ui.separator(); + for face in [Face::Plate, Face::Door] { + if ui.selectable_label(self.face == face, face.title()).clicked() && self.face != face { + self.face = face; + self.selection.clear(); + self.selected_wire = None; + if self.tool.profile().is_some() { + self.set_tool(Tool::Select); + } + } + } + ui.separator(); let tool = self.tool.clone(); for (t, label, tip) in [ (Tool::Select, "⬉ Select", "Select / move (Esc)"), (Tool::Rail, "Mounting rail", "Click start and end point"), (Tool::Duct, "Cable duct", "Click start and end point"), + (Tool::Busbar, "Busbar", "Copper busbar system: click start and end point"), + (Tool::Cutout, "Cutout", "Opening in the mounting plate / door: click two corners (round: in the properties)"), ] { + if self.face == Face::Door && t.profile().is_some() { + continue; + } if ui.selectable_label(tool == t, label).on_hover_text(tip).clicked() { self.set_tool(t); } @@ -577,7 +681,8 @@ impl PanelUi { } let ptr = ui.input(|i| i.pointer.hover_pos()).filter(|q| rect.contains(*q)); // Plate coordinates of the pointer - let plate = ptr.map(|s| self.s2w(rect, s) - p(PLATE_MARGIN, PLATE_MARGIN)); + let fm = self.face.origin(); + let plate = ptr.map(|s| self.s2w(rect, s) - p(fm, fm)); let snapped = plate.map(|q| p(panel::snap(q.x), panel::snap(q.y))); // Keyboard @@ -596,6 +701,9 @@ impl PanelUi { self.selected_wire = None; } } + if self.face == Face::Door && self.tool.profile().is_some() { + self.set_tool(Tool::Select); + } if del && !self.selection.is_empty() { e.items.retain(|i| !self.selection.contains(&i.id)); self.selection.clear(); @@ -618,15 +726,18 @@ impl PanelUi { // Mouse match self.tool.clone() { Tool::Select => self.select_and_move(ui, &resp, prj, ei, rect, an), - Tool::Rail | Tool::Duct => { + Tool::Rail | Tool::Duct | Tool::Busbar => { if let (true, Some(sn)) = (resp.clicked_by(PointerButton::Primary), snapped) { match self.start.take() { None => self.start = Some(sn), Some(a) if !a.same(sn) => { - let (kind, part) = if self.tool == Tool::Rail { (ItemKind::Rail, panel::RAIL_PART) } else { (ItemKind::Duct, panel::DUCT_PART) }; + let (kind, part) = self.tool.profile().unwrap_or((ItemKind::Duct, panel::DUCT_PART)); if db.get(part).is_some() { parts::ensure_in_project(prj, db, part); } + if kind == ItemKind::Busbar && db.get(crate::production::BUSBAR_HOLDER).is_some() { + parts::ensure_in_project(prj, db, crate::production::BUSBAR_HOLDER); + } let item = panel::new_profile(prj, kind, part, a, sn); prj.layout.enclosures[ei].items.push(item); } @@ -634,11 +745,27 @@ impl PanelUi { } } } + Tool::Cutout => { + if let (true, Some(sn)) = (resp.clicked_by(PointerButton::Primary), snapped) { + match self.start.take() { + None => self.start = Some(sn), + Some(a) if (a.x - sn.x).abs() > 0.1 && (a.y - sn.y).abs() > 0.1 => { + let id = prj.new_id(); + let (x, y) = (a.x.min(sn.x), a.y.min(sn.y)); + let (w, h) = ((a.x - sn.x).abs(), (a.y - sn.y).abs()); + let (z, d) = if self.face == Face::Door { (0.0, 2.0) } else { (-PLATE_THICKNESS, PLATE_THICKNESS) }; + prj.layout.enclosures[ei].items.push(PanelItem { id, kind: ItemKind::Cutout, x, y, w, h, z, d, face: self.face, ..Default::default() }); + self.select_item(id); + } + Some(_) => {} + } + } + } Tool::PlaceDevice(tag) => { if let (true, Some(q)) = (resp.clicked_by(PointerButton::Primary), plate) { let size = panel::device_size(prj, &tag); let (w, h) = size.map(|s| (s.w, s.h)).unwrap_or((panel::DEFAULT_DEVICE.0, panel::DEFAULT_DEVICE.1)); - if let Some(id) = panel::place_device(prj, ei, &tag, p(q.x - w / 2.0, q.y - h / 2.0)) { + if let Some(id) = panel::place_device_on(prj, ei, &tag, p(q.x - w / 2.0, q.y - h / 2.0), self.face) { self.select_item(id); } // Continue with the next unplaced device. @@ -652,12 +779,13 @@ impl PanelUi { let e = &prj.layout.enclosures[ei]; painter.rect_filled(rect, 0.0, pal.canvas); let origin = rect.min + self.offset; - let problems = panel::problem_items(e); + let problems = panel::problem_items(e, &prj.parts); let mut d = EguiDraw { painter: &painter, origin, zoom: self.zoom, pal: &pal, force: None }; - render::draw_enclosure(&mut d, e, p(0.0, 0.0), 1.0, &self.selection, &problems, &prj.parts); - let to_screen = |q: P| origin + vec2(q.x + PLATE_MARGIN, q.y + PLATE_MARGIN) * self.zoom; - let selected_wire = self.wire_index(an).filter(|i| an.wiring[*i].enclosure == ei); - if self.show_wires || selected_wire.is_some() { + render::draw_enclosure(&mut d, e, self.face, p(0.0, 0.0), 1.0, &self.selection, &problems, &prj.parts); + let to_screen = |q: P| origin + vec2(q.x + fm, q.y + fm) * self.zoom; + // Wires run on the mounting plate. + let selected_wire = self.wire_index(an).filter(|i| an.wiring[*i].enclosure == ei && self.face == Face::Plate); + if (self.show_wires && self.face == Face::Plate) || selected_wire.is_some() { // Other wires are dimmed while one is selected. let normal = if selected_wire.is_some() { WIRE_COLOR.gamma_multiply(0.25) } else { WIRE_COLOR.gamma_multiply(0.7) }; for (i, w) in an.wiring.iter().enumerate().filter(|(_, w)| w.enclosure == ei) { @@ -685,12 +813,20 @@ impl PanelUi { } // Previews let mut g = EguiDraw { painter: &painter, origin, zoom: self.zoom, pal: &pal, force: Some(Ink::Ghost) }; - let m = p(PLATE_MARGIN, PLATE_MARGIN); + let m = p(fm, fm); match (&self.tool, snapped, plate) { - (Tool::Rail | Tool::Duct, Some(sn), _) => { + (Tool::Cutout, Some(sn), _) => { if let Some(a) = self.start { - let kind = if self.tool == Tool::Rail { ItemKind::Rail } else { ItemKind::Duct }; - let part = if kind == ItemKind::Rail { panel::RAIL_PART } else { panel::DUCT_PART }; + g.rect(a + m, sn + m, 0.5, Ink::Ghost, false); + self.status = format!("Cutout {:.0} × {:.0} mm", (sn.x - a.x).abs(), (sn.y - a.y).abs()); + } + let c = to_screen(sn); + painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, pal.ghost)); + painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, pal.ghost)); + } + (Tool::Rail | Tool::Duct | Tool::Busbar, Some(sn), _) => { + if let Some(a) = self.start { + let (kind, part) = self.tool.profile().unwrap_or((ItemKind::Duct, panel::DUCT_PART)); let (pw, _) = panel::profile(prj, kind, part); let horizontal = (sn.x - a.x).abs() >= (sn.y - a.y).abs(); let (r0, r1) = if horizontal { @@ -708,7 +844,7 @@ impl PanelUi { } (Tool::PlaceDevice(tag), _, Some(q)) => { let (w, h) = panel::device_size(prj, tag).map(|s| (s.w, s.h)).unwrap_or((panel::DEFAULT_DEVICE.0, panel::DEFAULT_DEVICE.1)); - let mut ghost = PanelItem { kind: ItemKind::Device, x: panel::snap(q.x - w / 2.0), y: panel::snap(q.y - h / 2.0), w, h, ..Default::default() }; + let mut ghost = PanelItem { kind: ItemKind::Device, x: panel::snap(q.x - w / 2.0), y: panel::snap(q.y - h / 2.0), w, h, face: self.face, ..Default::default() }; panel::snap_to_rail(e, &mut ghost); g.rect(p(ghost.x, ghost.y) + m, p(ghost.x + w, ghost.y + h) + m, 0.6, Ink::Ghost, false); g.text(ghost.center() + m, tag, (w.min(h) * 0.22).clamp(3.0, 9.0), crate::symbols::Anchor::Center, render::VAnchor::Middle, Ink::Ghost); @@ -717,7 +853,7 @@ impl PanelUi { } if let Some(q) = plate { if self.start.is_none() && !resp.clicked() { - self.status = format!("X {:.0} Y {:.0} mm on the mounting plate", q.x, q.y); + self.status = format!("X {:.0} Y {:.0} mm on the {}", q.x, q.y, self.face.title().to_lowercase()); } } } @@ -725,15 +861,15 @@ impl PanelUi { fn select_and_move(&mut self, ui: &egui::Ui, resp: &egui::Response, prj: &mut Project, ei: usize, rect: Rect, an: &Analysis) { let shift = ui.input(|i| i.modifiers.shift); let tol = 6.0 / self.zoom; + let face = self.face; let hit = |e: &Enclosure, q: P| -> Option { - // Devices first, then ducts, then rails. - let order = [ItemKind::Device, ItemKind::Duct, ItemKind::Rail]; - order.iter().find_map(|k| e.items.iter().rev().find(|i| i.kind == *k && i.rect().expand(tol).contains(q)).map(|i| i.id)) - }; - let (offset, zoom) = (self.offset, self.zoom); - let to_plate = move |s: Pos2| { - p((s.x - rect.min.x - offset.x) / zoom - PLATE_MARGIN, (s.y - rect.min.y - offset.y) / zoom - PLATE_MARGIN) + // Top layer first: devices, busbars, ducts, rails, cutouts. + let mut items: Vec<&PanelItem> = e.items.iter().filter(|i| i.face == face && i.rect().expand(tol).contains(q)).collect(); + items.sort_by_key(|i| std::cmp::Reverse(i.kind.layer())); + items.first().map(|i| i.id) }; + let (offset, zoom, fm) = (self.offset, self.zoom, face.origin()); + let to_plate = move |s: Pos2| p((s.x - rect.min.x - offset.x) / zoom - fm, (s.y - rect.min.y - offset.y) / zoom - fm); if resp.drag_started_by(PointerButton::Primary) { let origin = ui.input(|i| i.pointer.press_origin()).unwrap_or(rect.center()); let q = to_plate(origin); @@ -796,7 +932,7 @@ impl PanelUi { let item = hit(e, q); let on_device = item.and_then(|id| e.item(id)).map(|i| i.kind == ItemKind::Device).unwrap_or(false); // Wires lie on top of ducts and rails, devices on top of wires. - if self.show_wires && !on_device && !shift { + if self.show_wires && face == Face::Plate && !on_device && !shift { let candidates = panel::wires_at(&an.wiring, ei, q, tol); if !candidates.is_empty() { self.pick_wire(an, &candidates); @@ -873,7 +1009,7 @@ impl PanelUi { // when looking through the open door, so they are drawn in earlier layers. let mut prims: Vec<(u8, f32, Prim)> = Vec::new(); let light = norm([0.35, 0.75, 0.55]); - let problems = panel::problem_items(e); + let problems = panel::problem_items(e, &prj.parts); let add_box = |prims: &mut Vec<(u8, f32, Prim)>, layer: u8, min: [f32; 3], max: [f32; 3], base: Color32, item: Option| { let c = |x: usize, y: usize, z: usize| [if x == 0 { min[0] } else { max[0] }, if y == 0 { min[1] } else { max[1] }, if z == 0 { min[2] } else { max[2] }]; let faces: [([usize; 4], [f32; 3]); 6] = [ @@ -925,6 +1061,8 @@ impl PanelUi { let plate_min = [PLATE_MARGIN, h - PLATE_MARGIN - ph, PLATE_Z - PLATE_THICKNESS]; add_box(&mut prims, 1, plate_min, [PLATE_MARGIN + pw, h - PLATE_MARGIN, PLATE_Z], Color32::from_rgb(222, 218, 205), None); let to3 = |x: f32, y: f32, z: f32| [PLATE_MARGIN + x, h - PLATE_MARGIN - y, PLATE_Z + z]; + // Enclosure coordinates (y down) to the 3D view (y up). + let up = |q: [f32; 3]| [q[0], h - q[1], q[2]]; let selected_wire = self.wire_index(an).filter(|i| an.wiring[*i].enclosure == ei); let wire_ends = selected_wire.map(|i| an.wiring[i].items); for it in &e.items { @@ -938,6 +1076,8 @@ impl PanelUi { match it.kind { ItemKind::Rail => Color32::from_rgb(205, 208, 212), ItemKind::Duct => Color32::from_rgb(150, 154, 160), + ItemKind::Busbar => Color32::from_rgb(200, 120, 60), + ItemKind::Cutout => Color32::from_rgb(40, 40, 44), ItemKind::Device => Color32::from_rgb(170, 186, 210), } }; @@ -945,7 +1085,7 @@ impl PanelUi { let mesh = prj.parts.iter().find(|p| it.kind == ItemKind::Device && p.number == it.part).and_then(|p| p.model_3d.as_ref()); if let Some(mesh) = mesh { for tri in panel::place_mesh(mesh, it) { - let w = tri.map(|v| to3(v[0], v[1], v[2])); + let w = tri.map(|v| up(panel::to_enclosure(e, it, v))); let n = norm(cross(sub(w[1], w[0]), sub(w[2], w[0]))); if dot(n, sub(eye, w[0])) <= 0.0 { continue; // back face @@ -963,11 +1103,17 @@ impl PanelUi { } continue; } - let min = to3(it.x, it.y + it.h, it.z); - let max = to3(it.x + it.w, it.y, it.z + it.d); + let (b0, b1) = panel::item_box(e, it); + let (min, max) = if it.kind == ItemKind::Cutout && it.face == Face::Plate { + // Dark patch just in front of the plate. + (to3(it.x, it.y + it.h, 0.0), to3(it.x + it.w, it.y, 0.3)) + } else { + (up([b0[0], b1[1], b0[2]]), up([b1[0], b0[1], b1[2]])) + }; let layer = match it.kind { + ItemKind::Cutout => 1, ItemKind::Rail => 2, - ItemKind::Duct => 3, + ItemKind::Duct | ItemKind::Busbar => 3, ItemKind::Device => 5, }; add_box(&mut prims, layer, min, max, base, Some(it.id)); @@ -1027,9 +1173,11 @@ impl PanelUi { } // Device labels on the front faces for it in e.items.iter().filter(|i| i.kind == ItemKind::Device) { - if let Some((q, z)) = project(to3(it.x + it.w / 2.0, it.y + it.h / 2.0, it.z + it.d)) { + let (b0, b1) = panel::item_box(e, it); + let front = up([(b0[0] + b1[0]) / 2.0, (b0[1] + b1[1]) / 2.0, b1[2]]); + if let Some((q, z)) = project(front) { let size = (it.w.min(it.h) * 0.25 * f / z).clamp(0.0, 18.0); - if size >= 7.0 && dot(sub(eye, to3(it.x, it.y, it.z + it.d)), [0.0, 0.0, 1.0]) > 0.0 { + if size >= 7.0 && dot(sub(eye, front), [0.0, 0.0, 1.0]) > 0.0 { painter.text(q, egui::Align2::CENTER_CENTER, &it.tag, egui::FontId::proportional(size), Color32::from_rgb(20, 30, 50)); } } diff --git a/src/parts.rs b/src/parts.rs index e351a72c..124e6de9 100644 --- a/src/parts.rs +++ b/src/parts.rs @@ -6,6 +6,13 @@ use crate::model::Project; use crate::symbols::{self, Func}; pub use openecraft_parts::*; use std::collections::BTreeMap; +use std::sync::OnceLock; + +/// The built-in catalog, built once (reports look up wiring material in it). +pub fn catalog() -> &'static [Part] { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(default_catalog) +} /// Function kind represented by a library symbol. pub fn kind_of_symbol(key: &str) -> Option { diff --git a/src/pdf.rs b/src/pdf.rs new file mode 100644 index 00000000..1a7d0318 --- /dev/null +++ b/src/pdf.rs @@ -0,0 +1,283 @@ +//! PDF export of all pages (A3 landscape): vector graphics, Helvetica text, clickable +//! cross references and report rows, one bookmark per page. The file is plain ASCII +//! (non-ASCII text is written as WinAnsi octal escapes). + +use crate::geom::P; +use crate::index::Index; +use crate::model::{Project, PAGE_H, PAGE_W}; +use crate::render::{draw_page, Draw, Ink, Opts, VAnchor}; +use crate::reports::Analysis; +use crate::symbols::Anchor; +use std::fmt::Write; + +/// Points per millimetre. +const K: f32 = 72.0 / 25.4; + +/// Glyph widths of Helvetica (1/1000 em) for ASCII 32..=126. +const HELVETICA: [u16; 95] = [ + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, + 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, + 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, + 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, +]; + +/// WinAnsi code of a character (`?` if it has none). +fn win_ansi(c: char) -> u8 { + match c { + ' '..='~' => c as u8, + '€' => 0x80, + '…' => 0x85, + '–' => 0x96, + '—' => 0x97, + '‘' => 0x91, + '’' => 0x92, + '“' => 0x93, + '”' => 0x94, + '•' => 0x95, + '\u{a0}'..='\u{ff}' => c as u8, + _ => b'?', + } +} + +/// PDF string literal content. +fn pdf_string(text: &str) -> String { + let mut out = String::new(); + for b in text.chars().map(win_ansi) { + match b { + b'(' | b')' | b'\\' => { + out.push('\\'); + out.push(b as char); + } + 32..=126 => out.push(b as char), + _ => { + let _ = write!(out, "\\{b:03o}"); + } + } + } + out +} + +fn text_width(text: &str, size: f32) -> f32 { + text.chars() + .map(|c| match win_ansi(c) { + b @ 32..=126 => HELVETICA[(b - 32) as usize] as f32, + _ => 556.0, + }) + .sum::() + * size + / 1000.0 +} + +fn rgb(ink: Ink) -> (f32, f32, f32) { + match ink { + Ink::Frame | Ink::FrameText => (0.33, 0.33, 0.33), + Ink::CrossRef => (0.1, 0.24, 0.56), + Ink::Error => (0.8, 0.0, 0.0), + Ink::Plate => (0.95, 0.95, 0.95), + Ink::Fill => (0.86, 0.86, 0.86), + _ => (0.0, 0.0, 0.0), + } +} + +fn x(v: f32) -> f32 { + v * K +} + +fn y(v: f32) -> f32 { + (PAGE_H - v) * K +} + +/// Collects the content stream and the links of one page. +#[derive(Default)] +pub struct PdfDraw { + ops: String, + /// (x0, y0, x1, y1 in PDF units, target page index) + links: Vec<([f32; 4], usize)>, +} + +impl PdfDraw { + fn stroke(&mut self, width: f32, ink: Ink, dashed: bool) { + let (r, g, b) = rgb(ink); + let dash = if dashed { "[4.25 2.83] 0 d" } else { "[] 0 d" }; + let _ = write!(self.ops, "{r:.3} {g:.3} {b:.3} RG {:.3} w {dash} ", width.max(0.1) * K); + } + + fn fill(&mut self, ink: Ink) { + let (r, g, b) = rgb(ink); + let _ = write!(self.ops, "{r:.3} {g:.3} {b:.3} rg "); + } + + fn path(&mut self, pts: &[P]) { + for (i, q) in pts.iter().enumerate() { + let _ = write!(self.ops, "{:.2} {:.2} {} ", x(q.x), y(q.y), if i == 0 { "m" } else { "l" }); + } + } +} + +impl Draw for PdfDraw { + fn line(&mut self, a: P, b: P, width: f32, ink: Ink, dashed: bool) { + self.stroke(width, ink, dashed); + self.path(&[a, b]); + self.ops.push_str("S\n"); + } + + fn poly(&mut self, pts: &[P], closed: bool, width: f32, ink: Ink, fill: bool) { + if pts.len() < 2 { + return; + } + if fill { + self.fill(ink); + } + if !fill || width > 0.0 { + self.stroke(width, ink, false); + } + self.path(pts); + let op = match (fill, width > 0.0, closed) { + (true, true, _) => "b", + (true, false, _) => "f", + (false, _, true) => "s", + (false, _, false) => "S", + }; + self.ops.push_str(op); + self.ops.push('\n'); + } + + fn circle(&mut self, c: P, r: f32, width: f32, ink: Ink, fill: bool) { + // Four Bézier arcs. + let (cx, cy, r) = (x(c.x), y(c.y), r * K); + let k = 0.552_284_8 * r; + if fill { + self.fill(ink); + } else { + self.stroke(width, ink, false); + } + let _ = writeln!( + self.ops, + "{:.2} {:.2} m {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c {}", + cx + r, cy, + cx + r, cy + k, cx + k, cy + r, cx, cy + r, + cx - k, cy + r, cx - r, cy + k, cx - r, cy, + cx - r, cy - k, cx - k, cy - r, cx, cy - r, + cx + k, cy - r, cx + r, cy - k, cx + r, cy, + if fill { "f" } else { "s" } + ); + } + + fn text(&mut self, pos: P, text: &str, size: f32, h: Anchor, v: VAnchor, ink: Ink) { + if text.is_empty() { + return; + } + // Same metrics as the SVG export. + let fs = size * 1.25 * K; + let w = text_width(text, fs); + let x0 = match h { + Anchor::Left => x(pos.x), + Anchor::Center => x(pos.x) - w / 2.0, + Anchor::Right => x(pos.x) - w, + }; + let base = match v { + VAnchor::Middle => pos.y + size * 0.35, + VAnchor::Bottom => pos.y - size * 0.1, + }; + self.fill(ink); + let _ = writeln!(self.ops, "BT /F1 {fs:.2} Tf {x0:.2} {:.2} Td ({}) Tj ET", y(base), pdf_string(text)); + } + + fn link(&mut self, min: P, max: P, page: usize) { + self.links.push(([x(min.x), y(max.y), x(max.x), y(min.y)], page)); + } +} + +/// Builds the PDF objects and the cross reference table. +struct Writer { + out: String, + offsets: Vec, +} + +impl Writer { + fn obj(&mut self, n: usize, body: &str) { + if self.offsets.len() <= n { + self.offsets.resize(n + 1, 0); + } + self.offsets[n] = self.out.len(); + let _ = write!(self.out, "{n} 0 obj\n{body}\nendobj\n"); + } +} + +/// All pages of the project as one PDF document. +pub fn document(prj: &Project) -> String { + let idx = Index::build(prj); + let an = Analysis::build(prj); + let pages: Vec = (0..prj.pages.len()) + .map(|i| { + let mut d = PdfDraw::default(); + draw_page(&mut d, prj, &idx, &an, i, &Opts::default()); + d + }) + .collect(); + + // Object numbers: 1 catalog, 2 page tree, 3 font, 4 outline root, 5 info, then + // per page: page, content, bookmark; then the link annotations. + let n = pages.len(); + let page_obj = |i: usize| 6 + 3 * i; + let mut next = 6 + 3 * n; + let mut w = Writer { out: String::from("%PDF-1.4\n"), offsets: vec![0] }; + w.obj(1, "<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /PageMode /UseOutlines >>"); + let kids: Vec = (0..n).map(|i| format!("{} 0 R", page_obj(i))).collect(); + w.obj(2, &format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))); + w.obj(3, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"); + if n > 0 { + w.obj(4, &format!("<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {n} >>", page_obj(0) + 2, page_obj(n - 1) + 2)); + } else { + w.obj(4, "<< /Type /Outlines /Count 0 >>"); + } + w.obj(5, &format!("<< /Title ({}) /Producer (OpenECraft) >>", pdf_string(&prj.info.name))); + let (width, height) = (PAGE_W * K, PAGE_H * K); + for (i, d) in pages.iter().enumerate() { + let mut annots = Vec::new(); + for (rect, target) in &d.links { + if *target >= n || *target == i { + continue; + } + let body = format!( + "<< /Type /Annot /Subtype /Link /Rect [{:.2} {:.2} {:.2} {:.2}] /Border [0 0 0] /Dest [{} 0 R /Fit] >>", + rect[0], rect[1], rect[2], rect[3], page_obj(*target) + ); + w.obj(next, &body); + annots.push(format!("{next} 0 R")); + next += 1; + } + let po = page_obj(i); + w.obj( + po, + &format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {width:.2} {height:.2}] /Resources << /Font << /F1 3 0 R >> >> /Contents {} 0 R /Annots [{}] >>", + po + 1, + annots.join(" ") + ), + ); + w.obj(po + 1, &format!("<< /Length {} >>\nstream\n{}endstream", d.ops.len(), d.ops)); + let pg = &prj.pages[i]; + let title = format!("{} {}", crate::structure::page_full_name(pg), pg.description).trim().to_string(); + let mut bookmark = format!("<< /Title ({}) /Parent 4 0 R /Dest [{po} 0 R /Fit]", pdf_string(&title)); + if i > 0 { + let _ = write!(bookmark, " /Prev {} 0 R", page_obj(i - 1) + 2); + } + if i + 1 < n { + let _ = write!(bookmark, " /Next {} 0 R", page_obj(i + 1) + 2); + } + bookmark.push_str(" >>"); + w.obj(po + 2, &bookmark); + } + let xref = w.out.len(); + let count = w.offsets.len(); + let _ = writeln!(w.out, "xref\n0 {count}\n0000000000 65535 f "); + for off in &w.offsets[1..] { + let _ = writeln!(w.out, "{off:010} 00000 n "); + } + let _ = write!(w.out, "trailer\n<< /Size {count} /Root 1 0 R /Info 5 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + w.out +} + +#[cfg(test)] +mod tests; diff --git a/src/pdf/tests.rs b/src/pdf/tests.rs new file mode 100644 index 00000000..76628818 --- /dev/null +++ b/src/pdf/tests.rs @@ -0,0 +1,44 @@ +use super::*; +use crate::sample::demo_project; + +#[test] +fn document_structure_is_valid() { + let prj = demo_project(); + let pdf = document(&prj); + assert!(pdf.starts_with("%PDF-1.4\n") && pdf.ends_with("%%EOF\n")); + assert!(pdf.is_ascii()); + // startxref points at the cross reference table, whose offsets point at the objects. + let start: usize = pdf.rsplit("startxref\n").next().unwrap().lines().next().unwrap().parse().unwrap(); + assert!(pdf[start..].starts_with("xref\n")); + let table: Vec<&str> = pdf[start..].lines().skip(3).take_while(|l| !l.starts_with("trailer")).collect(); + for (i, entry) in table.iter().enumerate() { + let off: usize = entry[..10].parse().unwrap(); + assert!(pdf[off..].starts_with(&format!("{} 0 obj", i + 1)), "object {}", i + 1); + } + // Stream lengths match. + for part in pdf.split("<< /Length ").skip(1) { + let len: usize = part[..part.find(' ').unwrap()].parse().unwrap(); + let body = &part[part.find("stream\n").unwrap() + 7..]; + assert!(body[len..].starts_with("endstream")); + } + assert_eq!(pdf.matches("/Type /Page ").count(), prj.pages.len()); + assert_eq!(pdf.matches("/Parent 4 0 R").count(), prj.pages.len(), "one bookmark per page"); +} + +#[test] +fn cross_references_are_links() { + let prj = demo_project(); + let pdf = document(&prj); + // Contacts on page 3 refer to the coil, the coil's contact image to page 2 and 3, + // report rows to their pages. + assert!(pdf.matches("/Subtype /Link").count() > 10); + assert!(pdf.contains("(-K1) Tj")); +} + +#[test] +fn text_encoding_and_metrics() { + assert_eq!(pdf_string("a(b)\\"), "a\\(b\\)\\\\"); + assert_eq!(pdf_string("1.5 mm² – x"), "1.5 mm\\262 \\226 x"); + assert_eq!(pdf_string("Ω"), "?"); + assert!((text_width("A", 10.0) - 6.67).abs() < 0.01); +} diff --git a/src/plc.rs b/src/plc.rs new file mode 100644 index 00000000..62f44c73 --- /dev/null +++ b/src/plc.rs @@ -0,0 +1,192 @@ +//! PLC overview: inputs / outputs per card, addressing from the card's start byte and +//! symbol table exchange with PLC programming tools (CSV: name, data type, address, +//! comment). + +use crate::model::*; +use crate::netlist::{pin_designation, Netlist}; +use crate::symbols::{self, Func}; +use std::collections::{BTreeMap, HashSet}; + +/// A PLC input or output placed in the schematic. +#[derive(Clone, Debug, PartialEq)] +pub struct Point { + pub page: usize, + pub sym: usize, + pub id: u64, + pub card: String, + pub address: String, + pub input: bool, + pub function_text: String, + /// Devices connected to the point. + pub connected: String, + pub location: String, +} + +fn is_plc(s: &SymbolInst) -> bool { + symbols::get(&s.sym).map(|d| d.func) == Some(Func::Plc) +} + +/// Address sort key: prefix, byte, bit (`I1.7` → ('I', 1, 7)). +pub fn address_key(addr: &str) -> (String, u32, u32) { + let a = addr.trim().trim_start_matches('%').to_uppercase(); + let prefix: String = a.chars().take_while(|c| c.is_ascii_alphabetic()).collect(); + let rest = &a[prefix.len()..]; + let (byte, bit) = rest.split_once('.').unwrap_or((rest, "0")); + (prefix, byte.parse().unwrap_or(u32::MAX), bit.parse().unwrap_or(0)) +} + +/// Tags of all PLC cards. +pub fn cards(prj: &Project) -> Vec { + let mut v: Vec = + prj.pages.iter().flat_map(|p| p.symbols.iter()).filter(|s| is_plc(s) && !s.tag.is_empty()).map(|s| s.tag.clone()).collect(); + v.extend(prj.plc_cards.keys().cloned()); + v.sort_by(|a, b| natural_cmp(a, b)); + v.dedup(); + v +} + +/// All PLC points, sorted by card and address. +pub fn points(prj: &Project, nl: &Netlist) -> Vec { + let mut v = Vec::new(); + for (pi, pg) in prj.pages.iter().enumerate() { + if pg.kind != PageKind::Schematic { + continue; + } + for (si, s) in pg.symbols.iter().enumerate().filter(|(_, s)| is_plc(s)) { + let connected = nl + .pin_net + .get(&(s.id, 0)) + .map(|&n| { + let mut t: Vec = + nl.nets[n].pins.iter().filter(|p| (p.page, p.sym) != (pi, si)).map(|p| pin_designation(prj, *p)).collect(); + t.sort_by(|a, b| natural_cmp(a, b)); + t.dedup(); + t.join(", ") + }) + .unwrap_or_default(); + v.push(Point { + page: pi, + sym: si, + id: s.id, + card: s.tag.clone(), + address: s.label.clone(), + input: s.sym == "plc_in", + function_text: s.function_text.replace('\n', " "), + connected, + location: format!("/{}.{}", pg.name, column_of(s.pos)), + }); + } + } + v.sort_by(|a, b| natural_cmp(&a.card, &b.card).then_with(|| address_key(&a.address).cmp(&address_key(&b.address)))); + v +} + +/// Gives the points of a card consecutive addresses from its start byte (inputs and +/// outputs separately, in schematic order). Returns the number of changed addresses. +pub fn readdress(prj: &mut Project, card: &str) -> usize { + let start = prj.plc_cards.get(card).map(|c| c.start_byte).unwrap_or(0); + let mut changed = 0; + for input in [true, false] { + let mut list: Vec<(usize, usize)> = Vec::new(); + for (pi, pg) in prj.pages.iter().enumerate() { + for (si, s) in pg.symbols.iter().enumerate() { + if is_plc(s) && s.tag == card && (s.sym == "plc_in") == input { + list.push((pi, si)); + } + } + } + list.sort_by(|a, b| { + let (sa, sb) = (&prj.pages[a.0].symbols[a.1], &prj.pages[b.0].symbols[b.1]); + a.0.cmp(&b.0).then(sa.pos.x.total_cmp(&sb.pos.x)).then(sa.pos.y.total_cmp(&sb.pos.y)) + }); + let prefix = if input { 'I' } else { 'Q' }; + for (n, (pi, si)) in list.into_iter().enumerate() { + let addr = format!("{prefix}{}.{}", start + n as u32 / 8, n % 8); + let s = &mut prj.pages[pi].symbols[si]; + if s.label != addr { + s.label = addr; + changed += 1; + } + } + } + changed +} + +/// Tag name for a PLC tool: letters, digits and underscores. +fn tag_name(p: &Point) -> String { + let base = if p.function_text.trim().is_empty() { format!("{}_{}", p.card, p.address) } else { p.function_text.clone() }; + let mut s: String = base.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); + while s.contains("__") { + s = s.replace("__", "_"); + } + let s = s.trim_matches('_').to_string(); + if s.starts_with(|c: char| c.is_ascii_digit()) { + format!("_{s}") + } else { + s + } +} + +/// Symbol table for PLC programming tools: `Name;Data Type;Logical Address;Comment`. +pub fn symbol_table(prj: &Project, nl: &Netlist) -> String { + let mut out = String::from("Name;Data Type;Logical Address;Comment\n"); + let mut used = HashSet::new(); + for p in points(prj, nl) { + let mut name = tag_name(&p); + let mut i = 2; + while !used.insert(name.clone()) { + name = format!("{}_{i}", tag_name(&p)); + i += 1; + } + let comment = format!("{} {}", p.card, p.function_text).trim().replace(';', ","); + out.push_str(&format!("{name};Bool;%{};{comment}\n", p.address)); + } + out +} + +/// Takes the comments (or names) of a PLC symbol table as function texts of the +/// points with the same address. Columns are found by their header (`Address` / +/// `Logical Address`, `Comment`, `Name`); `;`, `,` or tab separated. Returns the +/// number of updated points. +pub fn import_symbol_table(prj: &mut Project, text: &str) -> Result { + let mut lines = text.lines().filter(|l| !l.trim().is_empty()); + let header = lines.next().ok_or("empty file")?; + let sep = [';', '\t', ','].into_iter().max_by_key(|c| header.matches(*c).count()).unwrap_or(';'); + let cols: Vec = header.split(sep).map(|c| c.trim().trim_matches('"').to_lowercase()).collect(); + let find = |names: &[&str]| cols.iter().position(|c| names.contains(&c.as_str())); + let addr_col = find(&["logical address", "address", "adresse"]).ok_or("no address column")?; + let comment_col = find(&["comment", "kommentar"]); + let name_col = find(&["name", "symbol"]); + let mut texts: BTreeMap<(String, u32, u32), String> = BTreeMap::new(); + for line in lines { + let cells: Vec<&str> = line.split(sep).map(|c| c.trim().trim_matches('"')).collect(); + let Some(addr) = cells.get(addr_col).filter(|a| !a.is_empty()) else { continue }; + let comment = comment_col.and_then(|i| cells.get(i)).filter(|c| !c.is_empty()); + let text = comment.or(name_col.and_then(|i| cells.get(i))).map(|t| t.to_string()).unwrap_or_default(); + texts.insert(address_key(addr), text); + } + let mut n = 0; + for pg in &mut prj.pages { + for s in pg.symbols.iter_mut().filter(|s| is_plc(s)) { + if let Some(t) = texts.get(&address_key(&s.label)) { + if !t.is_empty() && s.function_text != *t { + s.function_text = t.clone(); + n += 1; + } + } + } + } + Ok(n) +} + +/// Addresses used by more than one point (over all cards). +pub fn duplicate_addresses(prj: &Project, nl: &Netlist) -> Vec<(String, Vec)> { + let mut by: BTreeMap<(String, u32, u32), Vec> = BTreeMap::new(); + for p in points(prj, nl) { + by.entry(address_key(&p.address)).or_default().push(p); + } + by.into_values().filter(|v| v.len() > 1).map(|v| (v[0].address.clone(), v)).collect() +} + +#[cfg(test)] +mod tests; diff --git a/src/plc/tests.rs b/src/plc/tests.rs new file mode 100644 index 00000000..084e5dd8 --- /dev/null +++ b/src/plc/tests.rs @@ -0,0 +1,60 @@ +use super::*; +use crate::sample::demo_project; + +fn nl(prj: &Project) -> Netlist { + Netlist::build(prj, true) +} + +#[test] +fn points_of_the_demo() { + let prj = demo_project(); + assert_eq!(cards(&prj), vec!["-A1".to_string(), "-A2".to_string()]); + let pts = points(&prj, &nl(&prj)); + let addrs: Vec<&str> = pts.iter().map(|p| p.address.as_str()).collect(); + assert_eq!(addrs, ["I0.0", "I0.1", "I0.2", "Q0.0", "Q0.1"]); + assert!(pts[0].input && !pts[3].input); + assert!(pts[0].connected.contains("-B1"), "{}", pts[0].connected); + assert_eq!(address_key("%I10.7"), ("I".into(), 10, 7)); +} + +#[test] +fn readdressing_uses_the_card_start_byte() { + let mut prj = demo_project(); + prj.plc_cards.insert("-A2".into(), PlcCard { start_byte: 4, ..Default::default() }); + assert_eq!(readdress(&mut prj, "-A2"), 2); + let pts = points(&prj, &nl(&prj)); + let a2: Vec<&str> = pts.iter().filter(|p| p.card == "-A2").map(|p| p.address.as_str()).collect(); + assert_eq!(a2, ["Q4.0", "Q4.1"]); + assert_eq!(readdress(&mut prj, "-A2"), 0, "nothing left to change"); +} + +#[test] +fn symbol_table_round_trip() { + let mut prj = demo_project(); + let table = symbol_table(&prj, &nl(&prj)); + let lines: Vec<&str> = table.lines().collect(); + assert_eq!(lines[0], "Name;Data Type;Logical Address;Comment"); + assert_eq!(lines.len(), 6); + assert!(lines.contains(&"Part_present;Bool;%I0.0;-A1 Part present"), "{table}"); + // Names stay unique ("Motor running" is not used twice here, but the rule holds). + let names: HashSet<&str> = lines[1..].iter().map(|l| l.split(';').next().unwrap()).collect(); + assert_eq!(names.len(), 5); + + let import = "\"Name\",\"Data Type\",\"Logical Address\",\"Comment\"\nX,Bool,%I0.1,Reset button\nY,Bool,%Q0.1,\n"; + assert_eq!(import_symbol_table(&mut prj, import).unwrap(), 2); + let pts = points(&prj, &nl(&prj)); + let text = |a: &str| pts.iter().find(|p| p.address == a).unwrap().function_text.clone(); + assert_eq!(text("I0.1"), "Reset button"); + assert_eq!(text("Q0.1"), "Y", "name when there is no comment"); + assert!(import_symbol_table(&mut prj, "Name;Comment\nx;y\n").is_err()); +} + +#[test] +fn addresses_used_on_two_cards_are_reported() { + let mut prj = demo_project(); + let s = prj.pages.iter_mut().flat_map(|p| p.symbols.iter_mut()).find(|s| s.label == "I0.2").unwrap(); + s.tag = "-A3".into(); + s.label = "I0.0".into(); + let msgs: Vec = crate::reports::Analysis::build(&prj).issues.into_iter().map(|i| i.message).collect(); + assert!(msgs.iter().any(|m| m == "PLC address I0.0 used on several cards: -A1, -A3"), "{msgs:#?}"); +} diff --git a/src/production.rs b/src/production.rs new file mode 100644 index 00000000..2ab8ab4f --- /dev/null +++ b/src/production.rs @@ -0,0 +1,393 @@ +//! Production data of the panel layout (in the spirit of EPLAN Pro Panel): drilling +//! pattern and cutouts of the mounting plate and the door with NC export (DXF / CSV), +//! wire end treatment (stripping length, ferrules) and clearance checks. + +use crate::geom::{p, P, R}; +use crate::model::Project; +use crate::panel::{Enclosure, Face, ItemKind, PanelItem}; +use crate::parts::Part; +use std::fmt::Write; + +/// Rails: M5 holes 12.5 mm from the ends, at most every 200 mm. +pub const RAIL_HOLES: (f32, f32, &str) = (12.5, 200.0, "M5"); +/// Cable ducts: M4 holes 20 mm from the ends, at most every 300 mm. +pub const DUCT_HOLES: (f32, f32, &str) = (20.0, 300.0, "M4"); +/// Busbar holders: M6 holes 25 mm from the ends, at most every 250 mm. +pub const BUSBAR_HOLES: (f32, f32, &str) = (25.0, 250.0, "M6"); +/// Devices screwed onto the plate without mounting data: two M4 holes, 5 mm from +/// two opposite corners. +pub const DEVICE_HOLE_INSET: f32 = 5.0; +pub const BUSBAR_HOLDER: &str = "GEN.BB-HOLDER-3P"; + +/// Tap drill diameter of a metric thread (M3 … M10), or a plain diameter ("Ø4.5", +/// "4.5"). +pub fn drill_diameter(spec: &str) -> Option { + let s = spec.trim(); + let tap = match s.to_uppercase().as_str() { + "M3" => Some(2.5), + "M4" => Some(3.3), + "M5" => Some(4.2), + "M6" => Some(5.0), + "M8" => Some(6.8), + "M10" => Some(8.5), + _ => None, + }; + tap.or_else(|| s.trim_start_matches(['Ø', 'D', 'd']).trim().replace(',', ".").parse().ok()) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Hole { + pub item: u64, + /// Plate coordinates (origin top left, y down). + pub pos: P, + pub diameter: f32, + /// Thread to cut ("M5"), empty for through holes. + pub thread: String, +} + +/// Positions along a length: `end` from both ends and evenly spaced in between with +/// at most `pitch` distance. +pub fn line_positions(len: f32, end: f32, pitch: f32) -> Vec { + if len <= 2.0 * end + 1.0 { + return vec![len / 2.0]; + } + let span = len - 2.0 * end; + let n = (span / pitch).ceil().max(1.0) as usize; + (0..=n).map(|i| end + span * i as f32 / n as f32).collect() +} + +/// Mounting holes from the part data: `Mounting holes: M4: 5,5; 40,85` (positions +/// relative to the top left corner of the part, front view). +pub fn part_holes(part: &Part) -> Option<(String, Vec

)> { + let spec = part.tech_value("Mounting holes")?; + let (thread, list) = spec.split_once(':')?; + let pts: Vec

= list + .split(';') + .filter_map(|xy| { + let (x, y) = xy.split_once(',')?; + Some(p(x.trim().parse().ok()?, y.trim().parse().ok()?)) + }) + .collect(); + (!pts.is_empty()).then(|| (thread.trim().to_string(), pts)) +} + +fn hole(item: u64, pos: P, thread: &str) -> Hole { + let diameter = drill_diameter(thread).unwrap_or(4.2); + let is_thread = thread.trim().to_uppercase().starts_with('M'); + Hole { item, pos, diameter, thread: if is_thread { thread.trim().to_uppercase() } else { String::new() } } +} + +/// Holes of one item (devices on rails need none). +pub fn item_holes(it: &PanelItem, parts: &[Part]) -> Vec { + let along = |(end, pitch, thread): (f32, f32, &str)| { + let (a, _) = it.center_line(); + line_positions(it.length(), end, pitch) + .into_iter() + .map(|t| hole(it.id, if it.horizontal() { p(a.x + t, a.y) } else { p(a.x, a.y + t) }, thread)) + .collect::>() + }; + match it.kind { + ItemKind::Rail => along(RAIL_HOLES), + ItemKind::Duct => along(DUCT_HOLES), + ItemKind::Busbar => { + // Holders sit at the two outer bars; one hole each side of the system. + let (a, _) = it.center_line(); + let half = if it.horizontal() { it.h / 2.0 - 6.0 } else { it.w / 2.0 - 6.0 }; + let off = if it.horizontal() { p(0.0, half) } else { p(half, 0.0) }; + let mut v = Vec::new(); + for t in line_positions(it.length(), BUSBAR_HOLES.0, BUSBAR_HOLES.1) { + let c = if it.horizontal() { p(a.x + t, a.y) } else { p(a.x, a.y + t) }; + v.push(hole(it.id, c - off, BUSBAR_HOLES.2)); + v.push(hole(it.id, c + off, BUSBAR_HOLES.2)); + } + v + } + ItemKind::Device if it.z <= 0.01 => { + let part = parts.iter().find(|x| x.number == it.part); + match part.and_then(part_holes) { + Some((thread, pts)) => { + // Turned devices (width and height swapped) turn their pattern. + let pd = part.unwrap(); + let rotated = (pd.width - pd.height).abs() > 0.5 && (it.w - pd.height).abs() < 0.5 && (it.h - pd.width).abs() < 0.5; + pts.into_iter() + .map(|q| if rotated { p(it.x + pd.height - q.y, it.y + q.x) } else { p(it.x + q.x, it.y + q.y) }) + .map(|q| hole(it.id, q, &thread)) + .collect() + } + None if it.w > 2.0 * DEVICE_HOLE_INSET && it.h > 2.0 * DEVICE_HOLE_INSET => { + let i = DEVICE_HOLE_INSET; + vec![hole(it.id, p(it.x + i, it.y + i), "M4"), hole(it.id, p(it.x + it.w - i, it.y + it.h - i), "M4")] + } + None => Vec::new(), + } + } + ItemKind::Device | ItemKind::Cutout => Vec::new(), + } +} + +/// Drilling pattern of a mounting plate. +pub fn holes(e: &Enclosure, parts: &[Part]) -> Vec { + let mut v: Vec = e.items.iter().filter(|it| it.face == Face::Plate).flat_map(|it| item_holes(it, parts)).collect(); + v.sort_by(|a, b| a.pos.y.total_cmp(&b.pos.y).then(a.pos.x.total_cmp(&b.pos.x))); + v +} + +/// Material of busbar systems besides the bars: holders (one per hole pair). +pub fn busbar_holders(e: &Enclosure) -> usize { + e.items + .iter() + .filter(|i| i.kind == ItemKind::Busbar) + .map(|i| line_positions(i.length(), BUSBAR_HOLES.0, BUSBAR_HOLES.1).len()) + .sum() +} + +/// Number of parallel bars of a busbar system (part data `Bars: 3`). +pub fn bar_count(parts: &[Part], part: &str) -> usize { + parts + .iter() + .find(|x| x.number == part) + .and_then(|x| x.tech_value("Bars")) + .and_then(|v| v.parse().ok()) + .unwrap_or(3) + .clamp(1, 8) +} + +// ---------------------------------------------------------------------- cutouts + +/// Opening in the mounting plate or the door, in the coordinates of its face. +#[derive(Clone, Debug, PartialEq)] +pub struct Opening { + /// Cutout item, or the door device the opening is for. + pub item: u64, + pub center: P, + pub w: f32, + pub h: f32, + pub round: bool, +} + +/// Door cutout of a device: part data `Door cutout: Ø22.5` (round) or `92 x 92` +/// (rectangular); without data Ø22.5 for command and signal devices, otherwise the +/// device outline less 2 mm on each side. Returns (round, width, height). +pub fn door_cutout(part: Option<&Part>, it: &PanelItem) -> (bool, f32, f32) { + if let Some(spec) = part.and_then(|p| p.tech_value("Door cutout")) { + let s = spec.trim().trim_end_matches("mm").trim().replace(',', "."); + if let Some((w, h)) = s.split_once(['x', 'X', '×']) { + if let (Ok(w), Ok(h)) = (w.trim().parse::(), h.trim().parse::()) { + return (false, w, h); + } + } + if let Some(d) = drill_diameter(&s) { + return (true, d, d); + } + } + let command = part.map(|p| p.group == "Sensors, switches, pushbuttons" || p.group == "Signal devices").unwrap_or(false); + if command { + (true, 22.5, 22.5) + } else { + (false, (it.w - 4.0).max(1.0), (it.h - 4.0).max(1.0)) + } +} + +/// Openings of a face: cutout items and, on the door, one per door device. +pub fn openings(e: &Enclosure, parts: &[Part], face: Face) -> Vec { + let mut v = Vec::new(); + for it in e.items.iter().filter(|i| i.face == face) { + match it.kind { + ItemKind::Cutout => v.push(Opening { item: it.id, center: it.center(), w: it.w, h: it.h, round: it.round }), + ItemKind::Device if face == Face::Door => { + let (round, w, h) = door_cutout(parts.iter().find(|p| p.number == it.part), it); + v.push(Opening { item: it.id, center: it.center(), w, h, round }); + } + _ => {} + } + } + v +} + +// ---------------------------------------------------------------------- NC export + +fn csv_num(v: f32) -> String { + format!("{v:.1}") +} + +fn face_holes(e: &Enclosure, parts: &[Part], face: Face) -> Vec { + if face == Face::Plate { holes(e, parts) } else { Vec::new() } +} + +/// Drilling and cutout list of the mounting plate or the door for NC machines: +/// coordinates from the bottom left corner, y up. +pub fn nc_csv(prj: &Project, enc: usize, face: Face) -> String { + let e = &prj.layout.enclosures[enc]; + let (_, fh) = e.face_size(face); + let name = |id: u64| e.item(id).map(|i| if i.kind == ItemKind::Device { i.tag.clone() } else { i.kind.title().to_string() }).unwrap_or_default(); + let mut out = String::from("Enclosure;Face;Item;Operation;X;Y;Diameter;Thread;Width;Height\n"); + for h in face_holes(e, &prj.parts, face) { + let op = if h.thread.is_empty() { "Drill" } else { "Drill + tap" }; + let _ = writeln!(out, "{};{};{};{op};{};{};{};{};;", e.name, face.title(), name(h.item), csv_num(h.pos.x), csv_num(fh - h.pos.y), csv_num(h.diameter), h.thread); + } + for o in openings(e, &prj.parts, face) { + let (op, dia) = if o.round { ("Cutout round", csv_num(o.w)) } else { ("Cutout rectangular", String::new()) }; + let _ = writeln!(out, "{};{};{};{op};{};{};{dia};;{};{}", e.name, face.title(), name(o.item), csv_num(o.center.x), csv_num(fh - o.center.y), csv_num(o.w), csv_num(o.h)); + } + out +} + +/// Mounting plate or door as DXF for NC machines: outline, holes on one layer per +/// diameter (`HOLE_D4.2`), thread marks, cutouts; millimetres, origin bottom left. +pub fn nc_dxf(prj: &Project, enc: usize, face: Face) -> String { + let e = &prj.layout.enclosures[enc]; + let (fw, fh) = e.face_size(face); + let hs = face_holes(e, &prj.parts, face); + let mut diameters: Vec = Vec::new(); + for h in &hs { + if !diameters.iter().any(|d| (d - h.diameter).abs() < 0.01) { + diameters.push(h.diameter); + } + } + let hole_layer = |d: f32| format!("HOLE_D{d:.1}"); + let outline = if face == Face::Plate { "PLATE" } else { "DOOR" }; + let mut layers: Vec<(String, u8)> = vec![(outline.into(), 7), ("CUTOUT".into(), 1), ("THREAD".into(), 3)]; + layers.extend(diameters.iter().map(|d| (hole_layer(*d), 5))); + let mut out = String::new(); + crate::dxf::header(&mut out, &layers); + out.push_str("0\nSECTION\n2\nENTITIES\n"); + let pt = |out: &mut String, code: u16, q: P| { + let _ = write!(out, "{}\n{:.3}\n{}\n{:.3}\n{}\n0.0\n", code, q.x, code + 10, fh - q.y, code + 20); + }; + let rect = |out: &mut String, layer: &str, r: R| { + let _ = write!(out, "0\nPOLYLINE\n8\n{layer}\n66\n1\n70\n1\n10\n0.0\n20\n0.0\n30\n0.0\n"); + for q in [r.min, p(r.max.x, r.min.y), r.max, p(r.min.x, r.max.y)] { + let _ = write!(out, "0\nVERTEX\n8\n{layer}\n"); + pt(out, 10, q); + } + let _ = write!(out, "0\nSEQEND\n8\n{layer}\n"); + }; + let circle = |out: &mut String, layer: &str, c: P, r: f32| { + let _ = write!(out, "0\nCIRCLE\n8\n{layer}\n"); + pt(out, 10, c); + let _ = write!(out, "40\n{r:.3}\n"); + }; + rect(&mut out, outline, R::from_points(p(0.0, 0.0), p(fw, fh))); + for h in &hs { + circle(&mut out, &hole_layer(h.diameter), h.pos, h.diameter / 2.0); + if !h.thread.is_empty() { + // Thread marking: the nominal diameter on its own layer. + let nominal: f32 = h.thread.trim_start_matches('M').parse().unwrap_or(h.diameter); + circle(&mut out, "THREAD", h.pos, nominal / 2.0); + } + } + for o in openings(e, &prj.parts, face) { + if o.round { + circle(&mut out, "CUTOUT", o.center, o.w / 2.0); + } else { + let half = p(o.w / 2.0, o.h / 2.0); + rect(&mut out, "CUTOUT", R::from_points(o.center - half, o.center + half)); + } + } + out.push_str("0\nENDSEC\n0\nEOF\n"); + out +} + +// ---------------------------------------------------------------------- wire ends + +/// Cross-section in mm² from texts like "1.5 mm²", "2,5" or "0.75mm2". +pub fn cross_section_mm2(s: &str) -> Option { + let num: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || *c == '.' || *c == ',').collect(); + let v: f32 = num.replace(',', ".").parse().ok()?; + (v > 0.0).then_some(v) +} + +/// Wire end ferrule (DIN 46228-4 colour code). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ferrule { + pub cross_section: f32, + pub color: &'static str, + /// Sleeve length = stripping length. + pub length: f32, + pub part: &'static str, +} + +pub const FERRULES: [Ferrule; 10] = [ + Ferrule { cross_section: 0.34, color: "turquoise", length: 8.0, part: "GEN.FER-0.34" }, + Ferrule { cross_section: 0.5, color: "white", length: 8.0, part: "GEN.FER-0.5" }, + Ferrule { cross_section: 0.75, color: "grey", length: 8.0, part: "GEN.FER-0.75" }, + Ferrule { cross_section: 1.0, color: "red", length: 8.0, part: "GEN.FER-1.0" }, + Ferrule { cross_section: 1.5, color: "black", length: 8.0, part: "GEN.FER-1.5" }, + Ferrule { cross_section: 2.5, color: "blue", length: 8.0, part: "GEN.FER-2.5" }, + Ferrule { cross_section: 4.0, color: "grey", length: 10.0, part: "GEN.FER-4" }, + Ferrule { cross_section: 6.0, color: "yellow", length: 12.0, part: "GEN.FER-6" }, + Ferrule { cross_section: 10.0, color: "red", length: 12.0, part: "GEN.FER-10" }, + Ferrule { cross_section: 16.0, color: "blue", length: 12.0, part: "GEN.FER-16" }, +]; + +/// End treatment of a wire end: stripping length and ferrule. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EndTreatment { + pub strip: f32, + pub ferrule: Option, +} + +/// End treatment for a wire cross-section (None if it is unknown). +pub fn end_treatment(cross_section: &str, ferrules: bool) -> Option { + let cs = cross_section_mm2(cross_section)?; + let f = FERRULES.iter().find(|f| (f.cross_section - cs).abs() < 0.01).copied(); + match (ferrules, f) { + (true, Some(f)) => Some(EndTreatment { strip: f.length, ferrule: Some(f) }), + _ => Some(EndTreatment { strip: if cs <= 2.5 { 8.0 } else if cs <= 6.0 { 10.0 } else { 12.0 }, ferrule: None }), + } +} + +/// Ferrules needed for the routed wires of the panel: (part, count). +pub fn ferrule_material(prj: &Project, wiring: &[crate::panel::RoutedWire]) -> Vec<(&'static str, usize)> { + let mut v: Vec<(&'static str, usize)> = Vec::new(); + if !prj.layout.ferrules { + return v; + } + for w in wiring { + if let Some(f) = end_treatment(&w.cross_section, true).and_then(|t| t.ferrule) { + match v.iter_mut().find(|x| x.0 == f.part) { + Some(x) => x.1 += 2, + None => v.push((f.part, 2)), + } + } + } + v +} + +// ---------------------------------------------------------------------- clearance + +/// Free space a device needs above and below (part data `Clearance: 50`, mm). +pub fn part_clearance(parts: &[Part], part: &str) -> f32 { + parts.iter().find(|x| x.number == part).and_then(|x| x.tech_value("Clearance")).and_then(|v| v.trim_end_matches("mm").trim().parse().ok()).unwrap_or(0.0) +} + +/// Devices whose clearance zone (above and below, e.g. for cooling air) is occupied +/// by another item: (device, other item). +pub fn clearance_violations(e: &Enclosure, parts: &[Part]) -> Vec<(u64, u64)> { + let mut v = Vec::new(); + for dev in e.items.iter().filter(|i| i.kind == ItemKind::Device && i.face == Face::Plate) { + let c = part_clearance(parts, &dev.part); + if c <= 0.0 { + continue; + } + let zones = [ + R::from_points(p(dev.x, dev.y - c), p(dev.x + dev.w, dev.y)), + R::from_points(p(dev.x, dev.y + dev.h), p(dev.x + dev.w, dev.y + dev.h + c)), + ]; + for other in &e.items { + // The rail a device sits on and cutouts do not block the air flow. + if other.id == dev.id || other.face != Face::Plate || matches!(other.kind, ItemKind::Rail | ItemKind::Cutout) { + continue; + } + let r = other.rect(); + let eps = 0.01; + if zones.iter().any(|z| r.min.x < z.max.x - eps && z.min.x < r.max.x - eps && r.min.y < z.max.y - eps && z.min.y < r.max.y - eps) { + v.push((dev.id, other.id)); + } + } + } + v +} + +#[cfg(test)] +mod tests; diff --git a/src/production/tests.rs b/src/production/tests.rs new file mode 100644 index 00000000..997707f3 --- /dev/null +++ b/src/production/tests.rs @@ -0,0 +1,178 @@ +use super::*; +use crate::geom::p; +use crate::panel::{collisions, PanelItem}; +use crate::reports::Analysis; +use crate::sample::demo_project; + +fn item(id: u64, kind: ItemKind, x: f32, y: f32, w: f32, h: f32) -> PanelItem { + PanelItem { id, kind, x, y, w, h, d: 40.0, ..Default::default() } +} + +#[test] +fn drill_diameters() { + assert_eq!(drill_diameter("M5"), Some(4.2)); + assert_eq!(drill_diameter("m4"), Some(3.3)); + assert_eq!(drill_diameter("Ø4.5"), Some(4.5)); + assert_eq!(drill_diameter("6,6"), Some(6.6)); + assert_eq!(drill_diameter("M7"), None); +} + +#[test] +fn holes_along_profiles() { + let v = line_positions(1000.0, 12.5, 200.0); + assert_eq!(v.len(), 6); + assert_eq!((v[0], v[5]), (12.5, 987.5)); + assert!(v.windows(2).all(|w| w[1] - w[0] <= 200.0 + 1e-3)); + assert_eq!(line_positions(20.0, 12.5, 200.0), vec![10.0]); + // A horizontal rail: M5 holes on its centre line. + let rail = item(1, ItemKind::Rail, 10.0, 100.0, 400.0, 35.0); + let hs = item_holes(&rail, &[]); + assert!(hs.iter().all(|h| h.pos.y == 117.5 && h.thread == "M5" && h.diameter == 4.2)); + assert_eq!(hs.first().unwrap().pos.x, 22.5); + // Busbar systems: a pair of holder holes per position. + let bb = item(2, ItemKind::Busbar, 0.0, 300.0, 500.0, 75.0); + let hs = item_holes(&bb, &[]); + assert_eq!(hs.len(), 2 * line_positions(500.0, 25.0, 250.0).len()); + assert!(hs.iter().all(|h| h.thread == "M6")); + let e = Enclosure { items: vec![bb], ..Default::default() }; + assert_eq!(busbar_holders(&e), 3); +} + +#[test] +fn device_holes_from_part_data() { + let mut part = Part { number: "T".into(), width: 78.0, height: 84.0, ..Default::default() }; + // Devices on rails need no holes, devices on the plate two by default. + let mut dev = PanelItem { id: 1, kind: ItemKind::Device, part: "T".into(), x: 100.0, y: 50.0, w: 78.0, h: 84.0, z: 7.5, ..Default::default() }; + assert!(item_holes(&dev, std::slice::from_ref(&part)).is_empty()); + dev.z = 0.0; + let hs = item_holes(&dev, std::slice::from_ref(&part)); + assert_eq!(hs.iter().map(|h| h.pos).collect::>(), vec![p(105.0, 55.0), p(173.0, 129.0)]); + part.tech_data = "Mounting holes: M5: 9,12; 69,72".into(); + let hs = item_holes(&dev, std::slice::from_ref(&part)); + assert_eq!(hs.iter().map(|h| h.pos).collect::>(), vec![p(109.0, 62.0), p(169.0, 122.0)]); + assert!(hs.iter().all(|h| h.thread == "M5")); + // Turned by 90°: the pattern turns with the device. + dev.w = 84.0; + dev.h = 78.0; + let hs = item_holes(&dev, std::slice::from_ref(&part)); + assert_eq!(hs.iter().map(|h| h.pos).collect::>(), vec![p(100.0 + 84.0 - 12.0, 59.0), p(100.0 + 84.0 - 72.0, 119.0)]); + for h in &hs { + assert!(dev.rect().contains(h.pos)); + } +} + +#[test] +fn nothing_is_mounted_over_a_cutout() { + let mut cut = item(1, ItemKind::Cutout, 100.0, 100.0, 50.0, 50.0); + cut.z = -3.0; + cut.d = 3.0; + let on_plate = PanelItem { z: 0.0, ..item(2, ItemKind::Duct, 120.0, 0.0, 40.0, 300.0) }; + let above = PanelItem { z: 7.5, ..item(3, ItemKind::Device, 100.0, 100.0, 45.0, 70.0) }; + let e = Enclosure { items: vec![cut, on_plate, above], ..Default::default() }; + assert_eq!(collisions(&e, &[]), vec![(1, 2), (2, 3)]); +} + +#[test] +fn nc_export() { + let mut prj = demo_project(); + let e = &mut prj.layout.enclosures[0]; + let id = 9999; + e.items.push(PanelItem { id, kind: ItemKind::Cutout, x: 400.0, y: 600.0, w: 22.5, h: 22.5, round: true, ..Default::default() }); + let (_, ph) = e.plate_size(); + let csv = nc_csv(&prj, 0, Face::Plate); + let lines: Vec<&str> = csv.lines().collect(); + let n_holes = holes(&prj.layout.enclosures[0], &prj.parts).len(); + assert!(n_holes > 0); + assert_eq!(lines.len(), 1 + n_holes + 1); + // Coordinates from the bottom left corner of the plate. + let cut = lines.last().unwrap(); + assert!(cut.contains("Cutout round"), "{cut}"); + assert!(cut.contains(&format!(";{:.1};", ph - 611.25)), "{cut}"); + let dxf = nc_dxf(&prj, 0, Face::Plate); + assert!(dxf.contains("\nHOLE_D4.2\n") || dxf.contains("\nHOLE_D3.3\n")); + assert!(dxf.contains("\nCUTOUT\n")); + assert!(dxf.contains("\nPLATE\n")); + assert!(dxf.ends_with("EOF\n")); + assert_eq!(dxf.matches("0\nCIRCLE\n").count(), n_holes + holes(&prj.layout.enclosures[0], &prj.parts).iter().filter(|h| !h.thread.is_empty()).count() + 1); +} + +#[test] +fn wire_end_treatment() { + assert_eq!(cross_section_mm2("1.5 mm²"), Some(1.5)); + assert_eq!(cross_section_mm2("2,5mm2"), Some(2.5)); + assert_eq!(cross_section_mm2("AWG 14"), None); + let t = end_treatment("1.5 mm²", true).unwrap(); + assert_eq!((t.strip, t.ferrule.unwrap().color, t.ferrule.unwrap().part), (8.0, "black", "GEN.FER-1.5")); + assert_eq!(end_treatment("6 mm²", false).unwrap(), EndTreatment { strip: 10.0, ferrule: None }); + // Unusual cross-sections get a stripping length but no ferrule. + assert_eq!(end_treatment("1.2", true).unwrap().ferrule, None); + assert!(end_treatment("", true).is_none()); + // Every ferrule is in the catalog. + let catalog = crate::parts::catalog(); + for f in FERRULES { + assert!(catalog.iter().any(|p| p.number == f.part), "{}", f.part); + } +} + +#[test] +fn ferrules_in_wire_list_and_bom() { + let mut prj = demo_project(); + for w in prj.pages.iter_mut().flat_map(|pg| pg.wires.iter_mut()).filter(|w| w.cable.is_empty()) { + w.cross_section = "0.75 mm²".into(); + } + let an = Analysis::build(&prj); + assert!(!an.wiring.is_empty()); + let list = crate::reports::production_wire_list(&prj, &an); + let col = list.headers.iter().position(|h| *h == "Ferrule part").unwrap(); + assert!(list.rows.iter().any(|r| r[col] == "GEN.FER-0.75")); + // Routed (panel) wires come first. + let len = list.headers.iter().position(|h| *h == "Length (mm)").unwrap(); + let first_unrouted = list.rows.iter().position(|r| r[len].is_empty()).unwrap_or(list.rows.len()); + assert!(list.rows[first_unrouted..].iter().all(|r| r[len].is_empty())); + let bom = &an.reports[&crate::model::ReportKind::BillOfMaterials]; + let row = bom.rows.iter().find(|r| r[3] == "GEN.FER-0.75").expect("ferrules in the BOM"); + assert_eq!(row[1], (2 * an.wiring.iter().filter(|w| w.cross_section == "0.75 mm²").count()).to_string()); + assert!(!row[6].contains("not in project"), "described from the catalog"); + prj.layout.ferrules = false; + let an = Analysis::build(&prj); + assert!(!an.reports[&crate::model::ReportKind::BillOfMaterials].rows.iter().any(|r| r[3] == "GEN.FER-0.75")); +} + +#[test] +fn clearance_zones() { + let part = Part { number: "PS".into(), tech_data: "Clearance: 25 mm".into(), ..Default::default() }; + let parts = [part]; + assert_eq!(part_clearance(&parts, "PS"), 25.0); + let dev = PanelItem { part: "PS".into(), z: 7.5, ..item(1, ItemKind::Device, 100.0, 100.0, 40.0, 125.0) }; + let rail = item(2, ItemKind::Rail, 0.0, 145.0, 500.0, 35.0); + let duct_close = item(3, ItemKind::Duct, 0.0, 40.0, 500.0, 40.0); + let duct_far = item(4, ItemKind::Duct, 0.0, 300.0, 500.0, 40.0); + let e = Enclosure { items: vec![dev, rail, duct_close, duct_far], ..Default::default() }; + assert_eq!(clearance_violations(&e, &parts), vec![(1, 3)]); + assert!(crate::panel::problem_items(&e, &parts).contains(&3)); +} + +#[test] +fn door_cutouts_and_nc_data() { + let prj = demo_project(); + let e = &prj.layout.enclosures[0]; + let door = openings(e, &prj.parts, Face::Door); + // One cutout per door device: Ø22.5 for command and signal devices. + assert_eq!(door.len(), 6); + assert!(door.iter().all(|o| o.round && o.w == 22.5)); + // The door has no drilling pattern of the plate and vice versa. + assert!(openings(e, &prj.parts, Face::Plate).is_empty()); + let csv = nc_csv(&prj, 0, Face::Door); + assert_eq!(csv.lines().count(), 1 + 6); + assert!(csv.lines().skip(1).all(|l| l.contains(";Door;") && l.contains("Cutout round"))); + let dxf = nc_dxf(&prj, 0, Face::Door); + assert!(dxf.contains("\nDOOR\n") && !dxf.contains("HOLE_D")); + assert_eq!(dxf.matches("0\nCIRCLE\n").count(), 6); + // Part data overrides the default: rectangular cutout. + let part = Part { number: "D".into(), tech_data: "Door cutout: 92 x 68 mm".into(), ..Default::default() }; + let it = item(1, ItemKind::Device, 0.0, 0.0, 96.0, 72.0); + assert_eq!(door_cutout(Some(&part), &it), (false, 92.0, 68.0)); + let part = Part { number: "D".into(), tech_data: "Door cutout: Ø30.5".into(), ..Default::default() }; + assert_eq!(door_cutout(Some(&part), &it), (true, 30.5, 30.5)); + assert_eq!(door_cutout(None, &it), (false, 92.0, 68.0)); +} diff --git a/src/render.rs b/src/render.rs index e0a868b9..208ff04d 100644 --- a/src/render.rs +++ b/src/render.rs @@ -5,10 +5,11 @@ use crate::geom::{p, P, R}; use crate::index::{Index, Loc}; use crate::model::*; use crate::netlist; -use crate::panel::{self, Enclosure, ItemKind, PanelItem}; +use crate::panel::{self, Enclosure, Face, ItemKind, PanelItem}; use crate::parts::{Model2d, Part, Prim2d}; use crate::parts::{self, FnKind}; use crate::reports::Analysis; +use crate::{structure, wirenum}; use crate::symbols::{self, Anchor, ContactKind, FieldKind, Func, Prim, SymbolDef}; use std::collections::{BTreeSet, HashSet}; @@ -45,6 +46,19 @@ pub trait Draw { fn rect(&mut self, a: P, b: P, width: f32, ink: Ink, fill: bool) { self.poly(&[a, p(b.x, a.y), b, p(a.x, b.y)], true, width, ink, fill); } + /// Marks the area `min`..`max` as a link to another page (PDF export). + fn link(&mut self, _min: P, _max: P, _page: usize) {} +} + +/// Links the area of a text (estimated from its length) to a page. +fn link_text(d: &mut dyn Draw, pos: P, text: &str, size: f32, h: Anchor, page: usize) { + let w = text.chars().count() as f32 * size * 0.62; + let x0 = match h { + Anchor::Left => pos.x, + Anchor::Center => pos.x - w / 2.0, + Anchor::Right => pos.x - w, + }; + d.link(p(x0, pos.y - size * 0.7), p(x0 + w, pos.y + size * 0.7), page); } pub const SYMBOL_W: f32 = 0.25; @@ -57,6 +71,8 @@ pub struct Opts { pub selected: BTreeSet, pub highlight_wires: HashSet, pub show_pins: bool, + /// Revision marks for changes since the last revision are drawn unless hidden. + pub hide_revision_marks: bool, } /// Draws a complete page including frame and title block. @@ -65,7 +81,7 @@ pub fn draw_page(d: &mut dyn Draw, prj: &Project, idx: &Index, an: &Analysis, pa draw_frame(d, prj, page_i); match page.kind { PageKind::Cover => draw_cover(d, prj), - PageKind::Report(kind) => draw_report(d, an, kind), + PageKind::Report(kind) => draw_report(d, prj, an, kind), PageKind::Mounting(id) => draw_mounting_page(d, prj, id), PageKind::Schematic => {} } @@ -86,11 +102,18 @@ pub fn draw_page(d: &mut dyn Draw, prj: &Project, idx: &Index, an: &Analysis, pa for j in netlist::junctions(page) { d.circle(j, 0.7, 0.0, Ink::Wire, true); } + draw_wire_labels(d, prj, an, page_i); + let structured = !page.function.is_empty() || !page.location.is_empty(); for s in &page.symbols { let Some(def) = symbols::get(&s.sym) else { continue }; let ink = if opts.selected.contains(&s.id) { Ink::Selected } else { Ink::Line }; - draw_symbol(d, def, s, ink); - draw_annotations(d, prj, idx, def, s, ink); + if structured { + let shown = SymbolInst { tag: structure::relative(page, &s.tag), ..s.clone() }; + draw_symbol(d, def, &shown, ink); + } else { + draw_symbol(d, def, s, ink); + } + draw_annotations(d, prj, idx, page_i, def, s, ink); if opts.show_pins { for i in 0..def.pins.len() { d.circle(def.pin_world(i, s.pos, s.rot, s.mirror), 0.6, 0.15, Ink::Pin, false); @@ -103,6 +126,28 @@ pub fn draw_page(d: &mut dyn Draw, prj: &Project, idx: &Index, an: &Analysis, pa d.text(t.pos + p(0.0, i as f32 * t.size * 1.4), line, t.size, Anchor::Left, VAnchor::Middle, ink); } } + if !opts.hide_revision_marks { + draw_revision_marks(d, prj, an, page_i); + } +} + +/// Triangle with the upcoming revision index at every item changed since the last +/// revision (at the title block for changed page properties / new pages). +fn draw_revision_marks(d: &mut dyn Draw, prj: &Project, an: &Analysis, page_i: usize) { + let Some(pc) = an.changes.iter().find(|c| c.page == Some(page_i)) else { return }; + let name = crate::revision::next_name(prj); + let mut done: Vec<(i64, i64)> = Vec::new(); + for c in &pc.changes { + let at = if c.what == "Page" { p(203.0, 262.0) } else { c.pos + p(3.5, -3.5) }; + // One mark per spot (e.g. a moved wire split into several). + if done.contains(&at.key()) { + continue; + } + done.push(at.key()); + let ink = Ink::Highlight; + d.poly(&[at + p(0.0, -2.4), at + p(2.2, 1.4), at + p(-2.2, 1.4)], true, 0.2, ink, false); + d.text(at + p(0.0, 0.3), &name, 1.5, Anchor::Center, VAnchor::Middle, ink); + } } pub fn draw_shape(d: &mut dyn Draw, s: &Shape, ink: Ink) { @@ -120,9 +165,14 @@ pub fn draw_shape(d: &mut dyn Draw, s: &Shape, ink: Ink) { /// Draws only the symbol graphics (used for canvas, ghost and library previews). pub fn draw_symbol(d: &mut dyn Draw, def: &SymbolDef, s: &SymbolInst, ink: Ink) { + draw_prims(d, &def.prims, s, ink); +} + +/// Symbol graphics placed like the instance `s` (also used by the symbol editor). +pub fn draw_prims(d: &mut dyn Draw, prims: &[Prim], s: &SymbolInst, ink: Ink) { let tf = |q: P| s.pos + q.transform(s.rot, s.mirror); let text_ink = if ink == Ink::Line { Ink::Text } else { ink }; - for prim in &def.prims { + for prim in prims { match prim { Prim::Line { a, b, dashed } => d.line(tf(*a), tf(*b), SYMBOL_W, ink, *dashed), Prim::Poly { pts, closed, fill } => { @@ -171,8 +221,50 @@ fn find_inst<'a>(prj: &'a Project, loc: &Loc) -> Option<&'a SymbolInst> { prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id) } +/// Text beside a wire at fraction `t` of its length: left of vertical wires, above +/// horizontal ones (`below`: right of / below the wire). +fn wire_text(d: &mut dyn Draw, w: &Wire, t: f32, text: &str, below: bool, ink: Ink) { + let q = p(w.a.x + (w.b.x - w.a.x) * t, w.a.y + (w.b.y - w.a.y) * t); + if (w.b.x - w.a.x).abs() < (w.b.y - w.a.y).abs() { + let (dx, anchor) = if below { (1.2, Anchor::Left) } else { (-0.8, Anchor::Right) }; + d.text(p(q.x + dx, q.y), text, SMALL_SIZE, anchor, VAnchor::Middle, ink); + } else if below { + d.text(p(q.x, q.y + 2.8), text, SMALL_SIZE, Anchor::Center, VAnchor::Bottom, ink); + } else { + d.text(p(q.x, q.y - 0.6), text, SMALL_SIZE, Anchor::Center, VAnchor::Bottom, ink); + } +} + +/// Wire numbers (once per connection and page, on its longest wire) and cable cores +/// (a stroke across the wire, the core and once per page the cable tag). +fn draw_wire_labels(d: &mut dyn Draw, prj: &Project, an: &Analysis, page_i: usize) { + let page = &prj.pages[page_i]; + for net in &an.open.nets { + let Some(w) = wirenum::label_wire(page, page_i, net) else { continue }; + let number = wirenum::number_of(prj, net); + if !number.is_empty() { + // Cable cores are labelled at 30 % of the wire. + let t = if w.cable.is_empty() { 0.5 } else { 0.72 }; + wire_text(d, w, t, &number, false, Ink::Text); + } + } + let mut cabled: Vec<&Wire> = page.wires.iter().filter(|w| !w.cable.is_empty()).collect(); + cabled.sort_by(|a, b| a.a.x.min(a.b.x).total_cmp(&b.a.x.min(b.b.x)).then(a.a.y.total_cmp(&b.a.y))); + let mut tagged: Vec<&str> = Vec::new(); + for w in cabled { + let t = 0.3; + let q = p(w.a.x + (w.b.x - w.a.x) * t, w.a.y + (w.b.y - w.a.y) * t); + d.line(q + p(-1.0, 0.8), q + p(1.0, -0.8), SYMBOL_W, Ink::Line, false); + if !tagged.contains(&w.cable.as_str()) { + tagged.push(&w.cable); + wire_text(d, w, t, &structure::relative(page, &w.cable), false, Ink::CrossRef); + } + wire_text(d, w, t, &w.core, true, Ink::CrossRef); + } +} + /// Device tag, function text, connection point designations and cross references. -pub fn draw_annotations(d: &mut dyn Draw, prj: &Project, idx: &Index, def: &SymbolDef, s: &SymbolInst, ink: Ink) { +pub fn draw_annotations(d: &mut dyn Draw, prj: &Project, idx: &Index, page_i: usize, def: &SymbolDef, s: &SymbolInst, ink: Ink) { let text_ink = if ink == Ink::Line { Ink::Text } else { ink }; let bounds = def.world_bounds(s.pos, s.rot, s.mirror); let vertical = s.rot.is_multiple_of(2); @@ -197,26 +289,33 @@ pub fn draw_annotations(d: &mut dyn Draw, prj: &Project, idx: &Index, def: &Symb } // Cross references - let mut refs: Vec = Vec::new(); + let mut refs: Vec<(String, Option)> = Vec::new(); let dev = idx.devices.get(&s.tag); match def.func { Func::Aux(_) => match dev.map(|d| d.mains.as_slice()) { - Some([]) | None => refs.push("?".into()), - Some(mains) => refs.extend(mains.iter().map(|m| m.reference(prj))), + Some([]) | None => refs.push(("?".into(), None)), + Some(mains) => refs.extend(mains.iter().map(|m| (m.reference_from(prj, page_i), Some(m.page)))), }, + Func::Overview => { + if let Some(dev) = dev { + refs.extend(dev.mains.iter().map(|m| (m.reference_from(prj, page_i), Some(m.page)))); + } + } Func::Main { mirror: false } => { if let Some(dev) = dev { - refs.extend(dev.auxs.iter().map(|a| a.reference(prj))); + refs.extend(dev.auxs.iter().map(|a| (a.reference_from(prj, page_i), Some(a.page)))); } } Func::Interruption => { if let Some(locs) = idx.interruptions.get(&s.label) { - let others: Vec = - locs.iter().filter(|l| l.sym_id != s.id).map(|l| l.reference(prj)).collect(); - let q = s.pos + p(2.2, 1.6).transform(s.rot, s.mirror); - let txt = if others.is_empty() { "?".to_string() } else { others.join(" ") }; + let others: Vec<&Loc> = locs.iter().filter(|l| l.sym_id != s.id).collect(); + let q = s.pos + p(2.2, 1.6).transform(s.rot, s.mirror) + p(0.0, 2.6); + let txt = if others.is_empty() { "?".to_string() } else { others.iter().map(|l| l.reference_from(prj, page_i)).collect::>().join(" ") }; let ink = if others.is_empty() { Ink::Error } else { Ink::CrossRef }; - d.text(q + p(0.0, 2.6), &txt, SMALL_SIZE, Anchor::Left, VAnchor::Middle, ink); + d.text(q, &txt, SMALL_SIZE, Anchor::Left, VAnchor::Middle, ink); + if let Some(l) = others.first() { + link_text(d, q, &txt, SMALL_SIZE, Anchor::Left, l.page); + } } } _ => {} @@ -224,52 +323,55 @@ pub fn draw_annotations(d: &mut dyn Draw, prj: &Project, idx: &Index, def: &Symb // Tag block if def.show_tag { - let mut lines: Vec<(String, f32, Ink)> = Vec::new(); + let mut lines: Vec<(String, f32, Ink, Option)> = Vec::new(); if !s.tag.is_empty() { - lines.push((s.tag.clone(), TAG_SIZE, text_ink)); + lines.push((structure::relative(&prj.pages[page_i], &s.tag), TAG_SIZE, text_ink, None)); } if !s.function_text.is_empty() { for l in s.function_text.lines() { - lines.push((l.to_string(), 2.0, text_ink)); + lines.push((l.to_string(), 2.0, text_ink, None)); } } - for r in refs { + for (r, target) in refs { let ink = if r == "?" { Ink::Error } else { Ink::CrossRef }; - lines.push((r, 2.0, ink)); + lines.push((r, 2.0, ink, target)); } let total: f32 = lines.iter().map(|l| l.1 * 1.35).sum(); - if vertical { - let x = bounds.min.x - 1.2; - let mut y = bounds.center().y - total / 2.0; - for (t, size, ink) in &lines { - d.text(p(x, y + size * 0.675), t, *size, Anchor::Right, VAnchor::Middle, *ink); - y += size * 1.35; - } + let (x, mut y, anchor) = if vertical { + (bounds.min.x - 1.2, bounds.center().y - total / 2.0, Anchor::Right) } else { - let x = bounds.center().x; - let mut y = bounds.min.y - 1.0 - total; - for (t, size, ink) in &lines { - d.text(p(x, y + size * 0.675), t, *size, Anchor::Center, VAnchor::Middle, *ink); - y += size * 1.35; + (bounds.center().x, bounds.min.y - 1.0 - total, Anchor::Center) + }; + for (t, size, ink, target) in &lines { + let q = p(x, y + size * 0.675); + d.text(q, t, *size, anchor, VAnchor::Middle, *ink); + if let Some(page) = target { + link_text(d, q, t, *size, anchor, *page); } + y += size * 1.35; } } // Contact image (mirror) below coils if matches!(def.func, Func::Main { mirror: true }) { if let Some(dev) = dev { - draw_contact_image(d, prj, &s.tag, dev.auxs.as_slice(), &bounds, vertical, text_ink); + draw_contact_image(d, prj, page_i, &s.tag, dev.auxs.as_slice(), &bounds, vertical, text_ink); } } } -fn draw_contact_image(d: &mut dyn Draw, prj: &Project, tag: &str, auxs: &[Loc], bounds: &R, vertical: bool, ink: Ink) { +/// Contact image row: kind, connection designations, cross reference and its page +/// (None = reserve contact). +type ContactRow = (ContactKind, Vec, Option<(String, usize)>); + +#[allow(clippy::too_many_arguments)] +fn draw_contact_image(d: &mut dyn Draw, prj: &Project, page_i: usize, tag: &str, auxs: &[Loc], bounds: &R, vertical: bool, ink: Ink) { // Rows: contact kind, connection designations, cross reference (None = reserve). - let mut rows: Vec<(ContactKind, Vec, Option)> = Vec::new(); + let mut rows: Vec = Vec::new(); for loc in auxs { let (Some(def), Some(inst)) = (find_symbol(prj, loc), find_inst(prj, loc)) else { continue }; let kind = def.contact_kind().unwrap_or(ContactKind::No); - rows.push((kind, inst.pins.clone(), Some(loc.reference(prj)))); + rows.push((kind, inst.pins.clone(), Some((loc.reference_from(prj, page_i), loc.page)))); } // Unused contacts of the assigned parts (function templates) are shown as reserve. for f in parts::reserve_functions(prj, None, tag) { @@ -312,7 +414,10 @@ fn draw_contact_image(d: &mut dyn Draw, prj: &Project, tag: &str, auxs: &[Loc], d.text(p(cx + 3.6, y), &right, SMALL_SIZE, Anchor::Left, VAnchor::Middle, text_ink); let rx = (cx + 4.2 + right.chars().count() as f32 * SMALL_SIZE * 0.6).max(cx + 7.5); match reference { - Some(r) => d.text(p(rx, y), &r, SMALL_SIZE, Anchor::Left, VAnchor::Middle, Ink::CrossRef), + Some((r, page)) => { + d.text(p(rx, y), &r, SMALL_SIZE, Anchor::Left, VAnchor::Middle, Ink::CrossRef); + link_text(d, p(rx, y), &r, SMALL_SIZE, Anchor::Left, page); + } None => d.text(p(rx, y), "reserve", SMALL_SIZE * 0.9, Anchor::Left, VAnchor::Middle, Ink::FrameText), } y += 3.0; @@ -369,52 +474,8 @@ pub fn draw_frame(d: &mut dyn Draw, prj: &Project, page_i: usize) { } fn draw_title_block(d: &mut dyn Draw, prj: &Project, page_i: usize) { - let page = &prj.pages[page_i]; - let info = &prj.info; - let fi = Ink::Frame; - let (y0, y1) = (TITLE_Y0, FRAME_Y1); - let ym = (y0 + y1) / 2.0; - d.line(p(FRAME_X0, y0), p(FRAME_X1, y0), 0.5, fi, false); - let cols = [FRAME_X0, 90.0, 150.0, 210.0, 330.0, 370.0, FRAME_X1]; - for &x in &cols[1..cols.len() - 1] { - d.line(p(x, y0), p(x, y1), 0.25, fi, false); - } - for (x0, x1) in [(90.0, 150.0), (150.0, 210.0), (330.0, 370.0), (370.0, FRAME_X1)] { - d.line(p(x0, ym), p(x1, ym), 0.25, fi, false); - } - let lbl = |d: &mut dyn Draw, x: f32, y: f32, t: &str| { - d.text(p(x + 1.0, y + 1.8), t, 1.6, Anchor::Left, VAnchor::Middle, Ink::FrameText) - }; - let val = |d: &mut dyn Draw, x: f32, y: f32, t: &str, size: f32| { - d.text(p(x + 2.0, y), t, size, Anchor::Left, VAnchor::Middle, Ink::Text) - }; - lbl(d, FRAME_X0, y0, "Company"); - val(d, FRAME_X0, ym + 2.0, &info.company, 4.0); - lbl(d, 90.0, y0, "Date"); - val(d, 90.0, y0 + 9.0, &info.date, 2.5); - lbl(d, 90.0, ym, "Creator"); - val(d, 90.0, ym + 9.0, &info.creator, 2.5); - lbl(d, 150.0, y0, "Revision"); - val(d, 150.0, y0 + 9.0, &info.revision, 2.5); - lbl(d, 150.0, ym, "Software"); - val(d, 150.0, ym + 9.0, "OpenECraft", 2.5); - lbl(d, 210.0, y0, "Project / page description"); - val(d, 210.0, y0 + 9.0, &info.name, 3.5); - val(d, 210.0, y0 + 21.0, &page.description, 3.0); - lbl(d, 330.0, y0, "Page"); - val(d, 330.0, y0 + 9.5, &page.name, 4.0); - lbl(d, 330.0, ym, "Type"); - let kind = match page.kind { - PageKind::Schematic => "Schematic", - PageKind::Cover => "Cover", - PageKind::Report(_) => "Report", - PageKind::Mounting(_) => "Mounting", - }; - val(d, 330.0, ym + 9.0, kind, 2.5); - lbl(d, 370.0, y0, "Sheet"); - val(d, 370.0, y0 + 9.5, &format!("{} / {}", page_i + 1, prj.pages.len()), 3.5); - lbl(d, 370.0, ym, "Project"); - val(d, 370.0, ym + 9.0, &info.name, 2.2); + let form = crate::forms::title_block(prj, page_i); + crate::forms::draw(d, &form, prj, page_i); } fn draw_cover(d: &mut dyn Draw, prj: &Project) { @@ -442,31 +503,41 @@ fn draw_cover(d: &mut dyn Draw, prj: &Project) { pub const REPORT_ROWS_PER_PAGE: usize = 40; -fn draw_report(d: &mut dyn Draw, an: &Analysis, kind: ReportKind) { +fn draw_report(d: &mut dyn Draw, prj: &Project, an: &Analysis, kind: ReportKind) { let Some(table) = an.reports.get(&kind) else { return }; - d.text(p(22.0, 24.0), kind.title(), 6.0, Anchor::Left, VAnchor::Middle, Ink::Text); + let form = prj.forms.reports.get(&kind); + let title = form.map(|f| f.title.as_str()).filter(|t| !t.is_empty()).unwrap_or(kind.title()); + d.text(p(22.0, 24.0), title, 6.0, Anchor::Left, VAnchor::Middle, Ink::Text); + let cols = crate::forms::report_columns(form, &table.headers); + let per_page = form.map(|f| f.rows).filter(|r| *r > 0).unwrap_or(REPORT_ROWS_PER_PAGE); let (x0, x1) = (22.0, 400.0); - let total_w: f32 = table.widths.iter().sum(); + let total_w: f32 = cols.iter().map(|&c| table.widths[c]).sum(); let mut xs = vec![x0]; - for w in &table.widths { - xs.push(xs.last().unwrap() + w / total_w * (x1 - x0)); + for &c in &cols { + xs.push(xs.last().unwrap() + table.widths[c] / total_w * (x1 - x0)); } - let row_h = 5.0; + // Rows get lower (and their text smaller) when more of them must fit. + let row_h = (5.0f32).min((TITLE_Y0 - 12.0 - 39.0) / per_page as f32).max(2.0); + let k = row_h / 5.0; let mut y = 34.0; - for (i, h) in table.headers.iter().enumerate() { - d.text(p(xs[i] + 1.2, y + row_h / 2.0), h, 2.4, Anchor::Left, VAnchor::Middle, Ink::Text); + for (i, &c) in cols.iter().enumerate() { + d.text(p(xs[i] + 1.2, y + 2.5), table.headers[c], 2.4, Anchor::Left, VAnchor::Middle, Ink::Text); } - y += row_h; + y += 5.0; d.line(p(x0, y), p(x1, y), 0.5, Ink::Frame, false); - for row in table.rows.iter().take(REPORT_ROWS_PER_PAGE) { - for (i, cell) in row.iter().enumerate() { - let maxc = ((xs[i + 1] - xs[i]) / (2.2 * 0.6)) as usize; + for (row, target) in table.rows.iter().zip(&table.targets).take(per_page) { + if let Some((page, _)) = target { + d.link(p(x0, y), p(x1, y + row_h), *page); + } + for (i, &c) in cols.iter().enumerate() { + let cell = row.get(c).map(String::as_str).unwrap_or(""); + let maxc = ((xs[i + 1] - xs[i]) / (2.2 * k * 0.6)) as usize; let txt: String = if cell.chars().count() > maxc && maxc > 1 { cell.chars().take(maxc - 1).collect::() + "…" } else { - cell.clone() + cell.to_string() }; - d.text(p(xs[i] + 1.2, y + row_h / 2.0), &txt, 2.2, Anchor::Left, VAnchor::Middle, Ink::Text); + d.text(p(xs[i] + 1.2, y + row_h / 2.0), &txt, 2.2 * k, Anchor::Left, VAnchor::Middle, Ink::Text); } y += row_h; d.line(p(x0, y), p(x1, y), 0.1, Ink::Frame, false); @@ -475,8 +546,8 @@ fn draw_report(d: &mut dyn Draw, an: &Analysis, kind: ReportKind) { d.line(p(*x, 34.0), p(*x, y), 0.15, Ink::Frame, false); } d.rect(p(x0, 34.0), p(x1, y), 0.3, Ink::Frame, false); - if table.rows.len() > REPORT_ROWS_PER_PAGE { - let more = format!("… {} more rows – see Reports window / CSV export", table.rows.len() - REPORT_ROWS_PER_PAGE); + if table.rows.len() > per_page { + let more = format!("… {} more rows – see Reports window / CSV export", table.rows.len() - per_page); d.text(p(x0, y + 5.0), &more, 2.5, Anchor::Left, VAnchor::Middle, Ink::FrameText); } if table.rows.is_empty() { @@ -486,29 +557,48 @@ fn draw_report(d: &mut dyn Draw, an: &Analysis, kind: ReportKind) { // ---------------------------------------------------------------------- panel layout -/// Draws an enclosure with its mounting plate in front view. `origin` is the page -/// position of the enclosure's top left corner, `k` the scale (page mm per real mm). +/// Draws an enclosure in front view: its mounting plate or its door (seen from the +/// front). `origin` is the page position of the enclosure's top left corner, `k` the +/// scale (page mm per real mm). +#[allow(clippy::too_many_arguments)] pub fn draw_enclosure( d: &mut dyn Draw, e: &Enclosure, + face: Face, origin: P, k: f32, selected: &BTreeSet, problems: &BTreeSet, parts: &[Part], ) { - let tf = |x: f32, y: f32| origin + p((x + panel::PLATE_MARGIN) * k, (y + panel::PLATE_MARGIN) * k); + let m = face.origin(); + let tf = |x: f32, y: f32| origin + p((x + m) * k, (y + m) * k); d.rect(origin, origin + p(e.width * k, e.height * k), 0.5, Ink::Line, false); - let (pw, ph) = e.plate_size(); - d.rect(tf(0.0, 0.0), tf(pw, ph), 0.0, Ink::Plate, true); - d.rect(tf(0.0, 0.0), tf(pw, ph), 0.25, Ink::Frame, false); - // Rails first, then ducts, devices on top. - let mut items: Vec<&PanelItem> = e.items.iter().collect(); - items.sort_by_key(|i| match i.kind { - ItemKind::Rail => 0, - ItemKind::Duct => 1, - ItemKind::Device => 2, - }); + match face { + Face::Plate => { + let (pw, ph) = e.plate_size(); + d.rect(tf(0.0, 0.0), tf(pw, ph), 0.0, Ink::Plate, true); + d.rect(tf(0.0, 0.0), tf(pw, ph), 0.25, Ink::Frame, false); + } + Face::Door => { + // Door frame, hinges on the left, handle on the right. + let f = panel::DOOR_FRAME; + let (a, b) = (tf(f, f), tf(e.width - f, e.height - f)); + for (s, t) in [(a, p(b.x, a.y)), (p(b.x, a.y), b), (b, p(a.x, b.y)), (p(a.x, b.y), a)] { + d.line(s, t, 0.15, Ink::Frame, true); + } + for y in [0.15, 0.85] { + let hy = e.height * y; + d.rect(tf(-3.0, hy - 25.0), tf(3.0, hy + 25.0), 0.25, Ink::Frame, false); + } + let hy = e.height / 2.0; + d.rect(tf(e.width - 32.0, hy - 50.0), tf(e.width - 14.0, hy + 50.0), 0.0, Ink::Fill, true); + d.rect(tf(e.width - 32.0, hy - 50.0), tf(e.width - 14.0, hy + 50.0), 0.25, Ink::Line, false); + } + } + // Cutouts first, then rails, ducts, busbars, devices on top. + let mut items: Vec<&PanelItem> = e.items.iter().filter(|i| i.face == face).collect(); + items.sort_by_key(|i| i.kind.layer()); for it in items { let ink = if selected.contains(&it.id) { Ink::Selected @@ -559,6 +649,39 @@ pub fn draw_enclosure( t += 10.0; } } + ItemKind::Busbar => { + d.rect(a, b, 0.0, Ink::Plate, true); + d.rect(a, b, 0.2, ink, false); + // The bars, evenly spaced across the system. + let n = crate::production::bar_count(parts, &it.part); + let across = if horizontal { it.h } else { it.w }; + let pitch = across / n as f32; + for k in 0..n { + let off = pitch * (k as f32 + 0.5); + let half = (pitch * 0.18).min(3.0); + let (r0, r1) = if horizontal { + (tf(it.x, it.y + off - half), tf(it.x + it.w, it.y + off + half)) + } else { + (tf(it.x + off - half, it.y), tf(it.x + off + half, it.y + it.h)) + }; + d.rect(r0, r1, 0.0, Ink::Fill, true); + d.rect(r0, r1, 0.15, ink, false); + } + } + ItemKind::Cutout => { + let line_ink = if ink == Ink::Line { Ink::Frame } else { ink }; + if it.round { + let c = tf(it.x + it.w / 2.0, it.y + it.h / 2.0); + d.circle(c, it.w / 2.0 * k, 0.3, ink, false); + let r = it.w / 2.0 * k * std::f32::consts::FRAC_1_SQRT_2; + d.line(c + p(-r, -r), c + p(r, r), 0.12, line_ink, false); + d.line(c + p(-r, r), c + p(r, -r), 0.12, line_ink, false); + } else { + d.rect(a, b, 0.3, ink, false); + d.line(a, b, 0.12, line_ink, false); + d.line(p(a.x, b.y), p(b.x, a.y), 0.12, line_ink, false); + } + } ItemKind::Device => { d.rect(a, b, 0.0, Ink::Fill, true); let model = parts.iter().find(|x| x.number == it.part).and_then(|x| x.model_2d.as_ref()); @@ -580,6 +703,31 @@ pub fn draw_enclosure( } } } + // Door cutouts of the door devices (dashed: under the device) + if face == Face::Door { + for o in crate::production::openings(e, parts, face).iter().filter(|o| e.item(o.item).map(|i| i.kind == ItemKind::Device).unwrap_or(false)) { + let c = tf(o.center.x, o.center.y); + if o.round { + d.circle(c, o.w / 2.0 * k, 0.15, Ink::Frame, false); + } else { + let half = p(o.w / 2.0 * k, o.h / 2.0 * k); + let (a, b) = (c - half, c + half); + for (s, t) in [(a, p(b.x, a.y)), (p(b.x, a.y), b), (b, p(a.x, b.y)), (p(a.x, b.y), a)] { + d.line(s, t, 0.15, Ink::Frame, true); + } + } + } + return; + } + // Drilling pattern (holes hidden under other devices are left out) + for h in crate::production::holes(e, parts) { + let covered = e.items.iter().any(|i| i.kind == ItemKind::Device && i.face == Face::Plate && i.id != h.item && i.rect().contains(h.pos)); + if covered { + continue; + } + let c = tf(h.pos.x, h.pos.y); + d.circle(c, (h.diameter / 2.0 * k).max(0.25), 0.1, Ink::Frame, false); + } } /// Draws a part's 2D front view into a placed device. Rotated devices (width and @@ -643,11 +791,21 @@ fn draw_mounting_page(d: &mut dyn Draw, prj: &Project, id: u64) { return; }; let (x0, y0, x1, y1) = (AREA_X0 + 25.0, AREA_Y0 + 12.0, FRAME_X1 - 15.0, TITLE_Y0 - 22.0); - let n = drawing_scale((e.width, e.height), (x1 - x0, y1 - y0)); + // With door devices the door is drawn to the right of the mounting plate. + let door = e.items.iter().any(|i| i.face == Face::Door); + let gap = if door { e.width * 0.25 } else { 0.0 }; + let total_w = if door { 2.0 * e.width + gap } else { e.width }; + let n = drawing_scale((total_w, e.height), (x1 - x0, y1 - y0)); let k = 1.0 / n; let (w, h) = (e.width * k, e.height * k); - let origin = p(x0 + ((x1 - x0) - w) / 2.0, y0 + ((y1 - y0) - h) / 2.0); - draw_enclosure(d, e, origin, k, &BTreeSet::new(), &BTreeSet::new(), &prj.parts); + let origin = p(x0 + ((x1 - x0) - total_w * k) / 2.0, y0 + ((y1 - y0) - h) / 2.0); + draw_enclosure(d, e, Face::Plate, origin, k, &BTreeSet::new(), &BTreeSet::new(), &prj.parts); + if door { + let o = origin + p(w + gap * k, 0.0); + draw_enclosure(d, e, Face::Door, o, k, &BTreeSet::new(), &BTreeSet::new(), &prj.parts); + d.text(p(origin.x + w / 2.0, origin.y - 3.0), "Mounting plate", 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); + d.text(p(o.x + w / 2.0, o.y - 3.0), "Door (front view)", 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); + } // Dimensions let bottom = origin.y + h + 6.0; d.line(p(origin.x, bottom), p(origin.x + w, bottom), 0.18, Ink::Frame, false); diff --git a/src/reports.rs b/src/reports.rs index 4b0b3247..c77099a7 100644 --- a/src/reports.rs +++ b/src/reports.rs @@ -3,7 +3,7 @@ use crate::index::Index; use crate::panel::{self, ItemKind, OpenWire, RoutedWire}; use crate::model::*; -use crate::netlist::{pin_designation, Netlist, PinRef}; +use crate::netlist::{connections, pin_designation, Connection, Netlist, PinRef}; use crate::symbols::{self, Func}; use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -67,10 +67,17 @@ pub struct Issue { #[derive(Default)] pub struct Analysis { pub netlist: Netlist, + /// Netlist with the terminal sides apart: one net per physical connection + /// (wire numbers, cables). + pub open: Netlist, pub reports: HashMap, pub issues: Vec, /// Virtual wiring of the panel layout. pub wiring: Vec, + /// Changes since the last revision (revision marks). + pub changes: Vec, + /// Point-to-point connections. + pub connections: Vec, } impl Analysis { @@ -78,25 +85,38 @@ impl Analysis { let idx = Index::build(prj); let netlist = Netlist::build(prj, true); let open = Netlist::build(prj, false); - let (wiring, open_wires) = panel::virtual_wiring(prj, &netlist); + let (wiring, open_wires) = panel::virtual_wiring(prj, &netlist, &open); + let conns = connections(prj, &netlist, &open); let mut reports = HashMap::new(); for k in ReportKind::ALL { let t = match k { ReportKind::TableOfContents => toc(prj), ReportKind::DeviceList => device_list(prj, &idx), - ReportKind::BillOfMaterials => bom(prj, &idx), + ReportKind::BillOfMaterials => bom(prj, &idx, &wiring), ReportKind::TerminalDiagram => terminal_diagram(prj, &netlist, &open), - ReportKind::ConnectionList => connection_list(prj, &netlist), + ReportKind::ConnectionList => connection_list(prj, &conns), ReportKind::PlcAssignment => plc_list(prj, &netlist), + ReportKind::RevisionOverview => revision_overview(prj), ReportKind::PotentialList => potential_list(prj, &netlist), ReportKind::PanelWiring => panel_wiring(prj, &wiring, &open_wires), + ReportKind::CableOverview => cable_overview(prj, &conns), + ReportKind::CableDiagram => cable_diagram(prj, &conns), + ReportKind::HarnessData => Table::default(), }; reports.insert(k, t); } let mut issues = check(prj, &idx, &netlist); issues.extend(check_layout(prj)); + issues.extend(check_wires(prj, &netlist, &open)); + issues.extend(check_strips_and_plc(prj, &netlist)); issues.sort_by_key(|i| i.severity); - Analysis { netlist, reports, issues, wiring } + let changes = crate::revision::pending(prj); + let mut an = Analysis { netlist, open, reports, issues, wiring, changes, connections: conns }; + // Harness data needs the connections and the routed lengths. + an.reports.insert(ReportKind::HarnessData, harness_data(prj, &an)); + an.issues.extend(check_harnesses(prj, &an)); + an.issues.sort_by_key(|i| i.severity); + an } } @@ -127,7 +147,7 @@ fn device_list(prj: &Project, idx: &Index) -> Table { ]); for tag in idx.sorted_tags() { let dev = &idx.devices[tag]; - let first = dev.mains.first().or(dev.others.first()).or(dev.auxs.first()).copied(); + let first = dev.mains.first().or(dev.others.first()).or(dev.auxs.first()).or(dev.overviews.first()).copied(); let Some(loc) = first else { continue }; let inst = prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id); let (name, ftext) = inst @@ -172,7 +192,7 @@ fn device_list(prj: &Project, idx: &Index) -> Table { t } -fn bom(prj: &Project, idx: &Index) -> Table { +fn bom(prj: &Project, idx: &Index, wiring: &[RoutedWire]) -> Table { let mut t = Table::new(&[ ("Pos", 0.5), ("Qty", 0.6), @@ -206,7 +226,8 @@ fn bom(prj: &Project, idx: &Index) -> Table { .unwrap_or(false) }) .count(); - let per_device = if dev.mains.is_empty() && terminals > 0 { terminals } else { 1 }; + let spares = prj.strips.get(tag).map(|d| d.spares as usize).unwrap_or(0); + let per_device = if dev.mains.is_empty() && terminals > 0 { terminals + spares } else { 1 }; for r in &data.parts { let g = groups.entry(r.number.clone()).or_default(); g.0 += (per_device * r.count.max(1) as usize) as f32; @@ -215,15 +236,35 @@ fn bom(prj: &Project, idx: &Index) -> Table { } } } - // Enclosures, rails and ducts of the panel layout. + // Finished harnesses per piece. + for h in prj.harnesses.iter().filter(|h| !h.part.is_empty()) { + let g = groups.entry(h.part.clone()).or_default(); + g.0 += 1.0; + g.1.push(h.tag.clone()); + } + // Cables by length (or piece without length). + for c in prj.cables.iter().filter(|c| !c.part.is_empty()) { + let g = groups.entry(c.part.clone()).or_default(); + g.0 += if c.length > 0.0 { c.length } else { 1.0 }; + g.1.push(c.tag.clone()); + } + // Enclosures, rails, ducts and busbars of the panel layout. for (part, qty, used) in panel::layout_material(prj) { let g = groups.entry(part).or_default(); g.0 += qty; g.1.extend(used); } + // Ferrules of the routed panel wiring. + for (part, n) in crate::production::ferrule_material(prj, wiring) { + let g = groups.entry(part.to_string()).or_default(); + g.0 += n as f32; + g.1.push("wiring".into()); + } + // Wiring and mounting material may come straight from the built-in catalog. + let catalog = crate::parts::catalog(); let mut sum = 0.0; for (i, (part, (qty, tags))) in groups.iter().enumerate() { - let pd = prj.parts.iter().find(|p| &p.number == part).cloned().unwrap_or_else(|| Part { + let pd = prj.parts.iter().chain(catalog.iter()).find(|p| &p.number == part).cloned().unwrap_or_else(|| Part { description: "(part not in project – synchronize parts)".into(), ..Default::default() }); @@ -258,6 +299,7 @@ fn bom(prj: &Project, idx: &Index) -> Table { fn panel_wiring(prj: &Project, wiring: &[RoutedWire], open: &[OpenWire]) -> Table { let mut t = Table::new(&[ ("Enclosure", 0.8), + ("Wire no.", 0.7), ("From", 1.4), ("To", 1.4), ("Potential", 0.9), @@ -272,6 +314,7 @@ fn panel_wiring(prj: &Project, wiring: &[RoutedWire], open: &[OpenWire]) -> Tabl t.push( vec![ prj.layout.enclosures[w.enclosure].name.clone(), + w.number.clone(), w.from.clone(), w.to.clone(), w.net.clone(), @@ -284,14 +327,14 @@ fn panel_wiring(prj: &Project, wiring: &[RoutedWire], open: &[OpenWire]) -> Tabl ); } if !wiring.is_empty() { - let mut last = vec![String::new(); 8]; - last[5] = "Total".into(); - last[6] = format!("{total:.0}"); + let mut last = vec![String::new(); 9]; + last[6] = "Total".into(); + last[7] = format!("{total:.0}"); t.push(last, None); } for w in open { t.push( - vec![String::new(), w.from.clone(), w.to.clone(), w.net.clone(), String::new(), String::new(), "–".into(), w.reason.into()], + vec![String::new(), String::new(), w.from.clone(), w.to.clone(), w.net.clone(), String::new(), String::new(), "–".into(), w.reason.into()], None, ); } @@ -312,7 +355,7 @@ fn check_layout(prj: &Project) -> Vec { let name = |id: u64| { e.item(id).map(|i| if i.kind == ItemKind::Device { i.tag.clone() } else { i.kind.title().to_string() }).unwrap_or_default() }; - for (a, b) in panel::collisions(e) { + for (a, b) in panel::collisions(e, &prj.parts) { v.push(Issue { severity: Severity::Warning, message: format!("{}: {} collides with {}", e.name, name(a), name(b)), target: None }); } for id in panel::outside(e) { @@ -322,82 +365,62 @@ fn check_layout(prj: &Project) -> Vec { target: None, }); } + for (a, b) in crate::production::clearance_violations(e, &prj.parts) { + v.push(Issue { + severity: Severity::Warning, + message: format!("{}: {} is inside the required clearance of {}", e.name, name(b), name(a)), + target: None, + }); + } } v } -fn targets(prj: &Project, nl: &Netlist, net: Option, exclude: (usize, usize)) -> String { - let Some(ni) = net else { return String::new() }; - let mut v: Vec = nl.nets[ni] - .pins - .iter() - .filter(|p| (p.page, p.sym) != exclude) - .map(|p| pin_designation(prj, *p)) - .collect(); - v.sort_by(|a, b| natural_cmp(a, b)); - v.dedup(); - v.join(", ") -} - -/// (sort key 1, sort key 2, remaining cells, jump target) -type SortRow = (String, String, Vec, (usize, u64)); - fn terminal_diagram(prj: &Project, nl: &Netlist, open: &Netlist) -> Table { let mut t = Table::new(&[ ("Strip", 0.8), - ("Terminal", 0.8), + ("Terminal", 0.7), + ("Jumper", 0.5), ("External (top)", 3.0), ("Internal (bottom)", 3.0), ("Potential", 1.0), ("Location", 0.8), ("Function text", 1.6), ]); - let mut rows: Vec = Vec::new(); - for (pi, pg) in prj.pages.iter().enumerate() { - for (si, s) in pg.symbols.iter().enumerate() { - let Some(def) = symbols::get(&s.sym) else { continue }; - if def.func != Func::Terminal { - continue; - } - let top = targets(prj, open, open.pin_net.get(&(s.id, 0)).copied(), (pi, si)); - let bot = targets(prj, open, open.pin_net.get(&(s.id, 1)).copied(), (pi, si)); - let pot = nl.pin_net.get(&(s.id, 0)).map(|&n| nl.nets[n].name.clone()).unwrap_or_default(); - rows.push(( - s.tag.clone(), - s.label.clone(), - vec![top, bot, pot, loc_str(prj, pi, s.pos), s.function_text.replace('\n', " ")], - (pi, s.id), - )); - } - } - rows.sort_by(|a, b| natural_cmp(&a.0, &b.0).then_with(|| natural_cmp(&a.1, &b.1))); - for (strip, num, rest, target) in rows { - let mut r = vec![strip, num]; - r.extend(rest); - t.push(r, Some(target)); + for strip in crate::strips::strip_tags(prj) { + for r in crate::strips::rows(prj, &strip, nl, open) { + let target = r.terminal.as_ref().map(|t| (t.page, t.id)); + let jumper = if r.jumper > 0 { r.jumper.to_string() } else { String::new() }; + t.push(vec![strip.clone(), r.label, jumper, r.external, r.internal, r.potential, r.location, r.function_text], target); + } } t } - -fn connection_list(prj: &Project, nl: &Netlist) -> Table { +fn connection_list(prj: &Project, conns: &[Connection]) -> Table { let mut t = Table::new(&[ + ("Wire no.", 0.8), ("Potential", 1.0), ("From", 1.6), ("To", 1.6), ("Page", 0.8), ("Colour", 0.8), ("Cross-section", 1.0), + ("Cable", 1.0), + ("Core", 0.6), ]); - for c in crate::netlist::connections(prj, nl) { + for c in conns { let s = &prj.pages[c.a.page].symbols[c.a.sym]; t.push( vec![ + c.number.clone(), c.net.clone(), pin_designation(prj, c.a), pin_designation(prj, c.b), loc_str(prj, c.a.page, s.pos), c.color.clone(), c.cross_section.clone(), + c.cable.clone(), + c.core.clone(), ], Some((c.a.page, s.id)), ); @@ -405,6 +428,186 @@ fn connection_list(prj: &Project, nl: &Netlist) -> Table { t } +/// Device of a connection end (`-X1:3` → `-X1`). +fn device_of(prj: &Project, pin: PinRef) -> String { + prj.pages[pin.page].symbols[pin.sym].tag.clone() +} + +/// Connections of a cable, oriented alike: the end at the device where the first +/// connection starts comes first. +fn cable_connections(prj: &Project, conns: &[Connection], cable: &str) -> Vec { + let mut v: Vec = conns.iter().filter(|c| c.cable == cable).cloned().collect(); + if let Some(first) = v.first() { + let (from, to) = (device_of(prj, first.a), device_of(prj, first.b)); + for c in &mut v { + if device_of(prj, c.b) == from || device_of(prj, c.a) == to { + std::mem::swap(&mut c.a, &mut c.b); + } + } + } + v +} + +fn sorted_cables(prj: &Project) -> Vec<&Cable> { + let mut v: Vec<&Cable> = prj.cables.iter().collect(); + v.sort_by(|a, b| natural_cmp(&a.tag, &b.tag)); + v +} + +fn cable_overview(prj: &Project, conns: &[Connection]) -> Table { + let mut t = Table::new(&[ + ("Cable", 1.0), + ("Type", 1.6), + ("Cores used", 0.8), + ("Cross-section", 0.9), + ("Length (m)", 0.8), + ("From", 1.6), + ("To", 1.6), + ("Part number", 1.4), + ("Description", 2.0), + ]); + for cable in sorted_cables(prj) { + let used = cable_connections(prj, conns, &cable.tag); + let ends = |f: fn(&Connection) -> PinRef| { + let mut v: Vec = used.iter().map(|c| device_of(prj, f(c))).collect(); + v.sort_by(|a, b| natural_cmp(a, b)); + v.dedup(); + v.join(", ") + }; + let cores: BTreeSet<&str> = used.iter().map(|c| c.core.as_str()).collect(); + let target = used.first().map(|c| (c.a.page, prj.pages[c.a.page].symbols[c.a.sym].id)); + t.push( + vec![ + cable.tag.clone(), + cable.cable_type.clone(), + format!("{}/{}", cores.len(), cable.core_list().len()), + cable.cross_section.clone(), + if cable.length > 0.0 { format!("{}", cable.length) } else { String::new() }, + ends(|c| c.a), + ends(|c| c.b), + cable.part.clone(), + cable.description.clone(), + ], + target, + ); + } + t +} + +fn cable_diagram(prj: &Project, conns: &[Connection]) -> Table { + let mut t = Table::new(&[ + ("Cable", 1.0), + ("Core", 0.6), + ("From", 1.6), + ("To", 1.6), + ("Potential", 1.0), + ("Wire no.", 0.8), + ("Cross-section", 0.9), + ]); + for cable in sorted_cables(prj) { + let used = cable_connections(prj, conns, &cable.tag); + let mut cores = cable.core_list(); + // Cores in use that the cable does not list (shown by the project check). + for c in &used { + if !cores.contains(&c.core) { + cores.push(c.core.clone()); + } + } + for core in cores { + let on_core: Vec<&Connection> = used.iter().filter(|c| c.core == core).collect(); + if on_core.is_empty() { + t.push(vec![cable.tag.clone(), core.clone(), "reserve".into(), String::new(), String::new(), String::new(), cable.cross_section.clone()], None); + } + for c in on_core { + let cs = if c.cross_section.is_empty() { cable.cross_section.clone() } else { c.cross_section.clone() }; + t.push( + vec![ + cable.tag.clone(), + core.clone(), + pin_designation(prj, c.a), + pin_designation(prj, c.b), + c.net.clone(), + c.number.clone(), + cs, + ], + Some((c.a.page, prj.pages[c.a.page].symbols[c.a.sym].id)), + ); + } + } + } + t +} + +/// Cable assignments, wire numbers and device tags. +fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { + let mut v = Vec::new(); + let mut issue = |severity, message: String, target| v.push(Issue { severity, message, target }); + let mut tags: HashMap<&str, usize> = HashMap::new(); + for c in &prj.cables { + *tags.entry(c.tag.as_str()).or_default() += 1; + if c.tag.trim().is_empty() { + issue(Severity::Error, "Cable without tag".into(), None); + } + } + for (tag, n) in tags.iter().filter(|(t, n)| **n > 1 && !t.is_empty()) { + issue(Severity::Error, format!("Cable {tag} defined {n} times"), None); + } + // Cable cores: known cable, listed core, one connection per core. + let mut core_use: BTreeMap<(String, String), Vec> = BTreeMap::new(); + for (ni, net) in open.nets.iter().enumerate() { + for (pi, id) in &net.wires { + let Some(w) = prj.pages[*pi].wires.iter().find(|w| w.id == *id) else { continue }; + if w.cable.is_empty() { + continue; + } + let at = Some((*pi, w.id)); + match prj.cable(&w.cable) { + None => issue(Severity::Error, format!("Wire assigned to unknown cable {}", w.cable), at), + Some(_) if w.core.is_empty() => issue(Severity::Warning, format!("{}: wire without core designation", w.cable), at), + Some(c) if !c.core_list().contains(&w.core) => { + issue(Severity::Warning, format!("{}: core {} is not a core of the cable ({})", w.cable, w.core, c.cores), at) + } + Some(_) => {} + } + let users = core_use.entry((w.cable.clone(), w.core.clone())).or_default(); + if !users.contains(&ni) { + users.push(ni); + } + } + } + for ((cable, core), nets) in &core_use { + if nets.len() > 1 && !core.is_empty() { + let at = open.nets[nets[1]].wires.first().copied(); + issue(Severity::Error, format!("{cable}: core {core} used for {} connections", nets.len()), at); + } + } + // Wire numbers: one per connection, not shared by different potentials. + let mut by_number: BTreeMap> = BTreeMap::new(); + for net in &open.nets { + let numbers = crate::wirenum::numbers_of(prj, net); + let at = net.wires.first().copied(); + if numbers.len() > 1 { + issue(Severity::Warning, format!("Different wire numbers in one connection: {}", numbers.join(", ")), at); + } + let potential = net.pins.first().and_then(|p| nl.pin_net.get(&(prj.pages[p.page].symbols[p.sym].id, p.pin)).copied()); + if let (Some(n), Some(pot)) = (numbers.first(), potential) { + by_number.entry(n.clone()).or_default().insert(pot); + } + } + for (number, pots) in by_number.iter().filter(|(_, p)| p.len() > 1) { + issue(Severity::Warning, format!("Wire number {number} is used for {} different potentials", pots.len()), None); + } + // Device tags need a device name after the structure. + for (pi, pg) in prj.pages.iter().enumerate() { + for s in pg.symbols.iter().filter(|s| !s.tag.is_empty()) { + if crate::structure::Dt::parse(&s.tag).name.is_empty() { + issue(Severity::Error, format!("{}: device tag without device name", s.tag), Some((pi, s.id))); + } + } + } + v +} + fn plc_list(prj: &Project, nl: &Netlist) -> Table { let mut t = Table::new(&[ ("PLC card", 1.0), @@ -414,31 +617,162 @@ fn plc_list(prj: &Project, nl: &Netlist) -> Table { ("Connected to", 3.0), ("Location", 0.8), ]); - let mut rows = Vec::new(); - for (pi, pg) in prj.pages.iter().enumerate() { - for (si, s) in pg.symbols.iter().enumerate() { - if symbols::get(&s.sym).map(|d| d.func) != Some(Func::Plc) { - continue; - } - let kind = if s.sym == "plc_in" { "DI" } else { "DO" }; - let to = targets(prj, nl, nl.pin_net.get(&(s.id, 0)).copied(), (pi, si)); - rows.push(( - s.tag.clone(), - s.label.clone(), - vec![kind.to_string(), s.function_text.replace('\n', " "), to, loc_str(prj, pi, s.pos)], - (pi, s.id), - )); - } - } - rows.sort_by(|a, b| natural_cmp(&a.0, &b.0).then_with(|| natural_cmp(&a.1, &b.1))); - for (card, addr, rest, target) in rows { - let mut r = vec![card, addr]; - r.extend(rest); - t.push(r, Some(target)); + for p in crate::plc::points(prj, nl) { + let kind = if p.input { "DI" } else { "DO" }; + t.push(vec![p.card, p.address, kind.into(), p.function_text, p.connected, p.location], Some((p.page, p.id))); + } + t +} + +fn revision_overview(prj: &Project) -> Table { + let since = prj.revisions.last().map(|r| r.name.as_str()).unwrap_or("-"); + let mut t = Table::new(&[("Page", 0.8), ("Change", 0.8), ("Item", 0.8), (if since.is_empty() { "Description" } else { "Description (since last revision)" }, 3.0)]); + for (page, kind, what, label, target) in crate::revision::overview(prj) { + t.push(vec![page, kind, what, label], target); + } + t +} + +/// Wire list for production (wire processing machines): one row per connection +/// with wire number, ends, colour, cross-section, the routed length if the devices +/// are placed in the panel layout, end treatment (stripping length, ferrule) and +/// cable core. Panel wires come first, sorted by cross-section, colour and length +/// (machine batches). +pub fn production_wire_list(prj: &Project, an: &Analysis) -> Table { + let mut t = Table::new(&[ + ("Wire no.", 0.8), + ("From", 1.6), + ("To", 1.6), + ("Colour", 0.7), + ("Cross-section", 0.9), + ("Length (mm)", 0.9), + ("Strip (mm)", 0.7), + ("Ferrule", 1.6), + ("Ferrule part", 1.0), + ("Cable", 0.8), + ("Core", 0.6), + ("Potential", 1.0), + ]); + // (routed length, cells, jump target) + type Row = (Option, Vec, Option<(usize, u64)>); + let mut rows: Vec = Vec::new(); + for c in &an.connections { + let (from, to) = (pin_designation(prj, c.a), pin_designation(prj, c.b)); + let length = an.wiring.iter().find(|w| (w.from == from && w.to == to) || (w.from == to && w.to == from)).map(|w| w.length); + let end = crate::production::end_treatment(&c.cross_section, prj.layout.ferrules); + // Cable cores are processed with their cable, not as single wires. + let end = if c.cable.is_empty() { end } else { None }; + let ferrule = end.and_then(|e| e.ferrule); + let target = Some((c.a.page, prj.pages[c.a.page].symbols[c.a.sym].id)); + rows.push(( + length, + vec![ + c.number.clone(), + from, + to, + c.color.clone(), + c.cross_section.clone(), + length.map(|l| format!("{l:.0}")).unwrap_or_default(), + end.map(|e| format!("{:.0}", e.strip)).unwrap_or_default(), + ferrule.map(|f| format!("{} mm² {}, {:.0} mm", f.cross_section, f.color, f.length)).unwrap_or_default(), + ferrule.map(|f| f.part.to_string()).unwrap_or_default(), + c.cable.clone(), + c.core.clone(), + c.net.clone(), + ], + target, + )); + } + let cs = |r: &Vec| crate::production::cross_section_mm2(&r[4]).unwrap_or(0.0); + rows.sort_by(|a, b| { + b.0.is_some() + .cmp(&a.0.is_some()) + .then(cs(&a.1).total_cmp(&cs(&b.1))) + .then(a.1[3].cmp(&b.1[3])) + .then(a.0.unwrap_or(0.0).total_cmp(&b.0.unwrap_or(0.0))) + }); + for (_, row, target) in rows { + t.push(row, target); } t } +/// Harness data: per harness its wires with lengths and end treatment, and a +/// summary row (wires, connectors, total length, bundle diameter). +fn harness_data(prj: &Project, an: &Analysis) -> Table { + let mut t = Table::new(&[ + ("Harness", 0.9), + ("Wire no.", 0.7), + ("From", 1.4), + ("To", 1.4), + ("Colour", 0.6), + ("Cross-section", 0.9), + ("Length (mm)", 0.8), + ("End treatment", 1.6), + ]); + for h in &prj.harnesses { + let ws = crate::harness::wires(prj, an, &h.tag); + for w in &ws { + let end = crate::production::end_treatment(&w.cross_section, prj.layout.ferrules) + .map(|e| match e.ferrule { + Some(f) => format!("strip {:.0} mm, ferrule {} mm² {}", e.strip, f.cross_section, f.color), + None => format!("strip {:.0} mm", e.strip), + }) + .unwrap_or_default(); + let length = if w.length > 0.0 { format!("{:.0}{}", w.length, if w.routed { "" } else { " *" }) } else { "?".into() }; + let fmt = |e: &(String, String)| if e.1.is_empty() { e.0.clone() } else { format!("{}:{}", e.0, e.1) }; + t.push(vec![h.tag.clone(), w.number.clone(), fmt(&w.from), fmt(&w.to), w.color.clone(), w.cross_section.clone(), length, end], w.target); + } + let total: f32 = ws.iter().map(|w| w.length).sum(); + let summary = format!( + "{} wires, {} connectors, Ø {:.1} mm", + ws.len(), + crate::harness::connectors(&ws).len(), + crate::harness::bundle_diameter(&ws) + ); + t.push(vec![h.tag.clone(), String::new(), summary, String::new(), String::new(), "Total".into(), format!("{total:.0}"), h.description.clone()], None); + } + t +} + +/// Assigned connections that no longer exist, harnesses without wires. +fn check_harnesses(prj: &Project, an: &Analysis) -> Vec { + let mut v = Vec::new(); + for (tag, [a, b]) in crate::harness::stale(prj, an) { + v.push(Issue { severity: Severity::Warning, message: format!("Harness {tag}: connection {a} – {b} does not exist in the schematic"), target: None }); + } + for h in &prj.harnesses { + if !an.connections.iter().any(|c| c.harness == h.tag) { + v.push(Issue { severity: Severity::Info, message: format!("Harness {} has no wires", h.tag), target: None }); + } + } + v +} + +/// Jumpers on missing terminals, PLC addresses used on several cards. +fn check_strips_and_plc(prj: &Project, nl: &Netlist) -> Vec { + let mut v = Vec::new(); + for (strip, data) in &prj.strips { + let labels: Vec = crate::strips::terminals(prj, strip).into_iter().map(|t| t.label).collect(); + for (label, j) in data.jumpers.iter().filter(|(_, j)| **j > 0) { + if !labels.contains(label) { + v.push(Issue { severity: Severity::Warning, message: format!("{strip}: jumper {j} on terminal {label}, which is not placed"), target: None }); + } + } + } + for (addr, points) in crate::plc::duplicate_addresses(prj, nl) { + let mut cards: Vec<&str> = points.iter().map(|p| p.card.as_str()).collect(); + cards.dedup(); + if cards.len() > 1 { + v.push(Issue { + severity: Severity::Error, + message: format!("PLC address {addr} used on several cards: {}", cards.join(", ")), + target: Some((points[1].page, points[1].id)), + }); + } + } + v +} fn potential_list(prj: &Project, nl: &Netlist) -> Table { let mut t = Table::new(&[("Potential", 1.0), ("Connection points", 4.0), ("Pages", 1.5)]); let mut nets: Vec<_> = nl.nets.iter().filter(|n| n.named).collect(); @@ -561,3 +895,6 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { v.sort_by_key(|i| i.severity); v } + +#[cfg(test)] +mod tests; diff --git a/src/reports/tests.rs b/src/reports/tests.rs new file mode 100644 index 00000000..adca5a40 --- /dev/null +++ b/src/reports/tests.rs @@ -0,0 +1,83 @@ +use super::*; +use crate::sample::demo_project; + +fn row<'a>(t: &'a Table, first: &str) -> Vec<&'a Vec> { + t.rows.iter().filter(|r| r[0] == first).collect() +} + +#[test] +fn cable_reports_of_the_demo() { + let prj = demo_project(); + let an = Analysis::build(&prj); + let overview = &an.reports[&ReportKind::CableOverview]; + let w1 = row(overview, "-W1"); + assert_eq!(w1.len(), 1); + assert_eq!(w1[0][2], "4/4"); + assert_eq!((w1[0][4].as_str(), w1[0][5].as_str(), w1[0][6].as_str()), ("15", "-X1", "-M1")); + + let diagram = &an.reports[&ReportKind::CableDiagram]; + let cores: Vec<(&str, &str, &str)> = row(diagram, "-W1").iter().map(|r| (r[1].as_str(), r[2].as_str(), r[3].as_str())).collect(); + assert_eq!(cores, vec![("BN", "-X1:1", "-M1:U1"), ("BK", "-X1:2", "-M1:V1"), ("GY", "-X1:3", "-M1:W1"), ("GNYE", "-X1:PE", "-M1:PE")]); + assert!(row(diagram, "-W1").iter().all(|r| !r[5].is_empty()), "wire numbers"); + + // Connection list: wire numbers and cable cores, terminal sides apart. + let conns = &an.reports[&ReportKind::ConnectionList]; + let motor = conns.rows.iter().find(|r| r[3] == "-M1:U1").unwrap(); + assert_eq!((motor[2].as_str(), motor[7].as_str(), motor[8].as_str()), ("-X1:1", "-W1", "BN")); + assert!(conns.rows.iter().all(|r| !r[0].is_empty()), "every connection is numbered"); + assert!(conns.rows.iter().all(|r| r[2] != r[3]), "no connection from a terminal to itself"); + + // The cable is in the bill of materials by length. + let bom = &an.reports[&ReportKind::BillOfMaterials]; + let cable = bom.rows.iter().find(|r| r[3] == "GEN.CBL-4G1.5").unwrap(); + assert_eq!((cable[1].as_str(), cable[2].as_str(), cable[7].as_str()), ("15", "m", "-W1")); +} + +fn messages(prj: &Project) -> Vec { + Analysis::build(prj).issues.into_iter().map(|i| i.message).collect() +} + +fn find<'a>(msgs: &'a [String], part: &str) -> Option<&'a String> { + msgs.iter().find(|m| m.contains(part)) +} + +#[test] +fn cable_assignments_are_checked() { + let mut prj = demo_project(); + let page = prj.pages.iter().position(|p| p.name == "2").unwrap(); + let cabled: Vec = prj.pages[page].wires.iter().enumerate().filter(|(_, w)| w.cable == "-W1").map(|(i, _)| i).collect(); + // Same core on two connections, a core the cable does not have, an unknown cable. + prj.pages[page].wires[cabled[1]].core = "BN".into(); + prj.pages[page].wires[cabled[2]].core = "RD".into(); + prj.pages[page].wires[cabled[3]].cable = "-W7".into(); + let msgs = messages(&prj); + assert!(find(&msgs, "-W1: core BN used for 2 connections").is_some(), "{msgs:#?}"); + assert!(find(&msgs, "core RD is not a core of the cable").is_some(), "{msgs:#?}"); + assert!(find(&msgs, "unknown cable -W7").is_some(), "{msgs:#?}"); + prj.cables.push(prj.cables[0].clone()); + assert!(find(&messages(&prj), "Cable -W1 defined 2 times").is_some()); +} + +#[test] +fn wire_numbers_and_tags_are_checked() { + let mut prj = demo_project(); + let open = Netlist::build(&prj, false); + let bridged = Netlist::build(&prj, true); + let numbered: Vec<&crate::netlist::Net> = open.nets.iter().filter(|n| n.wires.len() > 1 && !n.pins.is_empty()).collect(); + // Two numbers in one connection + let (pi, id) = numbered[0].wires[0]; + prj.pages[pi].wires.iter_mut().find(|w| w.id == id).unwrap().number = "X99".into(); + assert!(find(&messages(&prj), "Different wire numbers in one connection").is_some()); + // The same number on two potentials + let pot = |n: &crate::netlist::Net| { + let p = n.pins[0]; + bridged.pin_net[&(prj.pages[p.page].symbols[p.sym].id, p.pin)] + }; + let other = open.nets.iter().find(|n| !n.wires.is_empty() && !n.pins.is_empty() && pot(n) != pot(numbered[1])).unwrap().clone(); + let number = crate::wirenum::number_of(&prj, numbered[1]); + crate::wirenum::set(&mut prj, &other, &number, true); + assert!(find(&messages(&prj), &format!("Wire number {number} is used for 2 different potentials")).is_some()); + // A tag without device name + prj.pages[2].symbols[0].tag = "=A1".into(); + assert!(find(&messages(&prj), "=A1: device tag without device name").is_some()); +} diff --git a/src/revision.rs b/src/revision.rs new file mode 100644 index 00000000..c020c98d --- /dev/null +++ b/src/revision.rs @@ -0,0 +1,185 @@ +//! Revision management: a revision stores a snapshot of all pages; changes made +//! since the last revision are listed and marked on the pages. Released pages are +//! locked against changes. + +use crate::geom::{p, P}; +use crate::model::{natural_cmp, Page, Project}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +/// Pages of a revision. Shared, so that undo snapshots of the project stay cheap. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(transparent)] +pub struct Snapshot(pub Arc>); + +impl PartialEq for Snapshot { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) || self.0 == other.0 + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Revision { + /// Revision index, e.g. "A", "B" or "01". + pub name: String, + pub date: String, + pub author: String, + pub description: String, + pub pages: Snapshot, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ChangeKind { + Added, + Removed, + Modified, +} + +impl ChangeKind { + pub fn title(self) -> &'static str { + match self { + ChangeKind::Added => "added", + ChangeKind::Removed => "removed", + ChangeKind::Modified => "changed", + } + } +} + +/// One changed item of a page. +#[derive(Clone, Debug, PartialEq)] +pub struct Change { + pub kind: ChangeKind, + /// "Symbol", "Wire", "Text", "Graphic" or "Page". + pub what: &'static str, + pub id: u64, + pub label: String, + /// Where to put the revision mark. + pub pos: P, +} + +/// Changes of one page (by page id; `page` is the current index if it still exists). +#[derive(Clone, Debug, PartialEq)] +pub struct PageChanges { + pub page_id: u64, + pub page: Option, + pub name: String, + pub changes: Vec, +} + +fn diff( + old: &[T], + new: &[T], + id: impl Fn(&T) -> u64, + what: &'static str, + describe: impl Fn(&T) -> (String, P), + out: &mut Vec, +) { + for n in new { + match old.iter().find(|o| id(o) == id(n)) { + None => { + let (label, pos) = describe(n); + out.push(Change { kind: ChangeKind::Added, what, id: id(n), label, pos }); + } + Some(o) if o != n => { + let (label, pos) = describe(n); + out.push(Change { kind: ChangeKind::Modified, what, id: id(n), label, pos }); + } + Some(_) => {} + } + } + for o in old.iter().filter(|o| !new.iter().any(|n| id(n) == id(o))) { + let (label, pos) = describe(o); + out.push(Change { kind: ChangeKind::Removed, what, id: id(o), label, pos }); + } +} + +fn mid(a: P, b: P) -> P { + p((a.x + b.x) / 2.0, (a.y + b.y) / 2.0) +} + +/// Item level differences between two page lists (matched by page and item ids). +pub fn compare(old: &[Page], new: &[Page]) -> Vec { + let mut out = Vec::new(); + for (i, n) in new.iter().enumerate() { + let mut changes = Vec::new(); + match old.iter().find(|o| o.id == n.id) { + None => changes.push(Change { kind: ChangeKind::Added, what: "Page", id: n.id, label: n.description.clone(), pos: p(0.0, 0.0) }), + Some(o) => { + if (&o.name, &o.description, &o.function, &o.location, o.kind) != (&n.name, &n.description, &n.function, &n.location, n.kind) { + changes.push(Change { kind: ChangeKind::Modified, what: "Page", id: n.id, label: "page properties".into(), pos: p(0.0, 0.0) }); + } + diff(&o.symbols, &n.symbols, |s| s.id, "Symbol", |s| (format!("{} {}", s.tag, s.label).trim().to_string(), s.pos), &mut changes); + diff(&o.wires, &n.wires, |w| w.id, "Wire", |w| (w.number.clone(), mid(w.a, w.b)), &mut changes); + diff(&o.texts, &n.texts, |t| t.id, "Text", |t| (t.text.lines().next().unwrap_or("").to_string(), t.pos), &mut changes); + diff(&o.shapes, &n.shapes, |s| s.id, "Graphic", |s| (String::new(), mid(s.a, s.b)), &mut changes); + } + } + if !changes.is_empty() { + out.push(PageChanges { page_id: n.id, page: Some(i), name: n.name.clone(), changes }); + } + } + for o in old.iter().filter(|o| !new.iter().any(|n| n.id == o.id)) { + let removed = Change { kind: ChangeKind::Removed, what: "Page", id: o.id, label: o.description.clone(), pos: p(0.0, 0.0) }; + out.push(PageChanges { page_id: o.id, page: None, name: o.name.clone(), changes: vec![removed] }); + } + out +} + +/// Changes since the last revision (empty without revisions). +pub fn pending(prj: &Project) -> Vec { + match prj.revisions.last() { + Some(r) => compare(&r.pages.0, &prj.pages), + None => Vec::new(), + } +} + +/// Suggested name of the next revision: A → B, Z → AA, 01 → 02. +pub fn next_name(prj: &Project) -> String { + let Some(last) = prj.revisions.last().map(|r| r.name.trim().to_string()) else { + return "A".into(); + }; + if let Ok(n) = last.parse::() { + return format!("{:0width$}", n + 1, width = last.len()); + } + let mut chars: Vec = last.chars().collect(); + match chars.last_mut() { + Some(c) if c.is_ascii_uppercase() && *c != 'Z' => *c = (*c as u8 + 1) as char, + Some(c) if *c == 'Z' => chars.push('A'), + _ => chars.push('A'), + } + chars.into_iter().collect() +} + +/// Creates a revision from the current pages; the project revision becomes its name. +/// With `release` all pages are locked. +pub fn create(prj: &mut Project, name: &str, date: &str, author: &str, description: &str, release: bool) { + if release { + for pg in &mut prj.pages { + pg.locked = true; + } + } + prj.info.revision = name.to_string(); + let pages = Snapshot(Arc::new(prj.pages.clone())); + prj.revisions.push(Revision { name: name.into(), date: date.into(), author: author.into(), description: description.into(), pages }); +} + +/// Report row: page, kind, item, description and jump target. +pub type OverviewRow = (String, String, String, String, Option<(usize, u64)>); + +/// Report rows of the changes since the last revision. +pub fn overview(prj: &Project) -> Vec { + let mut rows = Vec::new(); + let mut pages = pending(prj); + pages.sort_by(|a, b| a.page.unwrap_or(usize::MAX).cmp(&b.page.unwrap_or(usize::MAX)).then_with(|| natural_cmp(&a.name, &b.name))); + for pc in pages { + for c in &pc.changes { + let target = pc.page.map(|pi| (pi, if c.kind == ChangeKind::Removed || c.what == "Page" { 0 } else { c.id })); + rows.push((pc.name.clone(), c.kind.title().to_string(), c.what.to_string(), c.label.clone(), target)); + } + } + rows +} + +#[cfg(test)] +mod tests; diff --git a/src/revision/tests.rs b/src/revision/tests.rs new file mode 100644 index 00000000..59ccfbb7 --- /dev/null +++ b/src/revision/tests.rs @@ -0,0 +1,58 @@ +use super::*; +use crate::sample::demo_project; + +#[test] +fn changes_since_the_last_revision() { + let mut prj = demo_project(); + assert!(pending(&prj).is_empty(), "no revision yet"); + create(&mut prj, "A", "2026-10-20", "NS", "first release", true); + assert_eq!(prj.info.revision, "A"); + assert!(prj.pages.iter().all(|p| p.locked)); + assert!(pending(&prj).is_empty()); + + // Unlock, then change a symbol, delete a wire, add a text, add a page. + for pg in &mut prj.pages { + pg.locked = false; + } + assert!(pending(&prj).is_empty(), "locking alone is no change"); + let pg = &mut prj.pages[1]; + pg.symbols[0].function_text = "changed".into(); + let removed = pg.wires.remove(0).id; + pg.texts.push(crate::model::TextItem { id: 9999, text: "note".into(), ..Default::default() }); + prj.pages.push(Page::new(10_000, "9", "new page", crate::model::PageKind::Schematic)); + let changes = pending(&prj); + let page1 = changes.iter().find(|c| c.page == Some(1)).unwrap(); + let kinds: Vec<(ChangeKind, &str)> = page1.changes.iter().map(|c| (c.kind, c.what)).collect(); + assert!(kinds.contains(&(ChangeKind::Modified, "Symbol"))); + assert!(kinds.contains(&(ChangeKind::Added, "Text"))); + assert!(page1.changes.iter().any(|c| c.kind == ChangeKind::Removed && c.id == removed)); + assert!(changes.iter().any(|c| c.name == "9" && c.changes[0].what == "Page")); + assert_eq!(overview(&prj).len(), changes.iter().map(|c| c.changes.len()).sum::()); + + // A deleted page is reported as removed. + prj.pages.remove(3); + assert!(pending(&prj).iter().any(|c| c.page.is_none() && c.changes[0].kind == ChangeKind::Removed)); +} + +#[test] +fn revision_names_count_up() { + let mut prj = Project::default(); + assert_eq!(next_name(&prj), "A"); + for (last, next) in [("A", "B"), ("Z", "ZA"), ("01", "02"), ("9", "10"), ("B1", "B1A")] { + prj.revisions = vec![Revision { name: last.into(), ..Default::default() }]; + assert_eq!(next_name(&prj), next, "after {last}"); + } +} + +#[test] +fn snapshots_are_shared_and_serialized_as_pages() { + let mut prj = demo_project(); + create(&mut prj, "A", "", "", "", false); + let copy = prj.clone(); + assert!(Arc::ptr_eq(©.revisions[0].pages.0, &prj.revisions[0].pages.0)); + assert_eq!(copy, prj); + let json = serde_json::to_string(&prj).unwrap(); + let back: Project = serde_json::from_str(&json).unwrap(); + assert_eq!(back.revisions[0].pages.0.len(), prj.pages.len()); + assert_eq!(back, prj); +} diff --git a/src/sample.rs b/src/sample.rs index ae45fd89..5118000c 100644 --- a/src/sample.rs +++ b/src/sample.rs @@ -73,6 +73,7 @@ pub fn demo_project() -> Project { creator: "OpenECraft".into(), date: "2026-10-19".into(), revision: "A".into(), + ..Default::default() }; add_page(&mut prj, "1", "Cover sheet", PageKind::Cover); @@ -176,9 +177,55 @@ pub fn demo_project() -> Project { } } add_panel_layout(&mut prj, &db); + add_motor_cable(&mut prj, &db); + let open = crate::netlist::Netlist::build(&prj, false); + let bridged = crate::netlist::Netlist::build(&prj, true); + crate::wirenum::renumber(&mut prj, &open, &bridged, false); + add_door_harness(&mut prj); prj } +/// Command and signal devices on the door of +CAB1 are wired with harness -WH1. +const DOOR_DEVICES: [(&str, f32, f32); 6] = + [("-S1", 280.0, 110.0), ("-S2", 180.0, 230.0), ("-S3", 240.0, 230.0), ("-S4", 300.0, 230.0), ("-P1", 360.0, 230.0), ("-P2", 420.0, 230.0)]; + +fn add_door_harness(prj: &mut Project) { + let id = prj.new_id(); + prj.harnesses.push(crate::harness::Harness { id, tag: "-WH1".into(), description: "Door harness +CAB1".into(), length: 1.5, ..Default::default() }); + // Every connection with a door device at one of its ends. + let nl = crate::netlist::Netlist::build(prj, true); + let open = crate::netlist::Netlist::build(prj, false); + let door: Vec<&str> = DOOR_DEVICES.iter().map(|d| d.0).collect(); + let ends: Vec<(String, String)> = crate::netlist::connections(prj, &nl, &open) + .into_iter() + .filter(|c| [c.a, c.b].iter().any(|p| door.contains(&prj.pages[p.page].symbols[p.sym].tag.as_str()))) + .map(|c| (crate::netlist::pin_designation(prj, c.a), crate::netlist::pin_designation(prj, c.b))) + .collect(); + for (a, b) in ends { + crate::harness::assign(prj, &a, &b, "-WH1"); + } +} + +/// Cable -W1 from terminal strip -X1 to the motor -M1 (page 2). +fn add_motor_cable(prj: &mut Project, db: &PartsDb) { + let part = db.get("GEN.CBL-4G1.5").expect("cable part"); + let id = prj.new_id(); + prj.cables.push(Cable { + id, + tag: "-W1".into(), + cable_type: part.type_number.clone(), + cores: part.tech_value("Cores").unwrap_or_default().into(), + cross_section: part.tech_value("Cross-section").unwrap_or_default().into(), + length: 15.0, + part: part.number.clone(), + description: "Conveyor motor".into(), + }); + crate::parts::ensure_in_project(prj, db, "GEN.CBL-4G1.5"); + let page = prj.pages.iter().position(|p| p.name == "2").expect("page 2"); + let wires = prj.pages[page].wires.iter().filter(|w| w.a.y == 144.0 && w.b.y == 152.0).map(|w| w.id).collect(); + crate::ops::assign_cores(prj, page, &wires, "-W1"); +} + /// Enclosure +CAB1: cable duct frame, three mounting rails and the cabinet devices. fn add_panel_layout(prj: &mut Project, db: &PartsDb) { use crate::panel::{self, ItemKind}; @@ -217,6 +264,9 @@ fn add_panel_layout(prj: &mut Project, db: &PartsDb) { let h = panel::device_size(prj, tag).map(|d| d.h).unwrap_or(40.0); panel::place_device(prj, 0, tag, p(x, rail_y - h / 2.0)); } + for (tag, x, y) in DOOR_DEVICES { + panel::place_device_on(prj, 0, tag, p(x, y), panel::Face::Door); + } let id = prj.new_id(); let at = prj.pages.len(); prj.pages.push(Page::new(id, &(at + 1).to_string(), "Mounting layout +CAB1", PageKind::Mounting(enc_id))); diff --git a/src/strips.rs b/src/strips.rs new file mode 100644 index 00000000..c2997caf --- /dev/null +++ b/src/strips.rs @@ -0,0 +1,162 @@ +//! Terminal strips: terminal order, renumbering, jumpers and spare terminals. + +use crate::model::*; +use crate::netlist::{pin_designation, Netlist}; +use crate::symbols::{self, Func}; + +/// A terminal of a strip as placed in the schematic. +#[derive(Clone, Debug, PartialEq)] +pub struct Terminal { + pub page: usize, + pub sym: usize, + pub id: u64, + pub label: String, +} + +fn is_terminal(s: &SymbolInst) -> bool { + symbols::get(&s.sym).map(|d| d.func) == Some(Func::Terminal) +} + +/// Tags of all terminal strips. +pub fn strip_tags(prj: &Project) -> Vec { + let mut v: Vec = + prj.pages.iter().flat_map(|p| p.symbols.iter()).filter(|s| is_terminal(s) && !s.tag.is_empty()).map(|s| s.tag.clone()).collect(); + v.extend(prj.strips.keys().cloned()); + v.sort_by(|a, b| natural_cmp(a, b)); + v.dedup(); + v +} + +/// Terminals of a strip in strip order: the stored order first, the rest sorted by +/// designation (then schematic order). +pub fn terminals(prj: &Project, strip: &str) -> Vec { + let mut v = Vec::new(); + for (pi, pg) in prj.pages.iter().enumerate() { + if pg.kind != PageKind::Schematic { + continue; + } + for (si, s) in pg.symbols.iter().enumerate() { + if s.tag == strip && is_terminal(s) { + v.push(Terminal { page: pi, sym: si, id: s.id, label: s.label.clone() }); + } + } + } + let order = prj.strips.get(strip).map(|d| d.order.as_slice()).unwrap_or(&[]); + let rank = |t: &Terminal| order.iter().position(|o| *o == t.label).unwrap_or(usize::MAX); + v.sort_by(|a, b| rank(a).cmp(&rank(b)).then_with(|| natural_cmp(&a.label, &b.label)).then((a.page, a.sym).cmp(&(b.page, b.sym)))); + v +} + +/// Moves a terminal one place up or down and stores the resulting order. +pub fn move_terminal(prj: &mut Project, strip: &str, index: usize, up: bool) { + let mut labels: Vec = terminals(prj, strip).into_iter().map(|t| t.label).collect(); + let other = if up { index.checked_sub(1) } else { Some(index + 1).filter(|i| *i < labels.len()) }; + if let (Some(o), true) = (other, index < labels.len()) { + labels.swap(index, o); + prj.strips.entry(strip.to_string()).or_default().order = labels; + } +} + +/// Numbers the terminals 1, 2, 3 … in strip order; terminals with a non-numeric +/// designation (e.g. PE) keep it. Jumpers and order follow. Returns the number of +/// changed designations. +pub fn renumber(prj: &mut Project, strip: &str) -> usize { + let list = terminals(prj, strip); + let mut n = 0; + let mut changed = 0; + let mut renamed = Vec::new(); + for t in &list { + if !t.label.chars().all(|c| c.is_ascii_digit()) { + continue; + } + n += 1; + let new = n.to_string(); + if t.label != new { + renamed.push((t.label.clone(), new.clone())); + prj.pages[t.page].symbols[t.sym].label = new; + changed += 1; + } + } + if let Some(data) = prj.strips.get_mut(strip) { + let map = |l: &String| renamed.iter().find(|(o, _)| o == l).map(|(_, n)| n.clone()).unwrap_or_else(|| l.clone()); + data.order = list.iter().map(|t| map(&t.label)).collect(); + data.jumpers = data.jumpers.iter().map(|(l, j)| (map(l), *j)).collect(); + } + changed +} + +/// One row of the terminal diagram / strip editor. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub terminal: Option, + pub label: String, + pub jumper: u32, + pub external: String, + pub internal: String, + pub potential: String, + pub location: String, + pub function_text: String, +} + +fn targets(prj: &Project, nl: &Netlist, net: Option, exclude: (usize, usize)) -> String { + let Some(ni) = net else { return String::new() }; + let mut v: Vec = nl.nets[ni].pins.iter().filter(|p| (p.page, p.sym) != exclude).map(|p| pin_designation(prj, *p)).collect(); + v.sort_by(|a, b| natural_cmp(a, b)); + v.dedup(); + v.join(", ") +} + +/// Terminal diagram rows of a strip including spare terminals. `nl`: potentials, +/// `open`: terminal sides apart. +pub fn rows(prj: &Project, strip: &str, nl: &Netlist, open: &Netlist) -> Vec { + let data = prj.strips.get(strip).cloned().unwrap_or_default(); + let mut out = Vec::new(); + let mut max = 0u32; + for t in terminals(prj, strip) { + let s = &prj.pages[t.page].symbols[t.sym]; + max = max.max(t.label.parse().unwrap_or(0)); + out.push(Row { + label: t.label.clone(), + jumper: data.jumpers.get(&t.label).copied().unwrap_or(0), + external: targets(prj, open, open.pin_net.get(&(s.id, 0)).copied(), (t.page, t.sym)), + internal: targets(prj, open, open.pin_net.get(&(s.id, 1)).copied(), (t.page, t.sym)), + potential: nl.pin_net.get(&(s.id, 0)).map(|&n| nl.nets[n].name.clone()).unwrap_or_default(), + location: format!("/{}.{}", prj.pages[t.page].name, column_of(s.pos)), + function_text: s.function_text.replace('\n', " "), + terminal: Some(t), + }); + } + for i in 1..=data.spares { + out.push(Row { + terminal: None, + label: (max + i).to_string(), + jumper: 0, + external: String::new(), + internal: String::new(), + potential: String::new(), + location: String::new(), + function_text: "spare".into(), + }); + } + out +} + +/// Jumper groups of all strips: (strip, jumper number) -> terminal designations. +pub fn jumper_groups(prj: &Project) -> Vec<(String, Vec)> { + let mut v = Vec::new(); + for (strip, data) in &prj.strips { + let mut numbers: Vec = data.jumpers.values().copied().filter(|j| *j > 0).collect(); + numbers.sort(); + numbers.dedup(); + for j in numbers { + let labels: Vec = data.jumpers.iter().filter(|(_, x)| **x == j).map(|(l, _)| l.clone()).collect(); + if labels.len() > 1 { + v.push((strip.clone(), labels)); + } + } + } + v +} + +#[cfg(test)] +mod tests; diff --git a/src/strips/tests.rs b/src/strips/tests.rs new file mode 100644 index 00000000..88aa8394 --- /dev/null +++ b/src/strips/tests.rs @@ -0,0 +1,62 @@ +use super::*; +use crate::sample::demo_project; + +fn labels(prj: &Project) -> Vec { + terminals(prj, "-X1").into_iter().map(|t| t.label).collect() +} + +#[test] +fn order_moves_and_renumbering() { + let mut prj = demo_project(); + assert_eq!(strip_tags(&prj), vec!["-X1".to_string()]); + assert_eq!(labels(&prj), ["1", "2", "3", "PE"]); + move_terminal(&mut prj, "-X1", 2, true); + assert_eq!(labels(&prj), ["1", "3", "2", "PE"]); + move_terminal(&mut prj, "-X1", 0, true); // already first + assert_eq!(labels(&prj), ["1", "3", "2", "PE"]); + // Renumbering follows the strip order, PE keeps its designation; jumpers move along. + prj.strips.get_mut("-X1").unwrap().jumpers.insert("3".into(), 1); + assert_eq!(renumber(&mut prj, "-X1"), 2); + assert_eq!(labels(&prj), ["1", "2", "3", "PE"]); + assert_eq!(prj.strips["-X1"].jumpers.get("2"), Some(&1)); +} + +#[test] +fn rows_include_jumpers_and_spares() { + let mut prj = demo_project(); + let data = prj.strips.entry("-X1".into()).or_default(); + data.spares = 2; + data.jumpers.insert("1".into(), 4); + let nl = Netlist::build(&prj, true); + let open = Netlist::build(&prj, false); + let rows = rows(&prj, "-X1", &nl, &open); + assert_eq!(rows.len(), 6); + assert_eq!(rows[0].jumper, 4); + assert!(rows[0].internal.contains("-M1:U1"), "{}", rows[0].internal); + assert_eq!((rows[4].label.as_str(), rows[5].label.as_str()), ("4", "5")); + assert!(rows[5].terminal.is_none()); + // Spares are in the bill of materials. + let an = crate::reports::Analysis::build(&prj); + let tb = an.reports[&ReportKind::BillOfMaterials].rows.iter().find(|r| r[3] == "GEN.TB-2.5").cloned().unwrap(); + assert_eq!(tb[1], "6"); +} + +#[test] +fn jumpers_join_potentials() { + let mut prj = demo_project(); + let pot = |prj: &Project, label: &str| { + let nl = Netlist::build(prj, true); + let s = prj.pages.iter().flat_map(|p| &p.symbols).find(|s| s.tag == "-X1" && s.label == label).unwrap(); + nl.nets[nl.pin_net[&(s.id, 0)]].name.clone() + }; + assert_ne!(pot(&prj, "1"), pot(&prj, "2")); + let data = prj.strips.entry("-X1".into()).or_default(); + data.jumpers.insert("1".into(), 1); + data.jumpers.insert("2".into(), 1); + assert_eq!(pot(&prj, "1"), pot(&prj, "2")); + assert_eq!(jumper_groups(&prj), vec![("-X1".to_string(), vec!["1".to_string(), "2".to_string()])]); + // The physical connections (wire numbers) stay apart. + let open = Netlist::build(&prj, false); + let id = |l: &str| prj.pages.iter().flat_map(|p| &p.symbols).find(|s| s.tag == "-X1" && s.label == l).unwrap().id; + assert_ne!(open.pin_net[&(id("1"), 0)], open.pin_net[&(id("2"), 0)]); +} diff --git a/src/structure.rs b/src/structure.rs new file mode 100644 index 00000000..f4f2a5e9 --- /dev/null +++ b/src/structure.rs @@ -0,0 +1,116 @@ +//! Structure identifiers (IEC 81346): a device tag such as `=A1+CAB1-K1` names the +//! function (`=A1`), the location (`+CAB1`) and the device itself (`-K1`). +//! +//! Tags are stored complete. Pages carry a function and a location; on a page a +//! tag is shown without the aspects that equal the page's, and aspects missing in +//! an entered tag are taken from the page. + +use crate::model::Page; + +/// A device tag split into its aspects (stored without the prefix signs, except +/// the device name which keeps its `-`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Dt { + pub function: String, + pub location: String, + pub name: String, +} + +impl Dt { + /// Parses `=A1+CAB1-K1`, `+CAB1-K1`, `-K1` …; the device name starts at the + /// first `-`. + pub fn parse(tag: &str) -> Dt { + let tag = tag.trim(); + let (structure, name) = match tag.find('-') { + Some(i) => (&tag[..i], &tag[i..]), + None if tag.starts_with(['=', '+']) => (tag, ""), + None => ("", tag), + }; + let mut dt = Dt { name: name.to_string(), ..Default::default() }; + let mut sign = None; + let mut buf = String::new(); + for c in structure.chars().chain(std::iter::once('\0')) { + if matches!(c, '=' | '+' | '\0') { + match sign { + Some('=') => dt.function = std::mem::take(&mut buf), + Some('+') => dt.location = std::mem::take(&mut buf), + _ => buf.clear(), + } + sign = Some(c); + } else { + buf.push(c); + } + } + dt + } + + /// `=A1+CAB1` (empty without structure). + pub fn structure(&self) -> String { + structure(&self.function, &self.location) + } + + pub fn tag(&self) -> String { + format!("{}{}", self.structure(), self.name) + } +} + +/// `=function+location` with empty aspects left out. +pub fn structure(function: &str, location: &str) -> String { + let mut s = String::new(); + if !function.is_empty() { + s.push('='); + s.push_str(function); + } + if !location.is_empty() { + s.push('+'); + s.push_str(location); + } + s +} + +/// Removes prefix signs and blanks from an entered aspect (`"=A1 "` → `"A1"`). +pub fn clean_aspect(s: &str) -> String { + s.trim().trim_start_matches(['=', '+']).replace(' ', "") +} + +/// Structure of a page, e.g. `=A1+CAB1`. +pub fn page_structure(page: &Page) -> String { + structure(&page.function, &page.location) +} + +/// Page name with structure, e.g. `=A1+CAB1/3` (just `3` without structure). +pub fn page_full_name(page: &Page) -> String { + let s = page_structure(page); + if s.is_empty() { + page.name.clone() + } else { + format!("{s}/{}", page.name) + } +} + +/// Complete tag of a tag entered on a page: missing aspects come from the page. +pub fn complete(page: &Page, entered: &str) -> String { + let mut dt = Dt::parse(entered); + if dt.function.is_empty() { + dt.function = page.function.clone(); + } + if dt.location.is_empty() { + dt.location = page.location.clone(); + } + dt.tag() +} + +/// Shortest form of a complete tag on a page: aspects equal to the page's are left out. +pub fn relative(page: &Page, tag: &str) -> String { + let mut dt = Dt::parse(tag); + if dt.function == page.function { + dt.function.clear(); + } + if dt.location == page.location { + dt.location.clear(); + } + dt.tag() +} + +#[cfg(test)] +mod tests; diff --git a/src/structure/tests.rs b/src/structure/tests.rs new file mode 100644 index 00000000..32941c62 --- /dev/null +++ b/src/structure/tests.rs @@ -0,0 +1,47 @@ +use super::*; +use crate::model::PageKind; + +fn page(function: &str, location: &str) -> Page { + let mut p = Page::new(1, "3", "", PageKind::Schematic); + p.function = function.into(); + p.location = location.into(); + p +} + +#[test] +fn tags_are_split_into_aspects() { + let dt = Dt::parse("=A1+CAB1-K1"); + assert_eq!((dt.function.as_str(), dt.location.as_str(), dt.name.as_str()), ("A1", "CAB1", "-K1")); + assert_eq!(dt.tag(), "=A1+CAB1-K1"); + // Either order, missing aspects, plain names + assert_eq!(Dt::parse("+CAB1=A1-K1").tag(), "=A1+CAB1-K1"); + assert_eq!(Dt::parse("+CAB1-X1"), Dt { location: "CAB1".into(), name: "-X1".into(), ..Default::default() }); + assert_eq!(Dt::parse("-K1"), Dt { name: "-K1".into(), ..Default::default() }); + assert_eq!(Dt::parse("K1").name, "K1"); + assert_eq!(Dt::parse("=A1.2").function, "A1.2"); + assert_eq!(Dt::parse("=A1").structure(), "=A1"); +} + +#[test] +fn page_structure_completes_and_shortens_tags() { + let pg = page("A1", "CAB1"); + assert_eq!(page_full_name(&pg), "=A1+CAB1/3"); + assert_eq!(page_full_name(&page("", "")), "3"); + assert_eq!(complete(&pg, "-K1"), "=A1+CAB1-K1"); + assert_eq!(complete(&pg, "+FIELD-S1"), "=A1+FIELD-S1"); + assert_eq!(complete(&pg, "=B2+X-K1"), "=B2+X-K1"); + assert_eq!(relative(&pg, "=A1+CAB1-K1"), "-K1"); + assert_eq!(relative(&pg, "=A1+FIELD-S1"), "+FIELD-S1"); + assert_eq!(relative(&pg, "=B2+CAB1-K1"), "=B2-K1"); + // Without page structure nothing changes. + let plain = page("", ""); + assert_eq!(complete(&plain, "-K1"), "-K1"); + assert_eq!(relative(&plain, "=A1-K1"), "=A1-K1"); +} + +#[test] +fn aspects_are_cleaned() { + assert_eq!(clean_aspect(" =A1 "), "A1"); + assert_eq!(clean_aspect("+CAB 1"), "CAB1"); + assert_eq!(structure("", "CAB1"), "+CAB1"); +} diff --git a/src/symbols.rs b/src/symbols.rs index b56758eb..1261b20b 100644 --- a/src/symbols.rs +++ b/src/symbols.rs @@ -1,13 +1,15 @@ -//! Built-in IEC style symbol library. +//! Symbol libraries: built-in IEC, NFPA / JIC, fluid power, single-line and black +//! box symbols, plus the user symbols of the project ([`crate::symlib`]). //! //! Symbols are defined in local millimetre coordinates in vertical orientation //! (current flows top → bottom). Connection points lie on the 4 mm grid relative to //! the symbol origin so that placed symbols connect cleanly to wires. use crate::geom::{p, P, R}; +use serde::{Deserialize, Serialize}; use std::sync::OnceLock; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum ContactKind { No, Nc, @@ -15,7 +17,7 @@ pub enum ContactKind { MainNo, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Func { /// Main function of a device. `mirror` = draws a contact image (coils, overloads). Main { mirror: bool }, @@ -29,12 +31,47 @@ pub enum Func { Potential, /// Interruption point (page connector): label = name. No device tag. Interruption, + /// Single-line / overview representation of a device that is drawn in detail + /// elsewhere: shows cross references to the main function, its connection + /// points are not part of the netlist. + Overview, } impl Func { pub fn has_tag(self) -> bool { !matches!(self, Func::Potential | Func::Interruption) } + + /// All functions a symbol can have (symbol editor). + pub const ALL: [Func; 11] = [ + Func::Main { mirror: false }, + Func::Main { mirror: true }, + Func::Aux(ContactKind::No), + Func::Aux(ContactKind::Nc), + Func::Aux(ContactKind::Changeover), + Func::Aux(ContactKind::MainNo), + Func::Terminal, + Func::Plc, + Func::Potential, + Func::Interruption, + Func::Overview, + ]; + + pub fn title(self) -> &'static str { + match self { + Func::Main { mirror: false } => "Main function", + Func::Main { mirror: true } => "Main function with contact image", + Func::Aux(ContactKind::No) => "Auxiliary function: NO contact", + Func::Aux(ContactKind::Nc) => "Auxiliary function: NC contact", + Func::Aux(ContactKind::Changeover) => "Auxiliary function: changeover", + Func::Aux(ContactKind::MainNo) => "Auxiliary function: main contact", + Func::Terminal => "Terminal", + Func::Plc => "PLC connection point", + Func::Potential => "Potential", + Func::Interruption => "Interruption point", + Func::Overview => "Overview / single-line", + } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -48,10 +85,17 @@ pub enum Category { Plc, Potentials, Passive, + BlackBox, + SingleLine, + Nfpa, + Fluid, + /// Symbols of the project symbol library (symbol editor). + User, } impl Category { - pub const ALL: [Category; 9] = [ + /// Categories of the built-in libraries. + pub const ALL: [Category; 13] = [ Category::Coils, Category::Contacts, Category::Switches, @@ -61,6 +105,10 @@ impl Category { Category::Plc, Category::Potentials, Category::Passive, + Category::BlackBox, + Category::SingleLine, + Category::Nfpa, + Category::Fluid, ]; pub fn title(self) -> &'static str { @@ -74,24 +122,29 @@ impl Category { Category::Plc => "PLC", Category::Potentials => "Potentials / Connectors", Category::Passive => "Passive components", + Category::BlackBox => "Black boxes / PLC boxes", + Category::SingleLine => "Single-line / overview", + Category::Nfpa => "NFPA / JIC", + Category::Fluid => "Fluid power (ISO 1219)", + Category::User => "User symbols", } } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Anchor { Left, Center, Right, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum FieldKind { Label, Tag, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Prim { Line { a: P, b: P, dashed: bool }, Poly { pts: Vec

, closed: bool, fill: bool }, @@ -112,6 +165,8 @@ pub struct SymbolDef { pub key: &'static str, pub name: &'static str, pub category: Category, + /// Library of a user symbol (group in the symbol list); empty for built-in ones. + pub library: &'static str, /// Default identifying letter (IEC 81346 style). pub letter: &'static str, pub func: Func, @@ -172,6 +227,10 @@ impl B { self.prims.push(Prim::Line { a: p(x1, y1), b: p(x2, y2), dashed: true }); self } + /// Dashed rectangle (black box outline). + fn drect(&mut self, x1: f32, y1: f32, x2: f32, y2: f32) -> &mut Self { + self.dl(x1, y1, x2, y1).dl(x2, y1, x2, y2).dl(x2, y2, x1, y2).dl(x1, y2, x1, y1) + } fn rect(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, fill: bool) -> &mut Self { self.prims.push(Prim::Poly { pts: vec![p(x1, y1), p(x2, y1), p(x2, y2), p(x1, y2)], @@ -281,28 +340,12 @@ impl Def { self } fn build(self, b: &mut B) -> SymbolDef { - let mut bounds = R::nothing(); - for prim in &b.prims { - match prim { - Prim::Line { a, b, .. } => { - bounds.extend(*a); - bounds.extend(*b); - } - Prim::Poly { pts, .. } => pts.iter().for_each(|q| bounds.extend(*q)), - Prim::Circle { c, r, .. } => { - bounds.extend(p(c.x - r, c.y - r)); - bounds.extend(p(c.x + r, c.y + r)); - } - Prim::Text { .. } | Prim::Field { .. } => {} - } - } - for pin in &b.pins { - bounds.extend(pin.pos); - } + let bounds = bounds_of(&b.prims, b.pins.iter().map(|x| x.pos)); SymbolDef { key: self.key, name: self.name, category: self.category, + library: "", letter: self.letter, func: self.func, prims: std::mem::take(&mut b.prims), @@ -312,9 +355,35 @@ impl Def { auto_number: self.auto_number, show_tag: self.show_tag, show_pin_labels: self.show_pin_labels, - bounds: bounds.expand(0.5), + bounds, + } + } +} + +/// Bounding box of a symbol's graphics and pins (texts are not included). +pub fn bounds_of(prims: &[Prim], pins: impl Iterator) -> R { + let mut bounds = R::nothing(); + for prim in prims { + match prim { + Prim::Line { a, b, .. } => { + bounds.extend(*a); + bounds.extend(*b); + } + Prim::Poly { pts, .. } => pts.iter().for_each(|q| bounds.extend(*q)), + Prim::Circle { c, r, .. } => { + bounds.extend(p(c.x - r, c.y - r)); + bounds.extend(p(c.x + r, c.y + r)); + } + Prim::Text { .. } | Prim::Field { .. } => {} } } + for q in pins { + bounds.extend(q); + } + if bounds.min.x > bounds.max.x { + bounds = R::from_points(p(-1.0, -1.0), p(1.0, 1.0)); + } + bounds.expand(0.5) } const MAIN: Func = Func::Main { mirror: false }; @@ -572,16 +641,168 @@ fn build_library() -> Vec { b.pin(0.0, -4.0, "A").pin(0.0, 4.0, "K"); v.push(def("diode", "Diode", C::Passive, "V", MAIN).build(&mut b)); + // ---------------------------------------------------------------- black boxes + b.drect(-4.0, -4.0, 12.0, 4.0); + b.l(0.0, -8.0, 0.0, -4.0).l(8.0, -8.0, 8.0, -4.0).l(0.0, 4.0, 0.0, 8.0).l(8.0, 4.0, 8.0, 8.0); + b.pin(0.0, -8.0, "1").pin(8.0, -8.0, "2").pin(0.0, 8.0, "3").pin(8.0, 8.0, "4"); + v.push(def("box2", "Black box 2 + 2 connections", C::BlackBox, "A", MAIN).build(&mut b)); + + b.drect(-4.0, -4.0, 28.0, 4.0); + for (i, x) in [0.0, 8.0, 16.0, 24.0].into_iter().enumerate() { + b.l(x, -8.0, x, -4.0).l(x, 4.0, x, 8.0); + b.pin(x, -8.0, ["1", "2", "3", "4"][i]); + } + for (i, x) in [0.0, 8.0, 16.0, 24.0].into_iter().enumerate() { + b.pin(x, 8.0, ["5", "6", "7", "8"][i]); + } + v.push(def("box4", "Black box 4 + 4 connections", C::BlackBox, "A", MAIN).build(&mut b)); + + // PLC boxes: 8 channels on one side, supply on the other. + const CH: [&str; 8] = ["0", "1", "2", "3", "4", "5", "6", "7"]; + b.rect(-4.0, -6.0, 60.0, 6.0, false).text(28.0, 0.0, "DI 8 x 24 V DC", 2.5, Center); + for (i, label) in CH.into_iter().enumerate() { + let x = i as f32 * 8.0; + b.l(x, -12.0, x, -6.0).pin(x, -12.0, label); + } + b.l(0.0, 6.0, 0.0, 12.0).l(8.0, 6.0, 8.0, 12.0).pin(0.0, 12.0, "L+").pin(8.0, 12.0, "M"); + v.push(def("plcbox_di8", "PLC card 8 digital inputs", C::BlackBox, "A", MAIN).build(&mut b)); + + b.l(0.0, -12.0, 0.0, -6.0).l(8.0, -12.0, 8.0, -6.0).pin(0.0, -12.0, "L+").pin(8.0, -12.0, "M"); + b.rect(-4.0, -6.0, 60.0, 6.0, false).text(28.0, 0.0, "DO 8 x 24 V DC 0.5 A", 2.5, Center); + for (i, label) in CH.into_iter().enumerate() { + let x = i as f32 * 8.0; + b.l(x, 6.0, x, 12.0).pin(x, 12.0, label); + } + v.push(def("plcbox_do8", "PLC card 8 digital outputs", C::BlackBox, "A", MAIN).build(&mut b)); + + // ---------------------------------------------------------------- single-line + const OVERVIEW: Func = Func::Overview; + // Three strokes on the lead mark a 3-phase connection. + let three = |b: &mut B| { + for y in [-6.6, -5.6, -4.6] { + b.l(-1.0, y + 0.4, 1.0, y - 0.4); + } + }; + b.l(0.0, -8.0, 0.0, -2.0).l(0.0, 2.0, 0.0, 8.0).l(0.0, 2.0, -2.0, -2.4).breaker_x(0.0); + three(&mut b); + b.pin(0.0, -8.0, "").pin(0.0, 8.0, ""); + v.push(def("sl_cb", "Circuit breaker (single-line)", C::SingleLine, "Q", OVERVIEW).build(&mut b)); + + b.l(0.0, -8.0, 0.0, -2.0).l(0.0, 2.0, 0.0, 8.0).l(0.0, 2.0, -2.0, -2.4).arc(0.0, -1.3, 0.7, 180.0, 360.0); + three(&mut b); + b.pin(0.0, -8.0, "").pin(0.0, 8.0, ""); + v.push(def("sl_contactor", "Contactor (single-line)", C::SingleLine, "K", OVERVIEW).build(&mut b)); + + b.l(0.0, -8.0, 0.0, -2.0).rect(-1.2, -2.0, 1.2, 4.0, false).l(0.0, 4.0, 0.0, 8.0); + three(&mut b); + b.pin(0.0, -8.0, "").pin(0.0, 8.0, ""); + v.push(def("sl_fuse", "Fuse (single-line)", C::SingleLine, "F", OVERVIEW).build(&mut b)); + + b.l(0.0, -8.0, 0.0, -2.0).circle(0.0, 3.0, 5.0, false); + b.text(0.0, 1.8, "M", 3.0, Center).text(0.0, 5.0, "3~", 2.0, Center); + three(&mut b); + b.pin(0.0, -8.0, ""); + v.push(def("sl_motor", "Motor (single-line)", C::SingleLine, "M", OVERVIEW).build(&mut b)); + + b.l(0.0, -8.0, 0.0, -6.0).circle(0.0, -2.5, 3.5, false).circle(0.0, 2.5, 3.5, false).l(0.0, 6.0, 0.0, 8.0); + b.pin(0.0, -8.0, "").pin(0.0, 8.0, ""); + v.push(def("sl_trafo", "Transformer (single-line)", C::SingleLine, "T", OVERVIEW).build(&mut b)); + + // ---------------------------------------------------------------- NFPA / JIC + b.l(0.0, -4.0, 0.0, -3.0).circle(0.0, 0.0, 3.0, false).l(0.0, 3.0, 0.0, 4.0); + b.pin(0.0, -4.0, "A1").pin(0.0, 4.0, "A2"); + v.push(def("nfpa_coil", "Relay coil (NFPA)", C::Nfpa, "K", MAIN_MIRROR).build(&mut b)); + + b.l(0.0, -4.0, 0.0, -1.0).l(-2.2, -1.0, 2.2, -1.0).l(-2.2, 1.0, 2.2, 1.0).l(0.0, 1.0, 0.0, 4.0); + b.pin(0.0, -4.0, "13").pin(0.0, 4.0, "14"); + v.push(def("nfpa_no", "NO contact (NFPA)", C::Nfpa, "K", Func::Aux(ContactKind::No)).auto().build(&mut b)); + + b.l(0.0, -4.0, 0.0, -1.0).l(-2.2, -1.0, 2.2, -1.0).l(-2.2, 1.0, 2.2, 1.0).l(0.0, 1.0, 0.0, 4.0); + b.l(-2.4, 2.4, 2.4, -2.4); + b.pin(0.0, -4.0, "21").pin(0.0, 4.0, "22"); + v.push(def("nfpa_nc", "NC contact (NFPA)", C::Nfpa, "K", Func::Aux(ContactKind::Nc)).auto().build(&mut b)); + + b.l(0.0, -4.0, 0.0, -3.1).circle(0.0, -2.5, 0.6, false).circle(0.0, 2.5, 0.6, false).l(0.0, 3.1, 0.0, 4.0); + b.l(-2.0, -3.2, -2.0, 3.2).l(-2.0, 0.0, -4.5, 0.0).l(-4.5, -1.5, -4.5, 1.5); + b.pin(0.0, -4.0, "13").pin(0.0, 4.0, "14"); + v.push(def("nfpa_pb_no", "Push button NO (NFPA)", C::Nfpa, "S", MAIN).build(&mut b)); + + b.l(0.0, -4.0, 0.0, -3.1).circle(0.0, -2.5, 0.6, false).circle(0.0, 2.5, 0.6, false).l(0.0, 3.1, 0.0, 4.0); + b.l(0.6, -3.2, 0.6, 3.2).l(0.6, 0.0, -4.5, 0.0).l(-4.5, -1.5, -4.5, 1.5); + b.pin(0.0, -4.0, "11").pin(0.0, 4.0, "12"); + v.push(def("nfpa_pb_nc", "Push button NC (NFPA)", C::Nfpa, "S", MAIN).build(&mut b)); + + b.l(0.0, -4.0, 0.0, -2.0).arc(0.0, -1.0, 1.0, 270.0, 450.0).arc(0.0, 1.0, 1.0, 270.0, 450.0).l(0.0, 2.0, 0.0, 4.0); + b.pin(0.0, -4.0, "1").pin(0.0, 4.0, "2"); + v.push(def("nfpa_ol", "Overload heater (NFPA)", C::Nfpa, "F", MAIN_MIRROR).build(&mut b)); + + let r = 2.5 * std::f32::consts::FRAC_1_SQRT_2; + b.l(0.0, -4.0, 0.0, -2.5).circle(0.0, 0.0, 2.5, false).l(0.0, 2.5, 0.0, 4.0); + for (sx, sy) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] { + b.l(sx * (r + 0.4), sy * (r + 0.4), sx * (r + 1.4), sy * (r + 1.4)); + } + b.field(FieldKind::Label, 0.0, 0.0, 2.2, Center); + b.pin(0.0, -4.0, "X1").pin(0.0, 4.0, "X2"); + v.push(def("nfpa_lamp", "Pilot light (NFPA)", C::Nfpa, "P", MAIN).label("R").build(&mut b)); + + // ---------------------------------------------------------------- fluid power + // Small filled arrow head at `tip` pointing in direction (dx, dy). + let head = |b: &mut B, tx: f32, ty: f32, dx: f32, dy: f32| { + let (nx, ny) = (-dy, dx); + b.poly(&[(tx, ty), (tx - dx * 1.4 + nx * 0.7, ty - dy * 1.4 + ny * 0.7), (tx - dx * 1.4 - nx * 0.7, ty - dy * 1.4 - ny * 0.7)], true, true); + }; + b.l(0.0, -8.0, 0.0, -4.0).circle(0.0, 0.0, 4.0, false).l(0.0, 4.0, 0.0, 8.0); + b.poly(&[(0.0, -4.0), (-1.6, -1.4), (1.6, -1.4)], true, true); + b.pin(0.0, -8.0, "P").pin(0.0, 8.0, "S"); + v.push(def("fl_pump", "Hydraulic pump", C::Fluid, "GP", MAIN).build(&mut b)); + + b.rect(-4.0, -6.0, 20.0, 0.0, false).l(4.0, -6.0, 4.0, 0.0).l(4.0, -3.0, 28.0, -3.0); + b.l(0.0, 0.0, 0.0, 4.0).l(16.0, 0.0, 16.0, 4.0); + b.pin(0.0, 4.0, "1").pin(16.0, 4.0, "2"); + v.push(def("fl_cylinder", "Cylinder, double-acting", C::Fluid, "MM", MAIN).build(&mut b)); + + // 4/2 directional valve, solenoid operated, spring return; right box = rest position. + b.rect(-12.0, -4.0, 0.0, 4.0, false).rect(0.0, -4.0, 12.0, 4.0, false); + b.l(4.0, 4.0, 4.0, -3.0); + head(&mut b, 4.0, -4.0, 0.0, -1.0); + b.l(8.0, -4.0, 8.0, 3.0); + head(&mut b, 8.0, 4.0, 0.0, 1.0); + b.l(-8.0, 4.0, -4.6, -3.2); + head(&mut b, -4.0, -4.0, 0.5, -1.0); + b.l(-4.0, 4.0, -7.4, -3.2); + head(&mut b, -8.0, -4.0, -0.5, -1.0); + b.rect(-16.0, -2.0, -12.0, 2.0, false).l(-16.0, 2.0, -12.0, -2.0); + b.poly(&[(12.0, 0.0), (12.8, -1.5), (13.6, 1.5), (14.4, -1.5), (15.2, 1.5), (16.0, 0.0)], false, false); + b.l(4.0, -8.0, 4.0, -4.0).l(8.0, -8.0, 8.0, -4.0).l(4.0, 4.0, 4.0, 8.0).l(8.0, 4.0, 8.0, 8.0); + b.pin(4.0, -8.0, "A").pin(8.0, -8.0, "B").pin(4.0, 8.0, "P").pin(8.0, 8.0, "T"); + v.push(def("fl_valve42", "4/2 directional valve", C::Fluid, "QM", MAIN).build(&mut b)); + + b.l(0.0, -4.0, 0.0, -3.0).poly(&[(0.0, -3.0), (3.0, 0.0), (0.0, 3.0), (-3.0, 0.0)], true, false).l(0.0, 3.0, 0.0, 4.0); + b.dl(-3.0, 0.0, 3.0, 0.0); + b.pin(0.0, -4.0, "1").pin(0.0, 4.0, "2"); + v.push(def("fl_filter", "Filter", C::Fluid, "HQ", MAIN).build(&mut b)); + + b.circle(0.0, 0.0, 2.5, false).l(0.0, 2.5, 0.0, 4.0).l(-1.4, 1.4, 1.2, -1.2); + head(&mut b, 1.7, -1.7, 0.7, -0.7); + b.pin(0.0, 4.0, "1"); + v.push(def("fl_gauge", "Pressure gauge", C::Fluid, "BP", MAIN).build(&mut b)); + + b.poly(&[(-3.0, 0.0), (-3.0, 4.0), (3.0, 4.0), (3.0, 0.0)], false, false).l(0.0, -4.0, 0.0, 3.0); + b.pin(0.0, -4.0, "1"); + v.push(def("fl_tank", "Tank", C::Fluid, "CM", MAIN).build(&mut b)); + v } +/// Built-in symbols. pub fn library() -> &'static [SymbolDef] { static LIB: OnceLock> = OnceLock::new(); LIB.get_or_init(build_library) } +/// Built-in or registered user symbol. pub fn get(key: &str) -> Option<&'static SymbolDef> { - library().iter().find(|d| d.key == key) + library().iter().find(|d| d.key == key).or_else(|| crate::symlib::lookup(key)) } #[cfg(test)] diff --git a/src/symbols/tests.rs b/src/symbols/tests.rs index 8065cad5..99cd8487 100644 --- a/src/symbols/tests.rs +++ b/src/symbols/tests.rs @@ -14,3 +14,40 @@ fn pins_on_grid_and_keys_unique() { } } } + +#[test] +fn extra_libraries_are_complete() { + for cat in [Category::BlackBox, Category::SingleLine, Category::Nfpa, Category::Fluid] { + let n = library().iter().filter(|d| d.category == cat).count(); + assert!(n >= 4, "{} has only {n} symbols", cat.title()); + } + // Every function a symbol can have has a title (symbol editor). + assert_eq!(Func::ALL.iter().map(|f| f.title()).collect::>().len(), Func::ALL.len()); + for d in library().iter().filter(|d| d.category == Category::SingleLine) { + assert_eq!(d.func, Func::Overview, "{}", d.key); + } +} + +#[test] +fn overview_symbols_refer_to_the_main_function_but_stay_out_of_the_netlist() { + use crate::model::{Page, PageKind, Project, SymbolInst}; + let mut prj = Project { pages: vec![Page::new(1, "1", "", PageKind::Schematic), Page::new(2, "2", "", PageKind::Schematic)], next_id: 10, ..Default::default() }; + let motor = get("motor3").unwrap(); + let overview = get("sl_motor").unwrap(); + let inst = |id, sym: &str, x| SymbolInst { id, sym: sym.into(), pos: p(x, 60.0), tag: "-M1".into(), ..Default::default() }; + let mut m = inst(2, "motor3", 100.0); + m.pins = motor.pins.iter().map(|x| x.label.to_string()).collect(); + prj.pages[0].symbols.push(m); + prj.pages[1].symbols.push(inst(3, "sl_motor", 60.0)); + assert_eq!(overview.pins.len(), 1); + let idx = crate::index::Index::build(&prj); + assert_eq!(idx.devices["-M1"].mains.len(), 1); + assert_eq!(idx.devices["-M1"].overviews.len(), 1); + let nl = crate::netlist::Netlist::build(&prj, true); + // Only the four motor pins are open, the overview has no connection points. + assert_eq!(nl.unconnected.len(), 4); + assert!(nl.unconnected.iter().all(|(page, _, _)| *page == 0)); + // The overview shows the cross reference to the motor on page 1. + let svg = crate::svg::page_svg(&prj, 1); + assert!(svg.contains("/1.3"), "cross reference missing"); +} diff --git a/src/symlib.rs b/src/symlib.rs new file mode 100644 index 00000000..f9dd45c2 --- /dev/null +++ b/src/symlib.rs @@ -0,0 +1,329 @@ +//! Project symbol library: user defined symbols (symbol editor). They are stored in +//! the project, shared as library files and placed like built-in symbols; placed +//! instances refer to them by key. [`register`] makes them known to +//! [`symbols::get`](crate::symbols::get). + +use crate::geom::{dist_to_segment, p, P, GRID}; +use crate::model::Project; +use crate::symbols::{self, Anchor, Category, FieldKind, Func, PinDef, Prim, SymbolDef}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::{OnceLock, RwLock}; + +/// Keys of user symbols start with this prefix. +pub const PREFIX: &str = "user:"; +/// Snap of graphics in the symbol editor (pins snap to the 4 mm grid). +pub const DRAW_SNAP: f32 = 0.5; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct UserPin { + pub pos: P, + /// Default connection point designation. + pub label: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct UserSymbol { + pub key: String, + pub name: String, + /// Library (group in the symbol list), e.g. the company name. + pub library: String, + /// Identifying letter(s) for new device tags. + pub letter: String, + pub func: Func, + pub default_label: String, + pub auto_number: bool, + pub show_tag: bool, + pub show_pin_labels: bool, + pub prims: Vec, + pub pins: Vec, + /// Pins that are connected inside the symbol (terminals). + pub bridges: Vec<(usize, usize)>, +} + +impl Default for UserSymbol { + fn default() -> Self { + UserSymbol { + key: String::new(), + name: "New symbol".into(), + library: "User".into(), + letter: "A".into(), + func: Func::Main { mirror: false }, + default_label: String::new(), + auto_number: false, + show_tag: true, + show_pin_labels: true, + prims: Vec::new(), + pins: Vec::new(), + bridges: Vec::new(), + } + } +} + +/// File format for exchanging symbols between projects. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SymbolLibrary { + pub symbols: Vec, +} + +/// Symbol definition of a user symbol. Its texts are leaked to get the `'static` +/// lifetime of the built-in definitions, so it is only built when a symbol changed. +fn to_def(u: &UserSymbol) -> SymbolDef { + let leak = |s: &str| -> &'static str { Box::leak(s.to_string().into_boxed_str()) }; + SymbolDef { + key: leak(&u.key), + name: leak(&u.name), + category: Category::User, + library: leak(&u.library), + letter: leak(&u.letter), + func: u.func, + prims: u.prims.clone(), + pins: u.pins.iter().map(|x| PinDef { pos: x.pos, label: leak(&x.label) }).collect(), + bridges: u.bridges.iter().copied().filter(|(a, b)| *a < u.pins.len() && *b < u.pins.len()).collect(), + default_label: leak(&u.default_label), + auto_number: u.auto_number, + show_tag: u.show_tag && u.func.has_tag(), + show_pin_labels: u.show_pin_labels, + bounds: symbols::bounds_of(&u.prims, u.pins.iter().map(|x| x.pos)), + } +} + +type Registry = RwLock>; + +fn registry() -> &'static Registry { + static REG: OnceLock = OnceLock::new(); + REG.get_or_init(Default::default) +} + +/// Makes the user symbols known to the symbol lookup. Unchanged symbols are kept; +/// symbols removed from the project stay known so that open drawings still render. +pub fn register(list: &[UserSymbol]) { + let changed: Vec<&UserSymbol> = { + let Ok(reg) = registry().read() else { return }; + list.iter().filter(|u| reg.get(&u.key).map(|(old, _)| old != *u).unwrap_or(true)).collect() + }; + if changed.is_empty() { + return; + } + let Ok(mut reg) = registry().write() else { return }; + for u in changed { + // Definitions live as long as the program (`&'static`), like the built-in + // ones; only changed symbols are rebuilt. + let def: &'static SymbolDef = Box::leak(Box::new(to_def(u))); + reg.insert(u.key.clone(), (u.clone(), def)); + } +} + +pub fn lookup(key: &str) -> Option<&'static SymbolDef> { + if !key.starts_with(PREFIX) { + return None; + } + registry().read().ok()?.get(key).map(|(_, d)| *d) +} + +/// A new unique key for a symbol name, e.g. `user:motor_starter_2`. +pub fn new_key(existing: &[UserSymbol], name: &str) -> String { + let slug: String = name + .to_lowercase() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect::() + .split('_') + .filter(|s| !s.is_empty()) + .collect::>() + .join("_"); + let base = format!("{PREFIX}{}", if slug.is_empty() { "symbol" } else { &slug }); + let mut key = base.clone(); + let mut n = 2; + while existing.iter().any(|u| u.key == key) { + key = format!("{base}_{n}"); + n += 1; + } + key +} + +/// Editable copy of a built-in (or other) symbol. +pub fn from_def(def: &SymbolDef, existing: &[UserSymbol]) -> UserSymbol { + let name = format!("{} (copy)", def.name); + UserSymbol { + key: new_key(existing, &name), + name, + library: "User".into(), + letter: def.letter.into(), + func: def.func, + default_label: def.default_label.into(), + auto_number: def.auto_number, + show_tag: def.show_tag, + show_pin_labels: def.show_pin_labels, + prims: def.prims.clone(), + pins: def.pins.iter().map(|x| UserPin { pos: x.pos, label: x.label.into() }).collect(), + bridges: def.bridges.clone(), + } +} + +/// Number of placed instances of a symbol. +pub fn usage(prj: &Project, key: &str) -> usize { + prj.pages.iter().flat_map(|pg| pg.symbols.iter()).filter(|s| s.sym == key).count() +} + +/// Adds or replaces symbols of a library file; returns (added, replaced). +pub fn merge(list: &mut Vec, lib: SymbolLibrary) -> (usize, usize) { + let (mut added, mut replaced) = (0, 0); + for mut u in lib.symbols { + if !u.key.starts_with(PREFIX) { + u.key = new_key(list, &u.name); + } + match list.iter_mut().find(|x| x.key == u.key) { + Some(x) => { + *x = u; + replaced += 1; + } + None => { + list.push(u); + added += 1; + } + } + } + (added, replaced) +} + +/// Problems that make a symbol unusable or awkward to connect. +pub fn problems(u: &UserSymbol) -> Vec { + let mut v = Vec::new(); + if u.name.trim().is_empty() { + v.push("The symbol has no name.".into()); + } + if u.pins.is_empty() && !matches!(u.func, Func::Overview) { + v.push("The symbol has no connection points.".into()); + } + for (i, a) in u.pins.iter().enumerate() { + if a.pos.x % GRID != 0.0 || a.pos.y % GRID != 0.0 { + v.push(format!("Connection point {} is not on the {GRID} mm grid.", i + 1)); + } + if u.pins[..i].iter().any(|b| b.pos.same(a.pos)) { + v.push(format!("Connection point {} lies on another one.", i + 1)); + } + } + if u.func.has_tag() && u.letter.trim().is_empty() { + v.push("No identifying letter for the device tag.".into()); + } + v +} + +/// Item of a symbol under the pointer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hit { + Prim(usize), + Pin(usize), +} + +/// Distance from `q` to a graphic primitive. +pub fn prim_distance(prim: &Prim, q: P) -> f32 { + match prim { + Prim::Line { a, b, .. } => dist_to_segment(q, *a, *b), + Prim::Poly { pts, closed, fill } => { + let mut d = pts.windows(2).map(|s| dist_to_segment(q, s[0], s[1])).fold(f32::INFINITY, f32::min); + if *closed && pts.len() > 2 { + d = d.min(dist_to_segment(q, pts[pts.len() - 1], pts[0])); + if *fill && inside(pts, q) { + d = 0.0; + } + } + d + } + Prim::Circle { c, r, fill } => { + let d = (q.dist(*c) - r).abs(); + if *fill && q.dist(*c) <= *r { 0.0 } else { d } + } + Prim::Text { pos, text, size, anchor } => text_distance(*pos, text, *size, *anchor, q), + Prim::Field { pos, size, anchor, kind } => { + let sample = if *kind == FieldKind::Tag { "-K1" } else { "1" }; + text_distance(*pos, sample, *size, *anchor, q) + } + } +} + +fn text_distance(pos: P, text: &str, size: f32, anchor: Anchor, q: P) -> f32 { + let w = text.chars().count().max(1) as f32 * size * 0.62; + let x0 = match anchor { + Anchor::Left => pos.x, + Anchor::Center => pos.x - w / 2.0, + Anchor::Right => pos.x - w, + }; + let dx = (x0 - q.x).max(q.x - (x0 + w)).max(0.0); + let dy = ((q.y - pos.y).abs() - size * 0.6).max(0.0); + (dx * dx + dy * dy).sqrt() +} + +fn inside(pts: &[P], q: P) -> bool { + let mut c = false; + let mut j = pts.len() - 1; + for i in 0..pts.len() { + let (a, b) = (pts[i], pts[j]); + if (a.y > q.y) != (b.y > q.y) && q.x < (b.x - a.x) * (q.y - a.y) / (b.y - a.y) + a.x { + c = !c; + } + j = i; + } + c +} + +/// Pins first (they are small), then the nearest graphic within `tol`. +pub fn hit(u: &UserSymbol, q: P, tol: f32) -> Option { + if let Some(i) = u.pins.iter().position(|x| x.pos.dist(q) <= tol.max(1.0)) { + return Some(Hit::Pin(i)); + } + u.prims + .iter() + .enumerate() + .map(|(i, prim)| (i, prim_distance(prim, q))) + .filter(|(_, d)| *d <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| Hit::Prim(i)) +} + +/// Moves a primitive by `d`. +pub fn translate(prim: &mut Prim, d: P) { + match prim { + Prim::Line { a, b, .. } => { + *a = *a + d; + *b = *b + d; + } + Prim::Poly { pts, .. } => pts.iter_mut().for_each(|q| *q = *q + d), + Prim::Circle { c, .. } => *c = *c + d, + Prim::Text { pos, .. } | Prim::Field { pos, .. } => *pos = *pos + d, + } +} + +/// Removes a pin and fixes the bridges that refer to pins after it. +pub fn remove_pin(u: &mut UserSymbol, i: usize) { + if i >= u.pins.len() { + return; + } + u.pins.remove(i); + u.bridges.retain(|(a, b)| *a != i && *b != i); + for (a, b) in &mut u.bridges { + if *a > i { + *a -= 1; + } + if *b > i { + *b -= 1; + } + } +} + +/// Next free numeric pin designation ("1", "2", …). +pub fn next_pin_label(u: &UserSymbol) -> String { + let max = u.pins.iter().filter_map(|x| x.label.parse::().ok()).max().unwrap_or(0); + (max + 1).to_string() +} + +pub fn snap(q: P, step: f32) -> P { + p((q.x / step).round() * step, (q.y / step).round() * step) +} + +#[cfg(test)] +mod tests; diff --git a/src/symlib/tests.rs b/src/symlib/tests.rs new file mode 100644 index 00000000..036006ac --- /dev/null +++ b/src/symlib/tests.rs @@ -0,0 +1,132 @@ +use super::*; +use crate::index::Index; +use crate::model::{Page, PageKind, SymbolInst}; +use crate::netlist::Netlist; +use crate::reports::Analysis; + +fn box_symbol(key: &str) -> UserSymbol { + UserSymbol { + key: key.into(), + name: "Test box".into(), + letter: "A".into(), + prims: vec![Prim::Poly { pts: vec![p(-4.0, -4.0), p(4.0, -4.0), p(4.0, 4.0), p(-4.0, 4.0)], closed: true, fill: false }], + pins: vec![UserPin { pos: p(0.0, -8.0), label: "1".into() }, UserPin { pos: p(0.0, 8.0), label: "2".into() }], + ..Default::default() + } +} + +#[test] +fn registered_symbols_are_found_and_updated() { + let mut u = box_symbol("user:test_registry"); + register(std::slice::from_ref(&u)); + let def = symbols::get("user:test_registry").expect("registered"); + assert_eq!(def.category, Category::User); + assert_eq!(def.pins.len(), 2); + assert_eq!(def.library, "User"); + // Unchanged symbols keep their definition, changed ones get a new one. + register(std::slice::from_ref(&u)); + assert!(std::ptr::eq(def, symbols::get("user:test_registry").unwrap())); + u.pins.push(UserPin { pos: p(8.0, 8.0), label: "3".into() }); + register(std::slice::from_ref(&u)); + assert_eq!(symbols::get("user:test_registry").unwrap().pins.len(), 3); + // Keys without the prefix never reach the user registry. + assert!(lookup("coil").is_none()); +} + +#[test] +fn keys_are_unique_slugs() { + let mut list = vec![]; + let k = new_key(&list, "Motor starter (3~)"); + assert_eq!(k, "user:motor_starter_3"); + list.push(UserSymbol { key: k.clone(), ..Default::default() }); + assert_eq!(new_key(&list, "Motor starter (3~)"), "user:motor_starter_3_2"); + assert_eq!(new_key(&list, "äöü"), "user:symbol"); +} + +#[test] +fn copy_of_builtin_keeps_function_and_pins() { + let coil = symbols::get("coil").unwrap(); + let u = from_def(coil, &[]); + assert!(u.key.starts_with(PREFIX)); + assert_eq!(u.func, coil.func); + assert_eq!(u.pins.iter().map(|x| x.label.as_str()).collect::>(), vec!["A1", "A2"]); + assert_eq!(u.prims, coil.prims); + assert!(problems(&u).is_empty()); +} + +#[test] +fn problems_are_reported() { + let mut u = box_symbol("user:p"); + assert!(problems(&u).is_empty()); + u.pins[1].pos = p(1.0, 8.0); + u.pins.push(UserPin { pos: p(0.0, -8.0), label: "3".into() }); + let msgs = problems(&u); + assert!(msgs.iter().any(|m| m.contains("not on the")), "{msgs:?}"); + assert!(msgs.iter().any(|m| m.contains("lies on another")), "{msgs:?}"); + u.pins.clear(); + assert!(problems(&u).iter().any(|m| m.contains("no connection points"))); +} + +#[test] +fn hit_test_prefers_pins_and_moves_elements() { + let mut u = box_symbol("user:h"); + u.prims.push(Prim::Line { a: p(0.0, -8.0), b: p(0.0, -4.0), dashed: false }); + // The pin lies on the line: the pin wins. + assert_eq!(hit(&u, p(0.1, -8.0), 0.5), Some(Hit::Pin(0))); + assert_eq!(hit(&u, p(0.1, -6.0), 0.5), Some(Hit::Prim(1))); + assert_eq!(hit(&u, p(4.2, 0.0), 0.5), Some(Hit::Prim(0))); + assert_eq!(hit(&u, p(20.0, 20.0), 0.5), None); + translate(&mut u.prims[1], p(2.0, 0.0)); + assert_eq!(u.prims[1], Prim::Line { a: p(2.0, -8.0), b: p(2.0, -4.0), dashed: false }); + let text = Prim::Text { pos: p(0.0, 0.0), text: "ABC".into(), size: 2.0, anchor: Anchor::Left }; + assert_eq!(prim_distance(&text, p(1.0, 0.0)), 0.0); + assert!(prim_distance(&text, p(-3.0, 0.0)) > 2.9); +} + +#[test] +fn removing_a_pin_fixes_bridges() { + let mut u = box_symbol("user:b"); + u.pins.push(UserPin { pos: p(8.0, 8.0), label: "3".into() }); + u.bridges = vec![(0, 1), (1, 2)]; + remove_pin(&mut u, 0); + assert_eq!(u.pins.len(), 2); + assert_eq!(u.bridges, vec![(0, 1)]); + assert_eq!(next_pin_label(&u), "4"); +} + +#[test] +fn merge_adds_and_replaces() { + let mut list = vec![box_symbol("user:a")]; + let mut changed = box_symbol("user:a"); + changed.name = "Changed".into(); + let foreign = UserSymbol { key: "coil".into(), name: "Foreign".into(), ..Default::default() }; + let (added, replaced) = merge(&mut list, SymbolLibrary { symbols: vec![changed, foreign] }); + assert_eq!((added, replaced), (1, 1)); + assert_eq!(list[0].name, "Changed"); + // Keys of other programs are made user keys (no clash with built-in symbols). + assert_eq!(list[1].key, "user:foreign"); +} + +#[test] +fn placed_user_symbols_work_like_built_in_ones() { + let mut prj = Project { pages: vec![Page::new(1, "1", "", PageKind::Schematic)], next_id: 10, ..Default::default() }; + prj.symbols.push(box_symbol("user:test_placed")); + prj.pages[0].symbols.push(SymbolInst { + id: 2, + sym: "user:test_placed".into(), + pos: p(40.0, 40.0), + tag: "-A1".into(), + ..Default::default() + }); + // Saved and loaded: the symbol travels with the project. + let json = serde_json::to_string(&prj).unwrap(); + let mut back: Project = serde_json::from_str(&json).unwrap(); + back.normalize(); + assert_eq!(back.pages[0].symbols[0].pins, vec!["1", "2"]); + let idx = Index::build(&back); + assert_eq!(idx.devices["-A1"].mains.len(), 1); + let nl = Netlist::build(&back, true); + assert_eq!(nl.unconnected.len(), 2); + let an = Analysis::build(&back); + assert!(!an.issues.iter().any(|i| i.message.contains("Unknown symbol")), "{:?}", an.issues.iter().map(|i| &i.message).collect::>()); +} diff --git a/src/wirenum.rs b/src/wirenum.rs new file mode 100644 index 00000000..f2401024 --- /dev/null +++ b/src/wirenum.rs @@ -0,0 +1,145 @@ +//! Wire numbers. A number belongs to a connection: a net with the terminal sides +//! kept apart (`Netlist::build(prj, false)`), so the wires on both sides of a +//! terminal get their own numbers. All wire segments of a connection carry it. + +use crate::model::*; +use crate::netlist::{Net, Netlist}; +use std::collections::{HashMap, HashSet}; + +/// The wire segments of a net. +pub fn wires_of<'a>(prj: &'a Project, net: &Net) -> Vec<&'a Wire> { + let mut v: Vec<&Wire> = + net.wires.iter().filter_map(|(pi, id)| prj.pages[*pi].wires.iter().find(|w| w.id == *id)).collect(); + v.sort_by_key(|w| w.id); + v +} + +/// Number of a connection (the first number found on its wires). +pub fn number_of(prj: &Project, net: &Net) -> String { + wires_of(prj, net).iter().find(|w| !w.number.is_empty()).map(|w| w.number.clone()).unwrap_or_default() +} + +/// Different numbers on the wires of one connection (e.g. after joining two). +pub fn numbers_of(prj: &Project, net: &Net) -> Vec { + let mut v: Vec = wires_of(prj, net).iter().filter(|w| !w.number.is_empty()).map(|w| w.number.clone()).collect(); + v.sort_by(|a, b| natural_cmp(a, b)); + v.dedup(); + v +} + +/// Connections that get a number (they have wires and connect something), in +/// schematic order (page, column, top to bottom), with the page and column where +/// they start. +fn connections_in_order(prj: &Project, open: &Netlist) -> Vec<(usize, usize, usize)> { + let mut v: Vec<((usize, usize, i64, i64), usize)> = Vec::new(); + for (ni, net) in open.nets.iter().enumerate() { + if net.wires.is_empty() || net.pins.is_empty() { + continue; + } + let start = net + .wires + .iter() + .filter_map(|(pi, id)| prj.pages[*pi].wires.iter().find(|w| w.id == *id).map(|w| (*pi, w))) + .flat_map(|(pi, w)| [w.a, w.b].map(|q| (pi, column_of(q), (q.y * 10.0) as i64, (q.x * 10.0) as i64))) + .min(); + if let Some(start) = start { + v.push((start, ni)); + } + } + v.sort(); + v.into_iter().map(|((page, col, _, _), ni)| (ni, page, col)).collect() +} + +/// Numbers all connections according to the project's settings. Manually set +/// numbers stay unless `overwrite_fixed`. Returns the number of numbered connections. +pub fn renumber(prj: &mut Project, open: &Netlist, bridged: &Netlist, overwrite_fixed: bool) -> usize { + let settings = prj.wire_numbering.clone(); + let order = connections_in_order(prj, open); + let fixed = |prj: &Project, net: &Net| wires_of(prj, net).iter().any(|w| w.number_fixed && !w.number.is_empty()); + let mut used: HashSet = HashSet::new(); + let mut todo = Vec::new(); + for (ni, page, col) in order { + let net = &open.nets[ni]; + if !overwrite_fixed && fixed(prj, net) { + used.insert(number_of(prj, net)); + } else { + todo.push((ni, page, col)); + } + } + let mut counter = settings.start; + let mut next_counted = |used: &HashSet| loop { + let n = format!("{}{counter}", settings.prefix); + counter += 1; + if !used.contains(&n) { + return n; + } + }; + let mut per_column: HashMap<(usize, usize), u32> = HashMap::new(); + let mut numbers = Vec::new(); + for (ni, page, col) in todo { + let net = &open.nets[ni]; + let number = match settings.scheme { + NumberScheme::Sequential => next_counted(&used), + NumberScheme::PageColumn => loop { + let k = per_column.entry((page, col)).or_insert(0); + *k += 1; + let n = format!("{}{}.{col}.{k}", settings.prefix, prj.pages[page].name); + if !used.contains(&n) { + break n; + } + }, + NumberScheme::Potential => { + let pin = net.pins[0]; + let sym = prj.pages[pin.page].symbols[pin.sym].id; + match bridged.pin_net.get(&(sym, pin.pin)).map(|&n| &bridged.nets[n]) { + // Shared on purpose by all connections of the potential. + Some(pot) if pot.named => pot.name.clone(), + _ => next_counted(&used), + } + } + }; + used.insert(number.clone()); + numbers.push((ni, number)); + } + let count = numbers.len(); + for (ni, number) in numbers { + set(prj, &open.nets[ni], &number, false); + } + count +} + +/// Sets the number of all wires of a connection. +pub fn set(prj: &mut Project, net: &Net, number: &str, fixed: bool) { + for (pi, id) in &net.wires { + if let Some(w) = prj.pages[*pi].wires.iter_mut().find(|w| w.id == *id) { + w.number = number.to_string(); + w.number_fixed = fixed && !number.is_empty(); + } + } +} + +/// Removes wire numbers (manually set ones only with `include_fixed`). Returns the +/// number of wires changed. +pub fn clear(prj: &mut Project, include_fixed: bool) -> usize { + let mut n = 0; + for w in prj.pages.iter_mut().flat_map(|pg| pg.wires.iter_mut()) { + if !w.number.is_empty() && (include_fixed || !w.number_fixed) { + w.number.clear(); + w.number_fixed = false; + n += 1; + } + } + n +} + +/// Wire of a connection on a page that carries its label (the longest one). +pub fn label_wire<'a>(page: &'a Page, page_i: usize, net: &Net) -> Option<&'a Wire> { + net.wires + .iter() + .filter(|(pi, _)| *pi == page_i) + .filter_map(|(_, id)| page.wires.iter().find(|w| w.id == *id)) + .max_by(|a, b| (a.b - a.a).len().total_cmp(&(b.b - b.a).len()).then(b.id.cmp(&a.id))) +} + +#[cfg(test)] +mod tests; diff --git a/src/wirenum/tests.rs b/src/wirenum/tests.rs new file mode 100644 index 00000000..d9a92de5 --- /dev/null +++ b/src/wirenum/tests.rs @@ -0,0 +1,85 @@ +use super::*; +use crate::sample::demo_project; +use crate::symbols::{self, Func}; + +fn nets(prj: &Project) -> (Netlist, Netlist) { + (Netlist::build(prj, false), Netlist::build(prj, true)) +} + +fn numbered(open: &Netlist) -> Vec<&Net> { + open.nets.iter().filter(|n| !n.wires.is_empty() && !n.pins.is_empty()).collect() +} + +/// Number of the connection at a pin of the first symbol matching `pred`. +fn number_at(prj: &Project, pred: impl Fn(&SymbolInst) -> bool, pin: usize) -> String { + let open = Netlist::build(prj, false); + let s = prj.pages.iter().flat_map(|p| p.symbols.iter()).find(|s| pred(s)).expect("symbol"); + number_of(prj, &open.nets[open.pin_net[&(s.id, pin)]]) +} + +fn is_terminal(s: &SymbolInst, label: &str) -> bool { + symbols::get(&s.sym).map(|d| d.func) == Some(Func::Terminal) && s.label == label +} + +#[test] +fn sequential_numbers_are_unique_per_connection() { + let mut prj = demo_project(); + let (open, bridged) = nets(&prj); + let n = renumber(&mut prj, &open, &bridged, false); + assert_eq!(n, numbered(&open).len()); + let mut seen = HashSet::new(); + for net in numbered(&open) { + let numbers = numbers_of(&prj, net); + assert_eq!(numbers.len(), 1, "one number for all wires of a connection"); + assert!(seen.insert(numbers[0].clone()), "{} used twice", numbers[0]); + } + assert!(seen.contains("1")); + // Both sides of a terminal are separate connections. + let top = number_at(&prj, |s| is_terminal(s, "1"), 0); + let bottom = number_at(&prj, |s| is_terminal(s, "1"), 1); + assert!(!top.is_empty() && top != bottom); +} + +#[test] +fn page_column_and_potential_schemes() { + let mut prj = demo_project(); + let (open, bridged) = nets(&prj); + prj.wire_numbering.scheme = NumberScheme::PageColumn; + renumber(&mut prj, &open, &bridged, false); + let first = number_at(&prj, |s| s.tag == "-Q1", 0); + assert!(first.starts_with("2.") && first.ends_with(".1"), "{first}"); + + prj.wire_numbering = WireNumbering { scheme: NumberScheme::Potential, prefix: "W".into(), start: 100 }; + renumber(&mut prj, &open, &bridged, false); + // -Q1 is fed from the L1 rail; the motor side of the terminal is not a named potential. + assert_eq!(number_at(&prj, |s| s.tag == "-Q1", 0), "L1"); + assert!(number_at(&prj, |s| is_terminal(s, "1"), 1).starts_with('W')); +} + +#[test] +fn manual_numbers_are_kept_unless_overwritten() { + let mut prj = demo_project(); + let (open, bridged) = nets(&prj); + let target = &open.nets[open.pin_net[&(prj.pages[1].symbols.iter().find(|s| s.tag == "-M1").unwrap().id, 0)]]; + set(&mut prj, target, "MOTOR-U", true); + renumber(&mut prj, &open, &bridged, false); + assert_eq!(number_of(&prj, target), "MOTOR-U"); + let automatic = prj.pages.iter().flat_map(|p| &p.wires).filter(|w| !w.number.is_empty() && !w.number_fixed).count(); + assert_eq!(clear(&mut prj, false), automatic); + assert_eq!(number_of(&prj, target), "MOTOR-U"); + renumber(&mut prj, &open, &bridged, true); + assert_ne!(number_of(&prj, target), "MOTOR-U"); + assert!(clear(&mut prj, true) > 0); + assert!(prj.pages.iter().flat_map(|p| &p.wires).all(|w| w.number.is_empty())); +} + +#[test] +fn numbers_are_labelled_on_the_longest_wire() { + let prj = demo_project(); + let open = Netlist::build(&prj, false); + let net = numbered(&open).into_iter().find(|n| n.wires.len() > 1).unwrap(); + let pi = net.wires[0].0; + let w = label_wire(&prj.pages[pi], pi, net).unwrap(); + let len = |w: &Wire| (w.b - w.a).len(); + assert!(net.wires.iter().filter(|x| x.0 == pi).all(|(_, id)| len(prj.pages[pi].wires.iter().find(|x| x.id == *id).unwrap()) <= len(w))); +}