diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 12fffa8a..efab4a32 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,14 +19,16 @@ jobs: run: | sudo apt-get update sudo apt-get install -y libxkbcommon-dev libgtk-3-dev libwayland-dev libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev - - run: cargo test - - run: cargo build --release + - run: cargo test --workspace + - run: cargo build --workspace --release - uses: actions/upload-artifact@v4 with: name: openecraft-${{ matrix.os }} path: | target/release/openecraft target/release/openecraft.exe + target/release/openecraft-server + target/release/openecraft-server.exe web: runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index c561308a..1c12d09b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ /target /dist /.idea/ +# Local parts server databases +parts-db.json +*.tmp diff --git a/AGENTS.md b/AGENTS.md index d09d09de..4c9ce38b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,15 +9,32 @@ macOS and in the browser (WebAssembly). Run these before considering a change done. All of them must pass without warnings. ```bash -cargo test -cargo clippy --all-targets -cargo clippy --target wasm32-unknown-unknown +cargo test --workspace +cargo clippy --workspace --all-targets +cargo clippy -p openecraft --target wasm32-unknown-unknown ``` - Desktop: `cargo run --release` +- Parts server: `cargo run -p openecraft-server -- --token ` (http://127.0.0.1:8090) - Web: `trunk serve` (dev server on http://127.0.0.1:8080), `trunk build --release` - The web target needs `rustup target add wasm32-unknown-unknown` and `cargo install trunk --locked`. +## Workspace layout + +| Crate | Path | Purpose | +| --- | --- | --- | +| `openecraft` | `.` (`src/`) | Editor (desktop + web) – the root package, built by trunk | +| `openecraft-parts` | `crates/openecraft-parts` | Shared library: part model, function templates, CSV/JSON, catalog, parts server API types | +| `openecraft-server` | `server/` | Standalone parts database server (axum, JSON file storage) | + +- Code needed by more than one executable belongs in a library crate under `crates/`, + never duplicated. The library must stay free of UI and platform dependencies + (only `serde` / `serde_json`). +- API types and request paths of the parts server live in `openecraft_parts::api`; change + server and client together. +- New crates are added to `[workspace] members` in the root `Cargo.toml`; the + convention test reads that list, so its rules apply to every member. + ## Unit tests – mandatory layout **Unit tests never live inline in a module file.** Each module keeps its tests in a @@ -30,7 +47,7 @@ src/geom.rs ← module code, ends with: src/geom/tests.rs ← the tests, starting with `use super::*;` ``` -Rules: +Rules (for every crate of the workspace): 1. No `#[test]` functions and no `mod tests { … }` blocks in module files. 2. The module file declares its tests exactly as `#[cfg(test)]` followed by `mod tests;` diff --git a/Cargo.lock b/Cargo.lock index e612cd5e..17e7f06c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -429,6 +429,64 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "bit-set" version = "0.10.0" @@ -611,6 +669,46 @@ dependencies = [ "libc", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "clipboard-win" version = "5.4.1" @@ -950,6 +1048,20 @@ dependencies = [ "winit", ] +[[package]] +name = "ehttp" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2f1b93eb2e039aaff63ce07cca59bd1dca02f2ce30075a17b619d2c42f56efc" +dependencies = [ + "document-features", + "js-sys", + "ureq", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "either" version = "1.19.0" @@ -1284,6 +1396,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1463,6 +1586,12 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -1475,6 +1604,85 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -1837,6 +2045,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -1861,6 +2075,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1881,6 +2101,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -2308,9 +2539,11 @@ version = "0.1.0" dependencies = [ "eframe", "egui", + "ehttp", "env_logger", "js-sys", "log", + "openecraft-parts", "rfd", "serde", "serde_json", @@ -2319,6 +2552,31 @@ dependencies = [ "web-sys", ] +[[package]] +name = "openecraft-parts" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "openecraft-server" +version = "0.1.0" +dependencies = [ + "axum", + "clap", + "env_logger", + "http-body-util", + "log", + "openecraft-parts", + "serde", + "serde_json", + "tokio", + "tower", + "tower-http", +] + [[package]] name = "orbclient" version = "0.3.55" @@ -2738,6 +2996,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "ron" version = "0.12.2" @@ -2799,12 +3071,53 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2887,6 +3200,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -2898,6 +3222,18 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "shlex" version = "2.0.1" @@ -3048,6 +3384,16 @@ dependencies = [ "serde", ] +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -3060,6 +3406,18 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -3082,6 +3440,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "synstructure" version = "0.14.0" @@ -3100,10 +3464,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3176,7 +3540,24 @@ version = "1.54.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" dependencies = [ + "libc", + "mio", "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", ] [[package]] @@ -3209,6 +3590,49 @@ dependencies = [ "winnow", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "http", + "percent-encoding", + "pin-project-lite", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -3308,6 +3732,41 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -3320,6 +3779,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -3386,6 +3851,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" @@ -3622,6 +4093,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -4280,6 +4760,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 3306b80d..02567526 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,9 @@ license = "MIT OR Apache-2.0" name = "openecraft" path = "src/main.rs" +[workspace] +members = [".", "crates/openecraft-parts", "server"] + [dependencies] eframe = { version = "0.37", default-features = false, features = [ "accesskit", @@ -27,6 +30,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" log = "0.4" rfd = "0.17" +ehttp = "0.7" +openecraft-parts = { path = "crates/openecraft-parts" } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] env_logger = "0.11" diff --git a/README.md b/README.md index 38aba7ed..8ef2885f 100644 --- a/README.md +++ b/README.md @@ -88,10 +88,32 @@ trunk build --release # static files in dist/ – host them on any web server In the browser "Save" downloads the project file and "Open" uses the file picker. +### Parts server + +`openecraft-server` hosts a global parts database that all OpenECraft installations +(desktop and web) can share. It is a separate executable and runs independently of +the editor. + +```bash +cargo run --release -p openecraft-server -- --bind 0.0.0.0:8090 --data parts-db.json --token +``` + +- The database is a JSON file, created with the example catalog if it does not exist, + and written atomically on every change. +- Reading is open; changes need `Authorization: Bearer `. Without `--token` + (or the `OPENECRAFT_TOKEN` environment variable) the server is read-only. +- REST API (`/api/v1`): `GET /info`, `GET /parts?q=&group=&manufacturer=&offset=&limit=`, + `GET|PUT|DELETE /parts/{number}`, `POST /import` (CSV or JSON), `GET /export.csv`. +- In the editor: *Project › Parts management › 🌐 Parts server* – enter the server URL, + test the connection, download all parts into the local database or upload the + selected part / the whole local database (needs the access token). +- The server speaks plain HTTP; put it behind a TLS reverse proxy when it is reachable + from outside your network. + ### Tests ```bash -cargo test +cargo test --workspace ``` ## Usage @@ -111,6 +133,9 @@ cargo test | File | Purpose | | --- | --- | +| `crates/openecraft-parts` | Shared library: part model, function templates, CSV/JSON, catalog, server API types | +| `server/` | `openecraft-server`: parts database server (REST API, JSON storage) | +| `src/parts_server.rs` | Client for the parts server | | `src/model.rs` | Project data model (pages, symbols, wires, parts) and page layout constants | | `src/symbols.rs` | Built-in IEC symbol library | | `src/netlist.rs` | Connectivity analysis (nets / potentials, junctions) | diff --git a/crates/openecraft-parts/Cargo.toml b/crates/openecraft-parts/Cargo.toml new file mode 100644 index 00000000..55a03a09 --- /dev/null +++ b/crates/openecraft-parts/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "openecraft-parts" +version = "0.1.0" +edition = "2021" +description = "Shared parts model of OpenECraft (part data, function templates, CSV/JSON, parts server API)" +license = "MIT OR Apache-2.0" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/crates/openecraft-parts/src/api.rs b/crates/openecraft-parts/src/api.rs new file mode 100644 index 00000000..2927810c --- /dev/null +++ b/crates/openecraft-parts/src/api.rs @@ -0,0 +1,138 @@ +//! HTTP API of the parts server, shared by the server and its clients. +//! +//! | Method | Path | | +//! | --- | --- | --- | +//! | GET | `/api/v1/info` | [`ServerInfo`] | +//! | GET | `/api/v1/parts?q=&group=&manufacturer=&offset=&limit=` | [`PartList`] | +//! | GET | `/api/v1/parts/{number}` | [`Part`] | +//! | PUT | `/api/v1/parts/{number}` | create / replace a part (token) | +//! | DELETE | `/api/v1/parts/{number}` | delete a part (token) | +//! | POST | `/api/v1/import` | CSV or JSON body, upserts parts (token) → [`ImportResult`] | +//! | GET | `/api/v1/export.csv` | all parts as CSV | +//! +//! Write requests need `Authorization: Bearer `. Errors are returned as +//! [`ApiError`] JSON. + +use crate::{natural_cmp, Part}; +use serde::{Deserialize, Serialize}; + +pub const API_PREFIX: &str = "/api/v1"; +pub const DEFAULT_PORT: u16 = 8090; + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ServerInfo { + pub name: String, + pub version: String, + pub parts: usize, + /// Incremented on every change of the database. + pub revision: u64, + /// False if the server has no write token configured (read-only). + pub writable: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PartList { + pub revision: u64, + /// Number of matching parts (before offset / limit). + pub total: usize, + pub offset: usize, + pub parts: Vec, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ImportResult { + pub imported: usize, + pub revision: u64, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ApiError { + pub error: String, +} + +/// Query parameters of `GET /api/v1/parts`. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PartQuery { + /// Free text (number, type, manufacturer, description, groups). + pub q: Option, + /// Product group (exact, case insensitive). + pub group: Option, + /// Manufacturer (exact, case insensitive). + pub manufacturer: Option, + pub offset: Option, + pub limit: Option, +} + +impl PartQuery { + /// Filters, sorts (by part number) and pages `parts`. Returns the number of + /// matches before paging and the requested page. + pub fn apply(&self, parts: &[Part]) -> (usize, Vec) { + let eq = |a: &str, b: &Option| b.as_deref().map(|b| a.eq_ignore_ascii_case(b)).unwrap_or(true); + let mut hits: Vec<&Part> = parts + .iter() + .filter(|p| p.matches_text(self.q.as_deref().unwrap_or(""))) + .filter(|p| eq(&p.group, &self.group) && eq(&p.manufacturer, &self.manufacturer)) + .collect(); + hits.sort_by(|a, b| natural_cmp(&a.number, &b.number)); + let total = hits.len(); + let page = hits + .into_iter() + .skip(self.offset.unwrap_or(0)) + .take(self.limit.unwrap_or(usize::MAX)) + .cloned() + .collect(); + (total, page) + } + + /// `?q=…&group=…` (empty if no parameter is set). + pub fn to_query_string(&self) -> String { + let mut params = Vec::new(); + for (k, v) in [("q", &self.q), ("group", &self.group), ("manufacturer", &self.manufacturer)] { + if let Some(v) = v { + params.push(format!("{k}={}", encode_component(v))); + } + } + if let Some(o) = self.offset { + params.push(format!("offset={o}")); + } + if let Some(l) = self.limit { + params.push(format!("limit={l}")); + } + if params.is_empty() { + String::new() + } else { + format!("?{}", params.join("&")) + } + } +} + +/// Percent-encodes everything except unreserved URL characters (RFC 3986). +pub fn encode_component(s: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// Path of a single part, e.g. `/api/v1/parts/GEN.CT-9A-24DC`. +pub fn part_path(number: &str) -> String { + format!("{API_PREFIX}/parts/{}", encode_component(number)) +} + +/// Joins a server base URL (with or without trailing slash) and an API path. +pub fn url(base: &str, path: &str) -> String { + format!("{}{path}", base.trim().trim_end_matches('/')) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-parts/src/api/tests.rs b/crates/openecraft-parts/src/api/tests.rs new file mode 100644 index 00000000..b240becf --- /dev/null +++ b/crates/openecraft-parts/src/api/tests.rs @@ -0,0 +1,38 @@ +use super::*; +use crate::default_catalog; + +#[test] +fn query_filters_sorts_and_pages() { + let parts = default_catalog(); + let all = PartQuery::default().apply(&parts); + assert_eq!(all.0, parts.len()); + assert_eq!(all.1.len(), parts.len()); + + let q = PartQuery { q: Some("contactor".into()), ..Default::default() }; + let (total, hits) = q.apply(&parts); + assert!(total >= 2); + assert!(hits.iter().all(|p| p.matches_text("contactor"))); + + let q = PartQuery { group: Some("relays, CONTACTORS".into()), ..Default::default() }; + let (_, hits) = q.apply(&parts); + assert!(!hits.is_empty() && hits.iter().all(|p| p.group == "Relays, contactors")); + // Sorted by part number + assert!(hits.windows(2).all(|w| natural_cmp(&w[0].number, &w[1].number).is_le())); + + let q = PartQuery { offset: Some(2), limit: Some(3), ..Default::default() }; + let (total, page) = q.apply(&parts); + assert_eq!(total, parts.len()); + assert_eq!(page.len(), 3); + assert_eq!(page[0].number, all.1[2].number); +} + +#[test] +fn query_string_and_urls() { + assert_eq!(PartQuery::default().to_query_string(), ""); + let q = PartQuery { q: Some("24 V/DC".into()), limit: Some(10), ..Default::default() }; + assert_eq!(q.to_query_string(), "?q=24%20V%2FDC&limit=10"); + assert_eq!(part_path("GEN.CT-9A-24DC"), "/api/v1/parts/GEN.CT-9A-24DC"); + assert_eq!(part_path("A B/1"), "/api/v1/parts/A%20B%2F1"); + assert_eq!(url("http://host:8090/", "/api/v1/info"), "http://host:8090/api/v1/info"); + assert_eq!(url(" http://host:8090 ", "/api/v1/info"), "http://host:8090/api/v1/info"); +} diff --git a/crates/openecraft-parts/src/catalog.rs b/crates/openecraft-parts/src/catalog.rs new file mode 100644 index 00000000..46e67ab2 --- /dev/null +++ b/crates/openecraft-parts/src/catalog.rs @@ -0,0 +1,262 @@ +//! Generic example catalog with function templates. + +use crate::{natural_cmp, FnKind, FunctionTemplate, Mesh3d, Model2d, Part, Prim2d, TopGroup}; + +struct C { + parts: Vec, +} + +#[allow(clippy::too_many_arguments)] +impl C { + fn add( + &mut self, + number: &str, + desc: &str, + group: &str, + subgroup: &str, + ident: &str, + price: f32, + dims: (f32, f32, f32, f32), + functions: &[(FnKind, &str)], + ) -> &mut Part { + let (top, rest) = number.split_once('.').unwrap_or(("GEN", number)); + let manufacturer = if top == "GEN" { "Generic" } else { top }; + self.parts.push(Part { + number: number.into(), + type_number: rest.into(), + order_number: rest.into(), + manufacturer: manufacturer.into(), + supplier: "Generic distribution".into(), + description: desc.into(), + top_group: if group == "Mounting" { TopGroup::Mechanics } else if group == "Valves" { TopGroup::Fluid } else { TopGroup::Electrical }, + group: group.into(), + subgroup: subgroup.into(), + identifier: ident.into(), + price, + width: dims.0, + height: dims.1, + depth: dims.2, + weight: dims.3, + mounting: if dims.0 > 0.0 { "Mounting rail 35 mm".into() } else { String::new() }, + functions: functions.iter().map(|(k, p)| FunctionTemplate::new(*k, p)).collect(), + ..Default::default() + }); + self.parts.last_mut().unwrap() + } +} + +/// Generic example catalog with function templates. +pub fn default_catalog() -> Vec { + use FnKind::*; + let mut c = C { parts: Vec::new() }; + let rc = "Relays, contactors"; + let sd = "Safety devices"; + let sw = "Sensors, switches, pushbuttons"; + let main3 = "1 3 5 2 4 6"; + + let p = c.add("GEN.CT-9A-24DC", "Contactor 3P 9 A, coil 24 V DC, 1 NO aux", rc, "Power contactor", "K", 38.5, (45.0, 74.0, 73.0, 0.32), &[(Coil, "A1 A2"), (MainContacts3, main3), (No, "13 14")]); + p.voltage = "24 V DC".into(); + p.current = "9 A (AC-3)".into(); + p.power = "4 kW / 400 V".into(); + p.accessories = vec!["GEN.AUX-2NO2NC".into()]; + let p = c.add("GEN.CT-18A-24DC", "Contactor 3P 18 A, coil 24 V DC, 1 NO + 1 NC aux", rc, "Power contactor", "K", 52.0, (45.0, 84.0, 87.0, 0.45), &[(Coil, "A1 A2"), (MainContacts3, main3), (No, "13 14"), (Nc, "21 22")]); + p.voltage = "24 V DC".into(); + p.current = "18 A (AC-3)".into(); + p.power = "7.5 kW / 400 V".into(); + p.accessories = vec!["GEN.AUX-2NO2NC".into()]; + c.add("GEN.AUX-2NO2NC", "Auxiliary contact block 2 NO + 2 NC, front mounting", rc, "Auxiliary contact block", "K", 14.6, (45.0, 40.0, 40.0, 0.05), &[(No, "53 54"), (Nc, "61 62"), (Nc, "71 72"), (No, "83 84")]); + c.add("GEN.AUX-1NO1NC", "Auxiliary contact block 1 NO + 1 NC", rc, "Auxiliary contact block", "K", 9.8, (45.0, 40.0, 40.0, 0.03), &[(No, "53 54"), (Nc, "61 62")]); + let p = c.add("GEN.RLY-24DC-2CO", "Interface relay 24 V DC, 2 CO, with socket", rc, "Relay", "K", 12.4, (15.5, 78.0, 70.0, 0.04), &[(Coil, "A1 A2"), (Changeover, "11 12 14"), (Changeover, "21 22 24")]); + p.voltage = "24 V DC".into(); + p.current = "8 A".into(); + let p = c.add("GEN.TMR-24DC-OND", "Timer relay on-delay 24 V DC, 0.05 s - 100 h, 1 CO", rc, "Timer relay", "K", 34.9, (17.5, 90.0, 64.0, 0.07), &[(Coil, "A1 A2"), (Changeover, "15 16 18")]); + p.voltage = "24 V DC".into(); + + let p = c.add("GEN.MPS-2.5-4A", "Motor protection switch 2.5 - 4 A", sd, "Motor protection switch", "Q", 61.0, (45.0, 97.0, 97.0, 0.3), &[(MotorProtection, main3)]); + p.current = "2.5 - 4 A".into(); + p.accessories = vec!["GEN.MPS-AUX-1NO1NC".into()]; + let p = c.add("GEN.MPS-4-6.3A", "Motor protection switch 4 - 6.3 A", sd, "Motor protection switch", "Q", 63.0, (45.0, 97.0, 97.0, 0.3), &[(MotorProtection, main3)]); + p.current = "4 - 6.3 A".into(); + p.accessories = vec!["GEN.MPS-AUX-1NO1NC".into()]; + c.add("GEN.MPS-AUX-1NO1NC", "Auxiliary switch for motor protection switch, 1 NO + 1 NC", sd, "Auxiliary switch", "Q", 12.9, (9.0, 90.0, 60.0, 0.02), &[(No, "13 14"), (Nc, "21 22")]); + let p = c.add("GEN.MCB-1P-C6", "Miniature circuit breaker 1P C6", sd, "Circuit breaker", "F", 8.7, (18.0, 90.0, 70.0, 0.12), &[(Breaker1, "1 2")]); + p.current = "6 A".into(); + let p = c.add("GEN.MCB-1P-B10", "Miniature circuit breaker 1P B10", sd, "Circuit breaker", "F", 8.7, (18.0, 90.0, 70.0, 0.12), &[(Breaker1, "1 2")]); + p.current = "10 A".into(); + let p = c.add("GEN.MCB-3P-C16", "Miniature circuit breaker 3P C16", sd, "Circuit breaker", "Q", 27.3, (54.0, 90.0, 70.0, 0.36), &[(Breaker3, main3)]); + p.current = "16 A".into(); + let p = c.add("GEN.FUSE-5X20-2A", "Fuse holder 5x20 mm with fuse 2 A", sd, "Fuse", "F", 4.2, (8.0, 60.0, 50.0, 0.02), &[(Fuse, "1 2")]); + p.current = "2 A".into(); + let p = c.add("GEN.OL-2.8-4A", "Thermal overload relay 2.8 - 4 A, 1 NO + 1 NC", sd, "Overload relay", "F", 44.0, (45.0, 70.0, 80.0, 0.15), &[(Overload, main3), (Nc, "95 96"), (No, "97 98")]); + p.current = "2.8 - 4 A".into(); + + c.add("GEN.PB-GN-1NO", "Pushbutton green, 1 NO", sw, "Pushbutton", "S", 11.2, (30.0, 30.0, 45.0, 0.03), &[(PushbuttonNo, "13 14")]).accessories = vec!["GEN.CB-1NO".into(), "GEN.CB-1NC".into()]; + c.add("GEN.PB-RD-1NC", "Pushbutton red, 1 NC", sw, "Pushbutton", "S", 11.2, (30.0, 30.0, 45.0, 0.03), &[(PushbuttonNc, "11 12")]).accessories = vec!["GEN.CB-1NO".into(), "GEN.CB-1NC".into()]; + c.add("GEN.ESTOP-1NC", "Emergency stop mushroom 40 mm, twist release, 1 NC", sw, "Emergency stop", "S", 24.6, (40.0, 40.0, 60.0, 0.06), &[(PushbuttonNc, "11 12")]).accessories = vec!["GEN.CB-1NC".into()]; + c.add("GEN.SEL-2POS-1NO", "Selector switch 2 positions, 1 NO", sw, "Selector switch", "S", 15.9, (30.0, 30.0, 45.0, 0.03), &[(SwitchNo, "13 14")]); + c.add("GEN.CB-1NO", "Contact block 1 NO for front mounting", sw, "Contact block", "S", 4.9, (10.0, 30.0, 40.0, 0.01), &[(No, "13 14")]); + c.add("GEN.CB-1NC", "Contact block 1 NC for front mounting", sw, "Contact block", "S", 4.9, (10.0, 30.0, 40.0, 0.01), &[(Nc, "21 22")]); + let p = c.add("GEN.PROX-M12-PNP", "Inductive proximity sensor M12, PNP NO, Sn 4 mm", sw, "Proximity sensor", "B", 29.0, (12.0, 12.0, 60.0, 0.05), &[(Sensor, "BN BK")]); + p.voltage = "10 - 30 V DC".into(); + c.add("GEN.LIMIT-1NO1NC", "Position switch roller plunger, 1 NO + 1 NC", sw, "Position switch", "B", 32.0, (31.0, 60.0, 33.0, 0.1), &[(Sensor, "13 14"), (Nc, "21 22")]); + + let p = c.add("GEN.LMP-GN-24", "Indicator lamp green, LED 24 V", "Signal devices", "Indicator lamp", "P", 9.1, (30.0, 30.0, 45.0, 0.02), &[(Signal, "X1 X2")]); + p.voltage = "24 V AC/DC".into(); + let p = c.add("GEN.LMP-RD-24", "Indicator lamp red, LED 24 V", "Signal devices", "Indicator lamp", "P", 9.1, (30.0, 30.0, 45.0, 0.02), &[(Signal, "X1 X2")]); + p.voltage = "24 V AC/DC".into(); + c.add("GEN.HORN-24", "Panel buzzer 24 V, 85 dB", "Signal devices", "Horn", "P", 18.0, (30.0, 30.0, 50.0, 0.03), &[(Signal, "1 2")]); + + let p = c.add("GEN.MOT-0.75KW", "Three-phase motor 0.75 kW 400 V, 1400 rpm", "Motors", "Three-phase motor", "M", 180.0, (0.0, 0.0, 0.0, 9.5), &[(Motor3, "U1 V1 W1 PE")]); + p.voltage = "400 V".into(); + p.current = "1.9 A".into(); + p.power = "0.75 kW".into(); + let p = c.add("GEN.MOT-1PH-0.25KW", "Single-phase motor 0.25 kW 230 V", "Motors", "Single-phase motor", "M", 140.0, (0.0, 0.0, 0.0, 5.0), &[(Motor1, "L N PE")]); + p.power = "0.25 kW".into(); + + 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")]); + + 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()]; + c.add("GEN.TB-PE-2.5", "Protective earth terminal 2.5 mm², green-yellow", "Terminals", "PE terminal", "X", 1.8, (5.2, 48.0, 36.0, 0.01), &[(Terminal, "")]); + c.add("GEN.TB-END", "End plate for terminal 2.5 mm²", "Terminals", "Accessories", "X", 0.3, (1.5, 48.0, 36.0, 0.002), &[]); + + let di: Vec<(FnKind, String)> = (0..16).map(|i| (PlcInput, format!("I{}.{}", i / 8, i % 8))).collect(); + let di: Vec<(FnKind, &str)> = di.iter().map(|(k, s)| (*k, s.as_str())).collect(); + c.add("GEN.PLC-DI16", "PLC digital input module 16 x 24 V DC", "PLC", "Digital input module", "A", 145.0, (25.0, 100.0, 75.0, 0.15), &di); + let dq: Vec<(FnKind, String)> = (0..16).map(|i| (PlcOutput, format!("Q{}.{}", i / 8, i % 8))).collect(); + let dq: Vec<(FnKind, &str)> = dq.iter().map(|(k, s)| (*k, s.as_str())).collect(); + c.add("GEN.PLC-DO16", "PLC digital output module 16 x 24 V DC 0.5 A", "PLC", "Digital output module", "A", 165.0, (25.0, 100.0, 75.0, 0.15), &dq); + + let p = c.add("GEN.SV-24DC", "Solenoid valve coil 24 V DC, 4.8 W", "Valves", "Solenoid valve", "Y", 22.5, (0.0, 0.0, 0.0, 0.1), &[(Valve, "A1 A2")]); + p.voltage = "24 V DC".into(); + p.power = "4.8 W".into(); + + c.add("GEN.RES-1K", "Resistor 1 kΩ 0.6 W", "Passive components", "Resistor", "R", 0.1, (0.0, 0.0, 0.0, 0.0), &[(Generic, "1 2")]); + c.add("GEN.CAP-100N", "Capacitor 100 nF 63 V", "Passive components", "Capacitor", "C", 0.15, (0.0, 0.0, 0.0, 0.0), &[(Generic, "1 2")]); + c.add("GEN.DIODE-1N4007", "Rectifier diode 1 A 1000 V", "Passive components", "Diode", "V", 0.08, (0.0, 0.0, 0.0, 0.0), &[(Generic, "A K")]); + + let p = c.add("GEN.RAIL-TS35-1M", "Mounting rail TS 35 x 7.5, perforated, 1 m", "Mounting", "Mounting rail", "", 6.5, (1000.0, 35.0, 7.5, 0.35), &[]); + p.quantity_unit = "m".into(); + p.mounting.clear(); + let p = c.add("GEN.DUCT-40X60", "Cable duct 40 x 60 mm, 2 m", "Mounting", "Cable duct", "", 11.0, (2000.0, 40.0, 60.0, 0.9), &[]); + p.pack_quantity = 10; + 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(); + + let mut parts = c.parts; + for p in &mut parts { + if let Some((m2, m3)) = generated_models(p) { + p.model_2d = Some(m2); + p.model_3d = Some(m3); + } + } + parts.sort_by(|a, b| natural_cmp(&a.number, &b.number)); + parts +} + +/// Shape family of the generated example models. +#[derive(Clone, Copy, PartialEq)] +enum Shape { + /// DIN rail device: base, raised front, screw terminals top and bottom. + Din { toggle: bool, display: bool }, + /// Feed-through terminal: thin block with two screws. + Terminal, + /// PLC I/O module: tall block with an LED / connector column. + Plc, + /// Door / field device (pushbutton, lamp, sensor): round front. + Round, +} + +fn shape_of(p: &Part) -> Option { + if p.width <= 0.0 || p.height <= 0.0 || p.depth <= 0.0 || p.group == "Mounting" { + return None; + } + Some(match p.subgroup.as_str() { + "Feed-through terminal" | "PE terminal" | "Accessories" => Shape::Terminal, + "Digital input module" | "Digital output module" | "CPU" => Shape::Plc, + "Circuit breaker" | "Motor protection switch" | "Auxiliary switch" => Shape::Din { toggle: true, display: false }, + "Power supply" | "Timer relay" => Shape::Din { toggle: false, display: true }, + _ if p.group == "Sensors, switches, pushbuttons" || p.group == "Signal devices" => Shape::Round, + _ => Shape::Din { toggle: false, display: false }, + }) +} + +/// Simple 2D front view and 3D model with exactly the part's mounting dimensions. +fn generated_models(p: &Part) -> Option<(Model2d, Mesh3d)> { + let shape = shape_of(p)?; + let (w, h, d) = (p.width, p.height, p.depth); + let mut m3 = Mesh3d::default(); + let mut prims: Vec = vec![Prim2d::Rect { min: [0.0, 0.0], max: [w, h], fill: false }]; + // 2D uses y down from the top, 3D y up from the bottom. + let rect = |prims: &mut Vec, x0: f32, y0: f32, x1: f32, y1: f32, fill: bool| { + prims.push(Prim2d::Rect { min: [x0, h - y1], max: [x1, h - y0], fill }) + }; + match shape { + Shape::Din { toggle, display } => { + let base = d * 0.6; + m3.add_box([0.0, 0.0, 0.0], [w, h, base]); + // Raised front in the middle third + let (f0, f1) = (h * 0.3, h * 0.7); + m3.add_box([w * 0.05, f0, base], [w * 0.95, f1, if toggle || display { d * 0.92 } else { d }]); + rect(&mut prims, w * 0.05, f0, w * 0.95, f1, false); + // Screw terminals on the steps above and below the front + let n = ((w / 9.0).floor() as usize).clamp(1, 6); + let pitch = w / n as f32; + for i in 0..n { + let cx = pitch * (i as f32 + 0.5); + let r = (pitch * 0.28).min(3.0); + for cy in [h * 0.15, h * 0.85] { + m3.add_box([cx - r, cy - r, base], [cx + r, cy + r, base + 1.5]); + prims.push(Prim2d::Circle { c: [cx, h - cy], r, fill: false }); + prims.push(Prim2d::Line { a: [cx - r * 0.7, h - cy], b: [cx + r * 0.7, h - cy] }); + } + } + if toggle { + let (tw, th) = ((w * 0.35).min(8.0), h * 0.12); + let (cx, cy) = (w / 2.0, h / 2.0); + m3.add_box([cx - tw / 2.0, cy - th / 2.0, d * 0.92], [cx + tw / 2.0, cy + th / 2.0, d]); + rect(&mut prims, cx - tw / 2.0, cy - th / 2.0, cx + tw / 2.0, cy + th / 2.0, true); + } + if display { + let (cx, cy) = (w / 2.0, h * 0.58); + let (dw, dh) = (w * 0.6, h * 0.08); + m3.add_box([cx - dw / 2.0, cy - dh / 2.0, d * 0.92], [cx + dw / 2.0, cy + dh / 2.0, d]); + rect(&mut prims, cx - dw / 2.0, cy - dh / 2.0, cx + dw / 2.0, cy + dh / 2.0, false); + prims.push(Prim2d::Circle { c: [cx, h - h * 0.42], r: (w * 0.08).min(3.0), fill: false }); + } + } + Shape::Terminal => { + m3.add_box([0.0, 0.0, 0.0], [w, h, d * 0.7]); + m3.add_box([w * 0.1, h * 0.35, d * 0.7], [w * 0.9, h * 0.65, d]); + let r = (w * 0.3).min(2.0); + for cy in [h * 0.18, h * 0.82] { + prims.push(Prim2d::Circle { c: [w / 2.0, h - cy], r, fill: false }); + } + rect(&mut prims, w * 0.1, h * 0.35, w * 0.9, h * 0.65, false); + } + Shape::Plc => { + m3.add_box([0.0, 0.0, 0.0], [w, h, d * 0.85]); + m3.add_box([w * 0.15, h * 0.08, d * 0.85], [w * 0.85, h * 0.92, d]); + rect(&mut prims, w * 0.15, h * 0.08, w * 0.85, h * 0.92, false); + for i in 0..8 { + let y = h * 0.14 + i as f32 * h * 0.095; + prims.push(Prim2d::Rect { min: [w * 0.25, y], max: [w * 0.4, y + h * 0.03], fill: true }); + prims.push(Prim2d::Line { a: [w * 0.5, y + h * 0.015], b: [w * 0.75, y + h * 0.015] }); + } + } + Shape::Round => { + m3.add_box([0.0, 0.0, 0.0], [w, h, d * 0.8]); + m3.add_box([w * 0.15, h * 0.15, d * 0.8], [w * 0.85, h * 0.85, d]); + prims.push(Prim2d::Circle { c: [w / 2.0, h / 2.0], r: w.min(h) * 0.42, fill: false }); + prims.push(Prim2d::Circle { c: [w / 2.0, h / 2.0], r: w.min(h) * 0.3, fill: true }); + } + } + Some((Model2d { width: w, height: h, prims }, m3)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-parts/src/catalog/tests.rs b/crates/openecraft-parts/src/catalog/tests.rs new file mode 100644 index 00000000..f1a7414c --- /dev/null +++ b/crates/openecraft-parts/src/catalog/tests.rs @@ -0,0 +1,37 @@ +use super::*; + +#[test] +fn catalog_numbers_unique_and_accessories_exist() { + let parts = default_catalog(); + for (i, p) in parts.iter().enumerate() { + assert!(parts[i + 1..].iter().all(|q| q.number != p.number), "duplicate {}", p.number); + for a in &p.accessories { + assert!(parts.iter().any(|q| &q.number == a), "{} accessory {a} missing", p.number); + } + } +} + +#[test] +fn generated_models_match_mounting_data() { + let parts = default_catalog(); + let mut with_models = 0; + for p in &parts { + match (&p.model_2d, &p.model_3d) { + (Some(m2), Some(m3)) => { + with_models += 1; + let s = m3.size(); + for (got, want) in [(s[0], p.width), (s[1], p.height), (s[2], p.depth)] { + assert!((got - want).abs() < 0.01, "{}: model {s:?} vs {} x {} x {}", p.number, p.width, p.height, p.depth); + } + assert_eq!((m2.width, m2.height), (p.width, p.height), "{}", p.number); + assert!(m3.triangles.iter().flatten().all(|&i| (i as usize) < m3.vertices.len())); + } + (None, None) => { + // Mounting material and parts without dimensions have no model. + assert!(p.group == "Mounting" || p.width == 0.0 || p.depth == 0.0, "{} has no model", p.number); + } + _ => panic!("{}: only one of the models", p.number), + } + } + assert!(with_models >= 25, "{with_models}"); +} diff --git a/crates/openecraft-parts/src/csv.rs b/crates/openecraft-parts/src/csv.rs new file mode 100644 index 00000000..e175c6d0 --- /dev/null +++ b/crates/openecraft-parts/src/csv.rs @@ -0,0 +1,214 @@ +//! CSV / JSON import and export of parts. + +use crate::{FnKind, FunctionTemplate, Part, PartsDb, TopGroup}; + +const CSV_FIELDS: [&str; 29] = [ + "Part number", + "Type number", + "Order number", + "Manufacturer", + "Supplier", + "Description", + "Note", + "Product top group", + "Product group", + "Product subgroup", + "Identifier", + "Price", + "Currency", + "Price unit", + "Pack quantity", + "Quantity unit", + "Voltage", + "Current", + "Power", + "Technical data", + "Certificates", + "Datasheet", + "Width", + "Height", + "Depth", + "Weight", + "Mounting", + "Functions", + "Accessories", +]; + +fn csv_escape(s: &str) -> String { + if s.contains([';', '"', '\n', '\r']) { + format!("\"{}\"", s.replace('"', "\"\"")) + } else { + s.to_string() + } +} + +pub fn to_csv(parts: &[Part]) -> String { + let mut out = CSV_FIELDS.join(";"); + out.push('\n'); + for p in parts { + let functions = p + .functions + .iter() + .map(|f| format!("{}:{}", f.kind.short(), f.pins)) + .collect::>() + .join("|"); + let top = match p.top_group { + TopGroup::Electrical => "Electrical", + TopGroup::Fluid => "Fluid", + TopGroup::Mechanics => "Mechanics", + }; + let row = [ + p.number.clone(), + p.type_number.clone(), + p.order_number.clone(), + p.manufacturer.clone(), + p.supplier.clone(), + p.description.clone(), + p.note.clone(), + top.to_string(), + p.group.clone(), + p.subgroup.clone(), + p.identifier.clone(), + format!("{:.2}", p.price), + p.currency.clone(), + p.price_unit.to_string(), + p.pack_quantity.to_string(), + p.quantity_unit.clone(), + p.voltage.clone(), + p.current.clone(), + p.power.clone(), + p.tech_data.clone(), + p.certificates.clone(), + p.datasheet.clone(), + p.width.to_string(), + p.height.to_string(), + p.depth.to_string(), + p.weight.to_string(), + p.mounting.clone(), + functions, + p.accessories.join(","), + ]; + out.push_str(&row.iter().map(|c| csv_escape(c)).collect::>().join(";")); + out.push('\n'); + } + out +} + +/// Splits CSV text (separator `;` or `,`) into records, honouring quotes. +fn parse_csv(text: &str) -> Vec> { + let sep = if text.lines().next().map(|l| l.contains(';')).unwrap_or(true) { ';' } else { ',' }; + let mut rows = Vec::new(); + let mut row = Vec::new(); + let mut cell = String::new(); + let mut quoted = false; + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' if quoted && chars.peek() == Some(&'"') => { + cell.push('"'); + chars.next(); + } + '"' => quoted = !quoted, + c if c == sep && !quoted => row.push(std::mem::take(&mut cell)), + '\r' if !quoted => {} + '\n' if !quoted => { + row.push(std::mem::take(&mut cell)); + if row.iter().any(|c| !c.is_empty()) { + rows.push(std::mem::take(&mut row)); + } else { + row.clear(); + } + } + c => cell.push(c), + } + } + if !cell.is_empty() || !row.is_empty() { + row.push(cell); + rows.push(row); + } + rows +} + +/// Reads parts from CSV. Columns are matched by header name; unknown columns are ignored. +pub fn from_csv(text: &str) -> Result, String> { + let rows = parse_csv(text.trim_start_matches('\u{feff}')); + let Some((header, data)) = rows.split_first() else { return Err("empty file".into()) }; + let col = |name: &str| header.iter().position(|h| h.trim().eq_ignore_ascii_case(name)); + if col("Part number").is_none() { + return Err("column 'Part number' missing".into()); + } + let idx: Vec> = CSV_FIELDS.iter().map(|f| col(f)).collect(); + let mut parts = Vec::new(); + for r in data { + let get = |i: usize| idx[i].and_then(|c| r.get(c)).map(|s| s.trim().to_string()).unwrap_or_default(); + let num = |i: usize| get(i).replace(',', ".").parse::().unwrap_or(0.0); + let int = |i: usize, d: u32| get(i).parse::().unwrap_or(d); + let number = get(0); + if number.is_empty() { + continue; + } + let top_group = match get(7).to_lowercase().as_str() { + s if s.starts_with("fluid") => TopGroup::Fluid, + s if s.starts_with("mech") => TopGroup::Mechanics, + _ => TopGroup::Electrical, + }; + let functions = get(27) + .split('|') + .filter(|s| !s.trim().is_empty()) + .filter_map(|s| { + let (k, pins) = s.split_once(':').unwrap_or((s, "")); + FnKind::from_short(k).map(|k| FunctionTemplate::new(k, pins.trim())) + }) + .collect(); + parts.push(Part { + number, + type_number: get(1), + order_number: get(2), + manufacturer: get(3), + supplier: get(4), + description: get(5), + note: get(6), + top_group, + group: get(8), + subgroup: get(9), + identifier: get(10), + price: num(11), + currency: if get(12).is_empty() { "EUR".into() } else { get(12) }, + price_unit: int(13, 1).max(1), + pack_quantity: int(14, 1).max(1), + quantity_unit: if get(15).is_empty() { "pcs".into() } else { get(15) }, + voltage: get(16), + current: get(17), + power: get(18), + tech_data: get(19), + certificates: get(20), + datasheet: get(21), + width: num(22), + height: num(23), + depth: num(24), + weight: num(25), + mounting: get(26), + functions, + accessories: get(28).split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(), + // 2D / 3D models are only exchanged as JSON. + model_2d: None, + model_3d: None, + }); + } + Ok(parts) +} + +/// Imports a parts file (JSON database / part list or CSV). Returns the parts. +pub fn import(text: &str) -> Result, String> { + let t = text.trim_start_matches('\u{feff}').trim_start(); + if t.starts_with('{') { + serde_json::from_str::(t).map(|d| d.parts).map_err(|e| e.to_string()) + } else if t.starts_with('[') { + serde_json::from_str::>(t).map_err(|e| e.to_string()) + } else { + from_csv(t) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-parts/src/csv/tests.rs b/crates/openecraft-parts/src/csv/tests.rs new file mode 100644 index 00000000..83bd5eff --- /dev/null +++ b/crates/openecraft-parts/src/csv/tests.rs @@ -0,0 +1,23 @@ +use super::*; +use crate::default_catalog; + +#[test] +fn csv_roundtrip() { + let parts = default_catalog(); + let csv = to_csv(&parts); + let back = from_csv(&csv).unwrap(); + assert_eq!(parts.len(), back.len()); + for (a, b) in parts.iter().zip(&back) { + assert_eq!(a.number, b.number); + assert_eq!(a.functions, b.functions); + assert_eq!(a.accessories, b.accessories); + assert_eq!(a.description, b.description); + } +} + +#[test] +fn json_import() { + let db = PartsDb::default(); + let json = serde_json::to_string(&db).unwrap(); + assert_eq!(import(&json).unwrap().len(), db.parts.len()); +} diff --git a/crates/openecraft-parts/src/graphics.rs b/crates/openecraft-parts/src/graphics.rs new file mode 100644 index 00000000..bb8882d5 --- /dev/null +++ b/crates/openecraft-parts/src/graphics.rs @@ -0,0 +1,535 @@ +//! Graphical models of parts: a 2D front view (for mounting layouts) and a 3D mesh +//! (for the 3D panel view), with importers for SVG, STL and OBJ. +//! +//! Units are millimetres. +//! - 2D: origin at the top left corner of the front view, x to the right, y down. +//! - 3D: x to the right, y up, z towards the viewer (out of the mounting plate). + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Largest mesh accepted by the importers. +pub const MAX_TRIANGLES: usize = 200_000; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum Prim2d { + Line { a: [f32; 2], b: [f32; 2] }, + Rect { min: [f32; 2], max: [f32; 2], #[serde(default)] fill: bool }, + Circle { c: [f32; 2], r: f32, #[serde(default)] fill: bool }, + Polyline { pts: Vec<[f32; 2]>, #[serde(default)] closed: bool, #[serde(default)] fill: bool }, + Text { pos: [f32; 2], text: String, size: f32 }, +} + +/// Front view of a part. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Model2d { + pub width: f32, + pub height: f32, + pub prims: Vec, +} + +/// Triangle mesh of a part. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Mesh3d { + pub vertices: Vec<[f32; 3]>, + pub triangles: Vec<[u32; 3]>, +} + +impl Mesh3d { + /// Axis aligned bounding box (min, max). + pub fn bounds(&self) -> ([f32; 3], [f32; 3]) { + let mut min = [f32::INFINITY; 3]; + let mut max = [f32::NEG_INFINITY; 3]; + for v in &self.vertices { + for k in 0..3 { + min[k] = min[k].min(v[k]); + max[k] = max[k].max(v[k]); + } + } + if self.vertices.is_empty() { + ([0.0; 3], [0.0; 3]) + } else { + (min, max) + } + } + + /// Width, height, depth. + pub fn size(&self) -> [f32; 3] { + let (min, max) = self.bounds(); + [max[0] - min[0], max[1] - min[1], max[2] - min[2]] + } + + /// Moves the mesh so that its bounding box starts at the origin. + pub fn normalize(&mut self) { + let (min, _) = self.bounds(); + for v in &mut self.vertices { + for k in 0..3 { + v[k] -= min[k]; + } + } + } + + pub fn scale(&mut self, f: f32) { + for v in &mut self.vertices { + for c in v.iter_mut() { + *c *= f; + } + } + self.normalize(); + } + + /// Rotates by 90° around an axis (0 = x, 1 = y, 2 = z), right handed. + pub fn rotate90(&mut self, axis: usize) { + for v in &mut self.vertices { + let [x, y, z] = *v; + *v = match axis { + 0 => [x, -z, y], + 1 => [z, y, -x], + _ => [-y, x, z], + }; + } + self.normalize(); + } + + /// Adds an axis aligned box (outward facing, counter clockwise triangles). + pub fn add_box(&mut self, min: [f32; 3], max: [f32; 3]) { + let base = self.vertices.len() as u32; + for i in 0..8u32 { + self.vertices.push([ + if i & 4 == 0 { min[0] } else { max[0] }, + if i & 2 == 0 { min[1] } else { max[1] }, + if i & 1 == 0 { min[2] } else { max[2] }, + ]); + } + // Faces as quads of corner indices (bits: x y z), counter clockwise from outside. + let quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]; + for q in quads { + self.triangles.push([base + q[0], base + q[1], base + q[2]]); + self.triangles.push([base + q[0], base + q[2], base + q[3]]); + } + } +} + +/// Collects triangles and merges identical vertices. +struct MeshBuilder { + mesh: Mesh3d, + index: HashMap<(i64, i64, i64), u32>, +} + +impl MeshBuilder { + fn new() -> MeshBuilder { + MeshBuilder { mesh: Mesh3d::default(), index: HashMap::new() } + } + + fn vertex(&mut self, v: [f32; 3]) -> u32 { + let key = ((v[0] * 1000.0).round() as i64, (v[1] * 1000.0).round() as i64, (v[2] * 1000.0).round() as i64); + if let Some(&i) = self.index.get(&key) { + return i; + } + let i = self.mesh.vertices.len() as u32; + self.mesh.vertices.push(v); + self.index.insert(key, i); + i + } + + fn triangle(&mut self, a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> Result<(), String> { + if self.mesh.triangles.len() >= MAX_TRIANGLES { + return Err(format!("model has more than {MAX_TRIANGLES} triangles")); + } + let t = [self.vertex(a), self.vertex(b), self.vertex(c)]; + if t[0] != t[1] && t[1] != t[2] && t[0] != t[2] { + self.mesh.triangles.push(t); + } + Ok(()) + } + + fn finish(mut self) -> Result { + if self.mesh.triangles.is_empty() { + return Err("no triangles found".into()); + } + if self.mesh.vertices.iter().flatten().any(|c| !c.is_finite()) { + return Err("invalid coordinates".into()); + } + self.mesh.normalize(); + Ok(self.mesh) + } +} + +/// Reads an STL file (ASCII or binary). +pub fn parse_stl(bytes: &[u8]) -> Result { + let is_ascii = bytes.starts_with(b"solid") && { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(1024)]).to_lowercase(); + head.contains("facet") || head.contains("endsolid") + }; + let mut b = MeshBuilder::new(); + if is_ascii { + let text = String::from_utf8_lossy(bytes); + let mut verts: Vec<[f32; 3]> = Vec::new(); + for line in text.lines() { + let mut it = line.split_whitespace(); + match it.next() { + Some("vertex") => { + let c: Vec = it.filter_map(|x| x.parse().ok()).collect(); + if c.len() != 3 { + return Err(format!("invalid vertex line: {line}")); + } + verts.push([c[0], c[1], c[2]]); + } + Some("endloop") => { + // Facets are usually triangles; larger loops are fanned. + for i in 1..verts.len().saturating_sub(1) { + b.triangle(verts[0], verts[i], verts[i + 1])?; + } + verts.clear(); + } + _ => {} + } + } + } else { + if bytes.len() < 84 { + return Err("file too short for a binary STL".into()); + } + let n = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize; + if bytes.len() < 84 + n * 50 { + return Err("binary STL is truncated".into()); + } + let f = |o: usize| f32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]); + for t in 0..n { + let o = 84 + t * 50 + 12; // skip the normal + let v = |k: usize| [f(o + k * 12), f(o + k * 12 + 4), f(o + k * 12 + 8)]; + b.triangle(v(0), v(1), v(2))?; + } + } + b.finish() +} + +/// Reads a Wavefront OBJ file (vertices and faces; polygons are fanned). +pub fn parse_obj(text: &str) -> Result { + let mut verts: Vec<[f32; 3]> = Vec::new(); + let mut b = MeshBuilder::new(); + for line in text.lines() { + let mut it = line.split_whitespace(); + match it.next() { + Some("v") => { + let c: Vec = it.take(3).filter_map(|x| x.parse().ok()).collect(); + if c.len() != 3 { + return Err(format!("invalid vertex line: {line}")); + } + verts.push([c[0], c[1], c[2]]); + } + Some("f") => { + let idx: Result, String> = it + .map(|tok| { + let i: i64 = tok.split('/').next().unwrap_or("").parse().map_err(|_| format!("invalid face: {line}"))?; + let i = if i < 0 { verts.len() as i64 + i } else { i - 1 }; + if i < 0 || i as usize >= verts.len() { + return Err(format!("face index out of range: {line}")); + } + Ok(i as usize) + }) + .collect(); + let idx = idx?; + for i in 1..idx.len().saturating_sub(1) { + b.triangle(verts[idx[0]], verts[idx[i]], verts[idx[i + 1]])?; + } + } + _ => {} + } + } + b.finish() +} + +/// Reads a 3D model by file name extension (`.stl` or `.obj`). +pub fn parse_mesh(name: &str, bytes: &[u8]) -> Result { + let lower = name.to_lowercase(); + if lower.ends_with(".obj") { + parse_obj(&String::from_utf8_lossy(bytes)) + } else if lower.ends_with(".stl") { + parse_stl(bytes) + } else { + Err("unsupported 3D format (use STL or OBJ)".into()) + } +} + +// ---------------------------------------------------------------------- SVG + +/// Attributes of an SVG element. +fn attributes(tag: &str) -> HashMap { + let mut map = HashMap::new(); + let chars: Vec = tag.chars().collect(); + let mut i = 0; + // Skip the element name + while i < chars.len() && !chars[i].is_whitespace() { + i += 1; + } + while i < chars.len() { + while i < chars.len() && (chars[i].is_whitespace() || chars[i] == '/') { + i += 1; + } + let start = i; + while i < chars.len() && chars[i] != '=' && !chars[i].is_whitespace() { + i += 1; + } + let name: String = chars[start..i].iter().collect(); + while i < chars.len() && (chars[i].is_whitespace() || chars[i] == '=') { + i += 1; + } + if i < chars.len() && (chars[i] == '"' || chars[i] == '\'') { + let q = chars[i]; + i += 1; + let vs = i; + while i < chars.len() && chars[i] != q { + i += 1; + } + map.insert(name, chars[vs..i].iter().collect()); + i += 1; + } else if !name.is_empty() { + map.insert(name, String::new()); + } + } + map +} + +fn numbers(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let flush = |cur: &mut String, out: &mut Vec| { + if let Ok(v) = cur.parse() { + out.push(v); + } + cur.clear(); + }; + for c in s.chars() { + match c { + '0'..='9' | '.' | 'e' | 'E' => { + // A second '.' starts a new number ("1.5.5" = 1.5 .5) + if c == '.' && cur.contains('.') && !cur.contains(['e', 'E']) { + flush(&mut cur, &mut out); + } + cur.push(c); + } + '-' | '+' if !(cur.ends_with('e') || cur.ends_with('E')) => { + flush(&mut cur, &mut out); + cur.push(c); + } + '-' | '+' => cur.push(c), + _ => flush(&mut cur, &mut out), + } + } + flush(&mut cur, &mut out); + out +} + +/// Length in mm ("10mm", "1cm", "2in", "30" = user units). +fn length_mm(s: &str) -> Option<(f32, bool)> { + let s = s.trim(); + let (num, unit) = s.split_at(s.find(|c: char| c.is_alphabetic() || c == '%').unwrap_or(s.len())); + let v: f32 = num.trim().parse().ok()?; + match unit.trim() { + "mm" => Some((v, true)), + "cm" => Some((v * 10.0, true)), + "in" => Some((v * 25.4, true)), + "pt" => Some((v * 25.4 / 72.0, true)), + "px" | "" => Some((v, false)), + _ => None, + } +} + +/// Path data → polylines (curves are approximated by their end points). +fn path_polylines(d: &str) -> Vec<(Vec<[f32; 2]>, bool)> { + let mut out = Vec::new(); + let mut cur: Vec<[f32; 2]> = Vec::new(); + let (mut x, mut y) = (0.0f32, 0.0f32); + let mut start = [0.0f32, 0.0f32]; + // Split into commands with their numbers + let mut cmds: Vec<(char, Vec)> = Vec::new(); + let mut buf = String::new(); + let mut cmd: Option = None; + for c in d.chars() { + if c.is_ascii_alphabetic() && c != 'e' && c != 'E' { + if let Some(k) = cmd { + cmds.push((k, numbers(&buf))); + } + cmd = Some(c); + buf.clear(); + } else { + buf.push(c); + } + } + if let Some(k) = cmd { + cmds.push((k, numbers(&buf))); + } + let finish = |cur: &mut Vec<[f32; 2]>, closed: bool, out: &mut Vec<(Vec<[f32; 2]>, bool)>| { + if cur.len() >= 2 { + out.push((std::mem::take(cur), closed)); + } else { + cur.clear(); + } + }; + for (k, n) in cmds { + let rel = k.is_ascii_lowercase(); + let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) }; + // number of values per segment + let step = match k.to_ascii_uppercase() { + 'M' | 'L' | 'T' => 2, + 'H' | 'V' => 1, + 'S' | 'Q' => 4, + 'C' => 6, + 'A' => 7, + _ => 0, + }; + match k.to_ascii_uppercase() { + 'Z' => { + x = start[0]; + y = start[1]; + finish(&mut cur, true, &mut out); + } + _ if step == 0 => {} + _ => { + for (seg, chunk) in n.chunks(step).enumerate() { + if chunk.len() < step { + break; + } + let (ox, oy) = if rel { (x, y) } else { (ox, oy) }; + match k.to_ascii_uppercase() { + 'H' => x = chunk[0] + ox, + 'V' => y = chunk[0] + oy, + _ => { + x = chunk[step - 2] + ox; + y = chunk[step - 1] + oy; + } + } + if k.eq_ignore_ascii_case(&'M') && seg == 0 { + finish(&mut cur, false, &mut out); + start = [x, y]; + } + cur.push([x, y]); + } + } + } + } + finish(&mut cur, false, &mut out); + out +} + +/// Reads the drawing elements of an SVG file (`line`, `rect`, `circle`, `ellipse`, +/// `polyline`, `polygon`, `path`, `text`). Transforms are not applied and curves are +/// approximated by straight lines. Sizes in mm are taken from `width` / `height`, +/// otherwise one user unit is one millimetre. +pub fn parse_svg(text: &str) -> Result { + let svg_start = text.find("').ok_or("broken element")? + svg_start; + let root = attributes(&text[svg_start + 1..svg_end]); + let view: Vec = root.get("viewBox").map(|v| numbers(v)).unwrap_or_default(); + let w = root.get("width").and_then(|v| length_mm(v)); + let h = root.get("height").and_then(|v| length_mm(v)); + let (vx, vy, vw, vh) = if view.len() == 4 { + (view[0], view[1], view[2], view[3]) + } else { + (0.0, 0.0, w.map(|x| x.0).unwrap_or(0.0), h.map(|x| x.0).unwrap_or(0.0)) + }; + // Physical size if width/height carry units, else user units = mm + let (mw, mh) = match (w, h) { + (Some((w, true)), Some((h, true))) => (w, h), + _ => (vw, vh), + }; + let (sx, sy) = if vw > 0.0 && vh > 0.0 { (mw / vw, mh / vh) } else { (1.0, 1.0) }; + let tf = |x: f32, y: f32| [(x - vx) * sx, (y - vy) * sy]; + let filled = |a: &HashMap| { + let style = a.get("style").cloned().unwrap_or_default(); + let from_style = style.split(';').find_map(|kv| kv.trim().strip_prefix("fill:").map(|v| v.trim().to_string())); + match from_style.or_else(|| a.get("fill").cloned()) { + Some(f) => f != "none" && f != "transparent", + None => false, + } + }; + let num = |a: &HashMap, k: &str| a.get(k).and_then(|v| length_mm(v)).map(|x| x.0).unwrap_or(0.0); + + let mut prims = Vec::new(); + let mut rest = &text[svg_end + 1..]; + while let Some(lt) = rest.find('<') { + let gt = rest[lt..].find('>').ok_or("unterminated element")? + lt; + let tag = &rest[lt + 1..gt]; + let name = tag.split_whitespace().next().unwrap_or("").trim_end_matches('/'); + let a = attributes(tag); + match name { + "line" => prims.push(Prim2d::Line { a: tf(num(&a, "x1"), num(&a, "y1")), b: tf(num(&a, "x2"), num(&a, "y2")) }), + "rect" => { + let (x, y) = (num(&a, "x"), num(&a, "y")); + prims.push(Prim2d::Rect { min: tf(x, y), max: tf(x + num(&a, "width"), y + num(&a, "height")), fill: filled(&a) }); + } + "circle" => prims.push(Prim2d::Circle { c: tf(num(&a, "cx"), num(&a, "cy")), r: num(&a, "r") * sx, fill: filled(&a) }), + "ellipse" => { + let (cx, cy, rx, ry) = (num(&a, "cx"), num(&a, "cy"), num(&a, "rx"), num(&a, "ry")); + let pts = (0..=24) + .map(|i| { + let t = i as f32 / 24.0 * std::f32::consts::TAU; + tf(cx + rx * t.cos(), cy + ry * t.sin()) + }) + .collect(); + prims.push(Prim2d::Polyline { pts, closed: true, fill: filled(&a) }); + } + "polyline" | "polygon" => { + let n = numbers(a.get("points").map(String::as_str).unwrap_or("")); + let pts: Vec<[f32; 2]> = n.as_chunks::<2>().0.iter().map(|c| tf(c[0], c[1])).collect(); + if pts.len() >= 2 { + prims.push(Prim2d::Polyline { pts, closed: name == "polygon", fill: filled(&a) && name == "polygon" }); + } + } + "path" => { + let fill = filled(&a); + for (pts, closed) in path_polylines(a.get("d").map(String::as_str).unwrap_or("")) { + let pts = pts.into_iter().map(|p| tf(p[0], p[1])).collect(); + prims.push(Prim2d::Polyline { pts, closed, fill: fill && closed }); + } + } + "text" => { + let end = rest[gt..].find("").map(|e| e + gt).unwrap_or(gt); + let content: String = rest[gt + 1..end].split('<').next().unwrap_or("").trim().to_string(); + let size = a.get("font-size").and_then(|v| length_mm(v)).map(|x| x.0).unwrap_or(3.0) * sy; + if !content.is_empty() { + prims.push(Prim2d::Text { pos: tf(num(&a, "x"), num(&a, "y")), text: content, size }); + } + } + _ => {} + } + rest = &rest[gt + 1..]; + } + if prims.is_empty() { + return Err("no drawing elements found".into()); + } + let (width, height) = if mw > 0.0 && mh > 0.0 { (mw, mh) } else { bounds_2d(&prims) }; + Ok(Model2d { width, height, prims }) +} + +/// Extent of 2D primitives (max x, max y). +fn bounds_2d(prims: &[Prim2d]) -> (f32, f32) { + let mut w: f32 = 0.0; + let mut h: f32 = 0.0; + let mut ext = |p: [f32; 2]| { + w = w.max(p[0]); + h = h.max(p[1]); + }; + for p in prims { + match p { + Prim2d::Line { a, b } => { + ext(*a); + ext(*b); + } + Prim2d::Rect { min, max, .. } => { + ext(*min); + ext(*max); + } + Prim2d::Circle { c, r, .. } => ext([c[0] + r, c[1] + r]), + Prim2d::Polyline { pts, .. } => pts.iter().for_each(|p| ext(*p)), + Prim2d::Text { pos, .. } => ext(*pos), + } + } + (w, h) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-parts/src/graphics/tests.rs b/crates/openecraft-parts/src/graphics/tests.rs new file mode 100644 index 00000000..08cf86c4 --- /dev/null +++ b/crates/openecraft-parts/src/graphics/tests.rs @@ -0,0 +1,135 @@ +use super::*; + +fn unit_box() -> Mesh3d { + let mut m = Mesh3d::default(); + m.add_box([0.0, 0.0, 0.0], [10.0, 20.0, 30.0]); + m +} + +fn close(a: [f32; 3], b: [f32; 3]) -> bool { + (0..3).all(|k| (a[k] - b[k]).abs() < 1e-4) +} + +/// Every triangle of a closed box faces outwards (normal points away from the centre). +fn outward(m: &Mesh3d) -> bool { + let (min, max) = m.bounds(); + let c = [(min[0] + max[0]) / 2.0, (min[1] + max[1]) / 2.0, (min[2] + max[2]) / 2.0]; + m.triangles.iter().all(|t| { + let [a, b, d] = [m.vertices[t[0] as usize], m.vertices[t[1] as usize], m.vertices[t[2] as usize]]; + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let v = [d[0] - a[0], d[1] - a[1], d[2] - a[2]]; + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let to_face = [a[0] - c[0], a[1] - c[1], a[2] - c[2]]; + n[0] * to_face[0] + n[1] * to_face[1] + n[2] * to_face[2] > 0.0 + }) +} + +#[test] +fn box_mesh_and_transforms() { + let mut m = unit_box(); + assert_eq!((m.vertices.len(), m.triangles.len()), (8, 12)); + assert!(close(m.size(), [10.0, 20.0, 30.0])); + assert!(outward(&m)); + m.rotate90(2); // around z: width and height swap + assert!(close(m.size(), [20.0, 10.0, 30.0])); + assert!(close(m.bounds().0, [0.0, 0.0, 0.0])); + m.rotate90(0); // around x: height and depth swap + assert!(close(m.size(), [20.0, 30.0, 10.0])); + assert!(outward(&m)); + m.scale(2.0); + assert!(close(m.size(), [40.0, 60.0, 20.0])); +} + +fn ascii_stl(m: &Mesh3d) -> String { + let mut s = String::from("solid test\n"); + for t in &m.triangles { + s.push_str(" facet normal 0 0 0\n outer loop\n"); + for &i in t { + let v = m.vertices[i as usize]; + s.push_str(&format!(" vertex {} {} {}\n", v[0], v[1], v[2])); + } + s.push_str(" endloop\n endfacet\n"); + } + s.push_str("endsolid test\n"); + s +} + +fn binary_stl(m: &Mesh3d) -> Vec { + let mut b = vec![0u8; 80]; + b.extend((m.triangles.len() as u32).to_le_bytes()); + for t in &m.triangles { + b.extend([0u8; 12]); + for &i in t { + for c in m.vertices[i as usize] { + b.extend(c.to_le_bytes()); + } + } + b.extend([0u8; 2]); + } + b +} + +#[test] +fn stl_ascii_and_binary() { + let m = unit_box(); + for parsed in [parse_stl(ascii_stl(&m).as_bytes()).unwrap(), parse_stl(&binary_stl(&m)).unwrap()] { + // Vertices of neighbouring triangles are merged again. + assert_eq!((parsed.vertices.len(), parsed.triangles.len()), (8, 12)); + assert!(close(parsed.size(), [10.0, 20.0, 30.0])); + assert!(outward(&parsed)); + } + assert!(parse_stl(b"solid x\nendsolid x\n").is_err()); + let mut truncated = binary_stl(&m); + truncated.truncate(200); + assert!(parse_stl(&truncated).unwrap_err().contains("truncated")); + assert!(parse_mesh("model.STL", ascii_stl(&m).as_bytes()).is_ok()); + assert!(parse_mesh("model.step", b"").is_err()); +} + +#[test] +fn obj_with_quads_and_negative_indices() { + let obj = "# cube face\nv 0 0 0\nv 10 0 0\nv 10 10 0\nv 0 10 0\nvt 0 0\nf 1/1/1 2/1/1 3/1/1 4/1/1\nv 0 0 5\nf -1 1 2\n"; + let m = parse_obj(obj).unwrap(); + assert_eq!(m.triangles.len(), 3); + assert!(close(m.size(), [10.0, 10.0, 5.0])); + assert!(parse_obj("v 0 0 0\nf 1 2 3\n").unwrap_err().contains("out of range")); + assert!(parse_obj("o nothing\n").is_err()); +} + +#[test] +fn svg_elements_units_and_paths() { + let svg = r#" + + + + + + + + -K1 +"#; + let m = parse_svg(svg).unwrap(); + assert_eq!((m.width, m.height), (45.0, 90.0)); + // viewBox units are scaled to millimetres (1/10) + assert_eq!(m.prims[1], Prim2d::Rect { min: [5.0, 10.0], max: [40.0, 30.0], fill: true }); + assert_eq!(m.prims[0], Prim2d::Rect { min: [0.0, 0.0], max: [45.0, 90.0], fill: false }); + assert_eq!(m.prims[3], Prim2d::Circle { c: [10.0, 5.0], r: 2.0, fill: false }); + // Relative path commands and closing + let closed = m.prims.iter().find_map(|p| match p { + Prim2d::Polyline { pts, closed: true, .. } if pts.len() == 4 => Some(pts.clone()), + _ => None, + }); + assert_eq!(closed.unwrap(), vec![[1.0, 80.0], [11.0, 80.0], [11.0, 85.0], [1.0, 85.0]]); + assert!(m.prims.iter().any(|p| matches!(p, Prim2d::Polyline { pts, closed: false, .. } if pts == &vec![[21.0, 80.0], [30.0, 85.0]]))); + assert!(m.prims.iter().any(|p| matches!(p, Prim2d::Text { text, size, .. } if text == "-K1" && (*size - 4.0).abs() < 1e-4))); + // Without units one user unit is one millimetre + let plain = parse_svg(r#""#).unwrap(); + assert_eq!((plain.width, plain.height), (20.0, 10.0)); + assert!(parse_svg("").is_err()); + assert!(parse_svg("").is_err()); +} + +#[test] +fn number_lists() { + assert_eq!(numbers("10,20 -5-6 1e2 .5.5"), vec![10.0, 20.0, -5.0, -6.0, 100.0, 0.5, 0.5]); +} diff --git a/crates/openecraft-parts/src/lib.rs b/crates/openecraft-parts/src/lib.rs new file mode 100644 index 00000000..4b8638d0 --- /dev/null +++ b/crates/openecraft-parts/src/lib.rs @@ -0,0 +1,21 @@ +//! Shared parts model of OpenECraft, used by the editor and by the parts server. +//! +//! - [`Part`], [`FunctionTemplate`], [`PartsDb`] … – the part data (EPLAN style +//! product groups, commercial / technical / mounting data, function templates) +//! - CSV / JSON import and export ([`to_csv`], [`from_csv`], [`import`]) +//! - 2D / 3D models of parts with SVG, STL and OBJ import ([`Model2d`], [`Mesh3d`]) +//! - the generic example catalog ([`default_catalog`]) +//! - the HTTP API types of the parts server ([`api`]) + +pub mod api; +mod catalog; +mod csv; +mod graphics; +mod part; +mod text; + +pub use catalog::default_catalog; +pub use csv::{from_csv, import, to_csv}; +pub use graphics::{parse_mesh, parse_obj, parse_stl, parse_svg, Mesh3d, Model2d, Prim2d, MAX_TRIANGLES}; +pub use part::*; +pub use text::natural_cmp; diff --git a/crates/openecraft-parts/src/part.rs b/crates/openecraft-parts/src/part.rs new file mode 100644 index 00000000..7d189aa2 --- /dev/null +++ b/crates/openecraft-parts/src/part.rs @@ -0,0 +1,365 @@ +//! Part data: product groups, function templates, commercial / technical / mounting +//! data and the parts database container. + +use crate::{natural_cmp, Mesh3d, Model2d}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub enum TopGroup { + #[default] + Electrical, + Fluid, + Mechanics, +} + +impl TopGroup { + pub const ALL: [TopGroup; 3] = [TopGroup::Electrical, TopGroup::Fluid, TopGroup::Mechanics]; + + pub fn title(self) -> &'static str { + match self { + TopGroup::Electrical => "Electrical engineering", + TopGroup::Fluid => "Fluid power", + TopGroup::Mechanics => "Mechanics", + } + } +} + +/// Suggested product groups / subgroups (free text is allowed as well). +pub const PRODUCT_GROUPS: &[(&str, &[&str])] = &[ + ("Relays, contactors", &["Power contactor", "Auxiliary contact block", "Relay", "Timer relay"]), + ("Safety devices", &["Motor protection switch", "Circuit breaker", "Fuse", "Overload relay", "Auxiliary switch"]), + ("Sensors, switches, pushbuttons", &["Pushbutton", "Emergency stop", "Selector switch", "Proximity sensor", "Position switch", "Contact block"]), + ("Signal devices", &["Indicator lamp", "Horn"]), + ("Motors", &["Three-phase motor", "Single-phase motor"]), + ("Power supplies, transformers", &["Power supply", "Control transformer"]), + ("Terminals", &["Feed-through terminal", "PE terminal", "Accessories"]), + ("PLC", &["Digital input module", "Digital output module", "CPU"]), + ("Valves", &["Solenoid valve"]), + ("Passive components", &["Resistor", "Capacitor", "Diode"]), + ("Mounting", &["Mounting rail", "Cable duct", "Enclosure"]), +]; + +/// Kinds of functions in a function template. Placed symbols map onto these kinds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub enum FnKind { + Coil, + MainContacts3, + MainContact, + No, + Nc, + Changeover, + PushbuttonNo, + PushbuttonNc, + SwitchNo, + Sensor, + Breaker1, + Breaker3, + MotorProtection, + Overload, + Fuse, + Motor3, + Motor1, + Signal, + PowerSupply, + Transformer, + Terminal, + PlcInput, + PlcOutput, + Valve, + #[default] + Generic, +} + +impl FnKind { + pub const ALL: [FnKind; 25] = [ + FnKind::Coil, + FnKind::MainContacts3, + FnKind::MainContact, + FnKind::No, + FnKind::Nc, + FnKind::Changeover, + FnKind::PushbuttonNo, + FnKind::PushbuttonNc, + FnKind::SwitchNo, + FnKind::Sensor, + FnKind::Breaker1, + FnKind::Breaker3, + FnKind::MotorProtection, + FnKind::Overload, + FnKind::Fuse, + FnKind::Motor3, + FnKind::Motor1, + FnKind::Signal, + FnKind::PowerSupply, + FnKind::Transformer, + FnKind::Terminal, + FnKind::PlcInput, + FnKind::PlcOutput, + FnKind::Valve, + FnKind::Generic, + ]; + + pub fn title(self) -> &'static str { + match self { + FnKind::Coil => "Coil", + FnKind::MainContacts3 => "Main contacts 3-pole", + FnKind::MainContact => "Main contact 1-pole", + FnKind::No => "NO contact", + FnKind::Nc => "NC contact", + FnKind::Changeover => "Changeover contact", + FnKind::PushbuttonNo => "Pushbutton NO", + FnKind::PushbuttonNc => "Pushbutton NC", + FnKind::SwitchNo => "Switch NO", + FnKind::Sensor => "Sensor", + FnKind::Breaker1 => "Circuit breaker 1-pole", + FnKind::Breaker3 => "Circuit breaker 3-pole", + FnKind::MotorProtection => "Motor protection switch", + FnKind::Overload => "Overload relay", + FnKind::Fuse => "Fuse", + FnKind::Motor3 => "Motor 3-phase", + FnKind::Motor1 => "Motor 1-phase", + FnKind::Signal => "Signal device", + FnKind::PowerSupply => "Power supply", + FnKind::Transformer => "Transformer", + FnKind::Terminal => "Terminal", + FnKind::PlcInput => "PLC input", + FnKind::PlcOutput => "PLC output", + FnKind::Valve => "Valve coil", + FnKind::Generic => "Generic function", + } + } + + + pub(crate) fn short(self) -> &'static str { + match self { + FnKind::Coil => "Coil", + FnKind::MainContacts3 => "Main3", + FnKind::MainContact => "Main1", + FnKind::No => "NO", + FnKind::Nc => "NC", + FnKind::Changeover => "CO", + FnKind::PushbuttonNo => "PBNO", + FnKind::PushbuttonNc => "PBNC", + FnKind::SwitchNo => "SWNO", + FnKind::Sensor => "Sensor", + FnKind::Breaker1 => "CB1", + FnKind::Breaker3 => "CB3", + FnKind::MotorProtection => "MPS", + FnKind::Overload => "OL", + FnKind::Fuse => "Fuse", + FnKind::Motor3 => "M3", + FnKind::Motor1 => "M1", + FnKind::Signal => "Signal", + FnKind::PowerSupply => "PSU", + FnKind::Transformer => "Trafo", + FnKind::Terminal => "Terminal", + FnKind::PlcInput => "DI", + FnKind::PlcOutput => "DO", + FnKind::Valve => "Valve", + FnKind::Generic => "Generic", + } + } + + pub(crate) fn from_short(s: &str) -> Option { + FnKind::ALL.into_iter().find(|k| k.short().eq_ignore_ascii_case(s.trim())) + } +} + +/// One function of a function template. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FunctionTemplate { + pub kind: FnKind, + /// Connection point designations in symbol order, separated by blanks ("13 14"). + pub pins: String, + pub description: String, +} + +impl FunctionTemplate { + pub fn new(kind: FnKind, pins: &str) -> FunctionTemplate { + FunctionTemplate { kind, pins: pins.into(), description: String::new() } + } + + pub fn pin_list(&self) -> Vec { + self.pins.split_whitespace().map(String::from).collect() + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Part { + // General + /// Unique key, conventionally `MANUFACTURER.TYPE`. + pub number: String, + pub type_number: String, + pub order_number: String, + pub manufacturer: String, + pub supplier: String, + pub description: String, + pub note: String, + pub top_group: TopGroup, + pub group: String, + pub subgroup: String, + /// Identifying letter of devices using this part (device selection). + pub identifier: String, + // Commercial + pub price: f32, + pub currency: String, + /// The price refers to this many units. + pub price_unit: u32, + pub pack_quantity: u32, + pub quantity_unit: String, + // Technical + pub voltage: String, + pub current: String, + pub power: String, + pub tech_data: String, + pub certificates: String, + pub datasheet: String, + // Mounting + pub width: f32, + pub height: f32, + pub depth: f32, + pub weight: f32, + pub mounting: String, + // Logic + pub functions: Vec, + /// Part numbers of accessories. + pub accessories: Vec, + // Graphics + /// Front view for mounting layouts. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_2d: Option, + /// 3D model for the panel layout. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_3d: Option, +} + +impl Default for Part { + fn default() -> Self { + Part { + number: String::new(), + type_number: String::new(), + order_number: String::new(), + manufacturer: String::new(), + supplier: String::new(), + description: String::new(), + note: String::new(), + top_group: TopGroup::Electrical, + group: String::new(), + subgroup: String::new(), + identifier: String::new(), + price: 0.0, + currency: "EUR".into(), + price_unit: 1, + pack_quantity: 1, + quantity_unit: "pcs".into(), + voltage: String::new(), + current: String::new(), + power: String::new(), + tech_data: String::new(), + certificates: String::new(), + datasheet: String::new(), + width: 0.0, + height: 0.0, + depth: 0.0, + weight: 0.0, + mounting: String::new(), + functions: Vec::new(), + accessories: Vec::new(), + model_2d: None, + model_3d: None, + } + } +} + +impl Part { + /// Price of `qty` units, respecting the price unit. + pub fn total_price(&self, qty: f32) -> f32 { + self.price / self.price_unit.max(1) as f32 * qty + } + + pub fn matches_text(&self, f: &str) -> bool { + if f.is_empty() { + return true; + } + let f = f.to_lowercase(); + [&self.number, &self.type_number, &self.order_number, &self.manufacturer, &self.description, &self.group, &self.subgroup] + .iter() + .any(|s| s.to_lowercase().contains(&f)) + } + + /// Short summary of the function template, e.g. "Coil, Main3, NO". + pub fn template_summary(&self) -> String { + let mut counts: BTreeMap = BTreeMap::new(); + for f in &self.functions { + *counts.entry(f.kind).or_default() += 1; + } + counts + .iter() + .map(|(k, n)| if *n > 1 { format!("{n}× {}", k.title()) } else { k.title().to_string() }) + .collect::>() + .join(", ") + } +} + +/// Reference from a device to a part. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PartRef { + pub number: String, + pub count: u32, +} + +impl Default for PartRef { + fn default() -> Self { + PartRef { number: String::new(), count: 1 } + } +} + +/// The global parts database. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PartsDb { + pub parts: Vec, +} + +impl Default for PartsDb { + fn default() -> Self { + PartsDb { parts: crate::default_catalog() } + } +} + +impl PartsDb { + pub fn get(&self, number: &str) -> Option<&Part> { + self.parts.iter().find(|p| p.number == number) + } + + /// Inserts or replaces a part (by part number). + pub fn upsert(&mut self, part: Part) { + upsert(&mut self.parts, part); + } + + pub fn sort(&mut self) { + self.parts.sort_by(|a, b| natural_cmp(&a.number, &b.number)); + } +} + +pub fn upsert(list: &mut Vec, part: Part) { + match list.iter_mut().find(|p| p.number == part.number) { + Some(existing) => *existing = part, + None => list.push(part), + } +} + +/// A part number that does not exist yet, based on `base`. +pub fn unique_number(list: &[Part], base: &str) -> String { + if !list.iter().any(|p| p.number == base) { + return base.to_string(); + } + (1..) + .map(|i| format!("{base}_{i}")) + .find(|n| !list.iter().any(|p| &p.number == n)) + .unwrap() +} diff --git a/crates/openecraft-parts/src/text.rs b/crates/openecraft-parts/src/text.rs new file mode 100644 index 00000000..e380b370 --- /dev/null +++ b/crates/openecraft-parts/src/text.rs @@ -0,0 +1,33 @@ +//! Text helpers. + +/// Comparison that orders "-K2" before "-K10". +pub fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering { + fn chunks(s: &str) -> Vec<(bool, String)> { + let mut out: Vec<(bool, String)> = Vec::new(); + for c in s.chars() { + let d = c.is_ascii_digit(); + match out.last_mut() { + Some((ld, buf)) if *ld == d => buf.push(c), + _ => out.push((d, c.to_string())), + } + } + out + } + let (ca, cb) = (chunks(a), chunks(b)); + for (x, y) in ca.iter().zip(cb.iter()) { + let ord = if x.0 && y.0 { + let nx: u64 = x.1.parse().unwrap_or(0); + let ny: u64 = y.1.parse().unwrap_or(0); + nx.cmp(&ny).then_with(|| x.1.cmp(&y.1)) + } else { + x.1.cmp(&y.1) + }; + if ord != std::cmp::Ordering::Equal { + return ord; + } + } + ca.len().cmp(&cb.len()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-parts/src/text/tests.rs b/crates/openecraft-parts/src/text/tests.rs new file mode 100644 index 00000000..48a54666 --- /dev/null +++ b/crates/openecraft-parts/src/text/tests.rs @@ -0,0 +1,8 @@ +use super::*; + +#[test] +fn natural_order() { + let mut v = vec!["-K10", "-K2", "-F1", "-K1"]; + v.sort_by(|a, b| natural_cmp(a, b)); + assert_eq!(v, vec!["-F1", "-K1", "-K2", "-K10"]); +} diff --git a/server/Cargo.toml b/server/Cargo.toml new file mode 100644 index 00000000..9ac03c26 --- /dev/null +++ b/server/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "openecraft-server" +version = "0.1.0" +edition = "2021" +description = "Global parts database server for OpenECraft" +license = "MIT OR Apache-2.0" + +[[bin]] +name = "openecraft-server" +path = "src/main.rs" + +[dependencies] +openecraft-parts = { path = "../crates/openecraft-parts" } +axum = "0.8" +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] } +tower-http = { version = "0.7", features = ["cors"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +clap = { version = "4", features = ["derive", "env"] } +log = "0.4" +env_logger = "0.11" + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } +http-body-util = "0.1" diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 00000000..fbd39397 --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,66 @@ +//! OpenECraft parts server: hosts a global parts database for all OpenECraft +//! installations (desktop and web). Runs independently of the editor. +//! +//! ```text +//! openecraft-server --bind 0.0.0.0:8090 --data parts-db.json --token +//! ``` +//! +//! Without `--token` (or `OPENECRAFT_TOKEN`) the server is read-only. + +mod routes; +mod store; + +use clap::Parser; +use openecraft_parts::api::DEFAULT_PORT; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::{Arc, RwLock}; + +#[derive(Parser)] +#[command(version, about = "Global parts database server for OpenECraft")] +struct Args { + /// Address to listen on. + #[arg(long, default_value_t = SocketAddr::from(([127, 0, 0, 1], DEFAULT_PORT)))] + bind: SocketAddr, + /// Database file (created with the example catalog if missing). + #[arg(long, default_value = "parts-db.json")] + data: PathBuf, + /// Access token required for changes. Without a token the server is read-only. + #[arg(long, env = "OPENECRAFT_TOKEN", hide_env_values = true)] + token: Option, +} + +#[tokio::main] +async fn main() { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let args = Args::parse(); + let store = match store::Store::open(&args.data) { + Ok(s) => s, + Err(e) => { + log::error!("cannot open parts database: {e}"); + std::process::exit(1); + } + }; + log::info!("{} parts loaded from {} (revision {})", store.parts.len(), args.data.display(), store.revision); + let token = args.token.filter(|t| !t.trim().is_empty()); + if token.is_none() { + log::warn!("no access token set: the server is read-only"); + } + let state = routes::AppState { store: Arc::new(RwLock::new(store)), token }; + let listener = match tokio::net::TcpListener::bind(args.bind).await { + Ok(l) => l, + Err(e) => { + log::error!("cannot listen on {}: {e}", args.bind); + std::process::exit(1); + } + }; + log::info!("listening on http://{}", args.bind); + let shutdown = async { + tokio::signal::ctrl_c().await.ok(); + log::info!("shutting down"); + }; + if let Err(e) = axum::serve(listener, routes::router(state)).with_graceful_shutdown(shutdown).await { + log::error!("server error: {e}"); + std::process::exit(1); + } +} diff --git a/server/src/routes.rs b/server/src/routes.rs new file mode 100644 index 00000000..6118a998 --- /dev/null +++ b/server/src/routes.rs @@ -0,0 +1,175 @@ +//! HTTP routes of the parts server (see `openecraft_parts::api` for the API). + +use crate::store::Store; +use axum::extract::{DefaultBodyLimit, Path, Query, State}; +use axum::http::{header, HeaderMap, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use openecraft_parts::api::{ApiError, ImportResult, PartList, PartQuery, ServerInfo, API_PREFIX}; +use openecraft_parts::{import, to_csv, Part}; +use std::sync::{Arc, RwLock}; +use tower_http::cors::{Any, CorsLayer}; + +#[derive(Clone)] +pub struct AppState { + pub store: Arc>, + /// Bearer token for write requests. `None` = read-only server. + pub token: Option, +} + +pub struct AppError(StatusCode, String); + +impl IntoResponse for AppError { + fn into_response(self) -> Response { + (self.0, Json(ApiError { error: self.1 })).into_response() + } +} + +impl From for AppError { + fn from(e: std::io::Error) -> Self { + log::error!("storage error: {e}"); + AppError(StatusCode::INTERNAL_SERVER_ERROR, format!("storage error: {e}")) + } +} + +type Result = std::result::Result; + +pub fn router(state: AppState) -> Router { + Router::new() + .route("/", get(index)) + .route(&format!("{API_PREFIX}/info"), get(info)) + .route(&format!("{API_PREFIX}/parts"), get(list)) + .route(&format!("{API_PREFIX}/parts/{{number}}"), get(get_part).put(put_part).delete(delete_part)) + .route(&format!("{API_PREFIX}/import"), post(import_parts)) + .route(&format!("{API_PREFIX}/export.csv"), get(export_csv)) + .layer(DefaultBodyLimit::max(32 * 1024 * 1024)) + .layer(cors()) + .with_state(state) +} + +/// Any origin may call the API (e.g. the web app): authentication uses bearer +/// tokens, not cookies. `Authorization` must be listed explicitly – browsers do not +/// cover it with the `*` wildcard. +fn cors() -> CorsLayer { + CorsLayer::new() + .allow_origin(Any) + .allow_methods([Method::GET, Method::PUT, Method::POST, Method::DELETE]) + .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]) +} + +/// Constant time comparison of the presented token. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn authorize(state: &AppState, headers: &HeaderMap) -> Result<()> { + let Some(token) = &state.token else { + return Err(AppError(StatusCode::FORBIDDEN, "server is read-only (start it with --token to allow changes)".into())); + }; + let presented = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim); + match presented { + Some(p) if same(p, token) => Ok(()), + _ => Err(AppError(StatusCode::UNAUTHORIZED, "missing or wrong access token".into())), + } +} + +fn read(state: &AppState) -> std::sync::RwLockReadGuard<'_, Store> { + state.store.read().unwrap_or_else(|e| e.into_inner()) +} + +fn write(state: &AppState) -> std::sync::RwLockWriteGuard<'_, Store> { + state.store.write().unwrap_or_else(|e| e.into_inner()) +} + +async fn index(State(state): State) -> String { + let store = read(&state); + format!( + "OpenECraft parts server {}\n\n{} parts, revision {}, {}\n\nAPI: {API_PREFIX}/info, {API_PREFIX}/parts, {API_PREFIX}/parts/{{number}}, {API_PREFIX}/import, {API_PREFIX}/export.csv\n", + env!("CARGO_PKG_VERSION"), + store.parts.len(), + store.revision, + if state.token.is_some() { "writable with token" } else { "read-only" } + ) +} + +async fn info(State(state): State) -> Json { + let store = read(&state); + Json(ServerInfo { + name: "OpenECraft parts server".into(), + version: env!("CARGO_PKG_VERSION").into(), + parts: store.parts.len(), + revision: store.revision, + writable: state.token.is_some(), + }) +} + +async fn list(State(state): State, Query(query): Query) -> Json { + let store = read(&state); + let (total, parts) = query.apply(&store.parts); + Json(PartList { revision: store.revision, total, offset: query.offset.unwrap_or(0), parts }) +} + +async fn get_part(State(state): State, Path(number): Path) -> Result> { + let store = read(&state); + store.get(&number).cloned().map(Json).ok_or_else(|| AppError(StatusCode::NOT_FOUND, format!("part '{number}' not found"))) +} + +async fn put_part( + State(state): State, + headers: HeaderMap, + Path(number): Path, + Json(mut part): Json, +) -> Result<(StatusCode, Json)> { + authorize(&state, &headers)?; + if part.number.is_empty() { + part.number = number.clone(); + } + if part.number != number { + return Err(AppError(StatusCode::BAD_REQUEST, "part number in URL and body differ".into())); + } + if number.trim().is_empty() { + return Err(AppError(StatusCode::BAD_REQUEST, "part number must not be empty".into())); + } + let created = write(&state).upsert(part.clone())?; + log::info!("{} part {number}", if created { "created" } else { "updated" }); + Ok((if created { StatusCode::CREATED } else { StatusCode::OK }, Json(part))) +} + +async fn delete_part(State(state): State, headers: HeaderMap, Path(number): Path) -> Result { + authorize(&state, &headers)?; + if write(&state).delete(&number)? { + log::info!("deleted part {number}"); + Ok(StatusCode::NO_CONTENT) + } else { + Err(AppError(StatusCode::NOT_FOUND, format!("part '{number}' not found"))) + } +} + +/// Body: CSV (header names as in the export) or JSON (parts database or part list). +async fn import_parts(State(state): State, headers: HeaderMap, body: String) -> Result> { + authorize(&state, &headers)?; + let parts = import(&body).map_err(|e| AppError(StatusCode::BAD_REQUEST, format!("invalid parts data: {e}")))?; + if parts.iter().any(|p| p.number.trim().is_empty()) { + return Err(AppError(StatusCode::BAD_REQUEST, "every part needs a part number".into())); + } + let mut store = write(&state); + let imported = store.import(parts)?; + log::info!("imported {imported} parts"); + Ok(Json(ImportResult { imported, revision: store.revision })) +} + +async fn export_csv(State(state): State) -> impl IntoResponse { + let store = read(&state); + ( + [(header::CONTENT_TYPE, "text/csv; charset=utf-8"), (header::CONTENT_DISPOSITION, "attachment; filename=\"parts.csv\"")], + to_csv(&store.parts), + ) +} + +#[cfg(test)] +mod tests; diff --git a/server/src/routes/tests.rs b/server/src/routes/tests.rs new file mode 100644 index 00000000..f1834b9e --- /dev/null +++ b/server/src/routes/tests.rs @@ -0,0 +1,138 @@ +use super::*; +use axum::body::Body; +use axum::http::Request; +use http_body_util::BodyExt; +use openecraft_parts::default_catalog; +use tower::ServiceExt; + +const TOKEN: &str = "secret-token"; + +fn app(token: Option<&str>) -> Router { + router(AppState { + store: Arc::new(RwLock::new(Store::in_memory(default_catalog()))), + token: token.map(String::from), + }) +} + +async fn call(app: &Router, method: &str, uri: &str, token: Option<&str>, body: &str) -> (StatusCode, String) { + let mut req = Request::builder().method(method).uri(uri).header(header::CONTENT_TYPE, "application/json"); + if let Some(t) = token { + req = req.header(header::AUTHORIZATION, format!("Bearer {t}")); + } + let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap(); + let status = resp.status(); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + (status, String::from_utf8_lossy(&bytes).to_string()) +} + +#[tokio::test] +async fn info_list_and_get() { + let app = app(None); + let (status, body) = call(&app, "GET", "/api/v1/info", None, "").await; + assert_eq!(status, StatusCode::OK); + let info: ServerInfo = serde_json::from_str(&body).unwrap(); + assert_eq!(info.parts, default_catalog().len()); + assert!(!info.writable); + + let (status, body) = call(&app, "GET", "/api/v1/parts?q=contactor&limit=1", None, "").await; + assert_eq!(status, StatusCode::OK); + let list: PartList = serde_json::from_str(&body).unwrap(); + assert_eq!(list.parts.len(), 1); + assert!(list.total >= 2); + + let (status, body) = call(&app, "GET", "/api/v1/parts/GEN.CT-9A-24DC", None, "").await; + assert_eq!(status, StatusCode::OK); + let part: Part = serde_json::from_str(&body).unwrap(); + assert!(!part.functions.is_empty()); + + let (status, body) = call(&app, "GET", "/api/v1/parts/NOPE", None, "").await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert!(serde_json::from_str::(&body).unwrap().error.contains("NOPE")); +} + +#[tokio::test] +async fn writes_need_the_token() { + let part = r#"{"number": "TEST.1", "description": "Test"}"#; + // Read-only server + let ro = app(None); + assert_eq!(call(&ro, "PUT", "/api/v1/parts/TEST.1", Some(TOKEN), part).await.0, StatusCode::FORBIDDEN); + // Writable server: missing / wrong / correct token + let app = app(Some(TOKEN)); + assert_eq!(call(&app, "PUT", "/api/v1/parts/TEST.1", None, part).await.0, StatusCode::UNAUTHORIZED); + assert_eq!(call(&app, "PUT", "/api/v1/parts/TEST.1", Some("wrong"), part).await.0, StatusCode::UNAUTHORIZED); + assert_eq!(call(&app, "PUT", "/api/v1/parts/TEST.1", Some(TOKEN), part).await.0, StatusCode::CREATED); + assert_eq!(call(&app, "PUT", "/api/v1/parts/TEST.1", Some(TOKEN), part).await.0, StatusCode::OK); + // URL and body must agree + assert_eq!(call(&app, "PUT", "/api/v1/parts/OTHER", Some(TOKEN), part).await.0, StatusCode::BAD_REQUEST); + // Part numbers with special characters are URL encoded + let odd = r#"{"number": "A B/1"}"#; + assert_eq!(call(&app, "PUT", "/api/v1/parts/A%20B%2F1", Some(TOKEN), odd).await.0, StatusCode::CREATED); + assert_eq!(call(&app, "GET", "/api/v1/parts/A%20B%2F1", None, "").await.0, StatusCode::OK); + + assert_eq!(call(&app, "DELETE", "/api/v1/parts/TEST.1", None, "").await.0, StatusCode::UNAUTHORIZED); + assert_eq!(call(&app, "DELETE", "/api/v1/parts/TEST.1", Some(TOKEN), "").await.0, StatusCode::NO_CONTENT); + assert_eq!(call(&app, "DELETE", "/api/v1/parts/TEST.1", Some(TOKEN), "").await.0, StatusCode::NOT_FOUND); + assert_eq!(call(&app, "GET", "/api/v1/parts/TEST.1", None, "").await.0, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn import_and_export() { + let app = app(Some(TOKEN)); + let csv = "Part number;Manufacturer;Description;Functions\nIMP.1;ACME;Imported relay;Coil:A1 A2|CO:11 12 14\n"; + let (status, body) = call(&app, "POST", "/api/v1/import", Some(TOKEN), csv).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let result: ImportResult = serde_json::from_str(&body).unwrap(); + assert_eq!(result.imported, 1); + + let (_, body) = call(&app, "GET", "/api/v1/parts/IMP.1", None, "").await; + let part: Part = serde_json::from_str(&body).unwrap(); + assert_eq!(part.manufacturer, "ACME"); + assert_eq!(part.functions.len(), 2); + + // JSON part list works as well, invalid data is rejected. + let (status, _) = call(&app, "POST", "/api/v1/import", Some(TOKEN), r#"[{"number": "IMP.2"}]"#).await; + assert_eq!(status, StatusCode::OK); + let (status, _) = call(&app, "POST", "/api/v1/import", Some(TOKEN), "{ broken").await; + assert_eq!(status, StatusCode::BAD_REQUEST); + + let (status, csv) = call(&app, "GET", "/api/v1/export.csv", None, "").await; + assert_eq!(status, StatusCode::OK); + let parts = openecraft_parts::from_csv(&csv).unwrap(); + assert!(parts.iter().any(|p| p.number == "IMP.1")); + assert!(parts.iter().any(|p| p.number == "IMP.2")); +} + +#[tokio::test] +async fn revision_increases_on_changes() { + let app = app(Some(TOKEN)); + let rev = |body: String| serde_json::from_str::(&body).unwrap().revision; + let before = rev(call(&app, "GET", "/api/v1/info", None, "").await.1); + call(&app, "PUT", "/api/v1/parts/X", Some(TOKEN), r#"{"number": "X"}"#).await; + let after = rev(call(&app, "GET", "/api/v1/info", None, "").await.1); + assert_eq!(after, before + 1); +} + +#[tokio::test] +async fn cors_preflight_allows_authorization_header() { + let req = Request::builder() + .method("OPTIONS") + .uri("/api/v1/import") + .header(header::ORIGIN, "http://localhost:8080") + .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST") + .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "authorization,content-type") + .body(Body::empty()) + .unwrap(); + let resp = app(Some(TOKEN)).oneshot(req).await.unwrap(); + let h = |name| resp.headers().get(name).and_then(|v| v.to_str().ok()).unwrap_or("").to_lowercase(); + assert_eq!(h(header::ACCESS_CONTROL_ALLOW_ORIGIN), "*"); + // The wildcard would not cover Authorization in browsers. + assert!(h(header::ACCESS_CONTROL_ALLOW_HEADERS).contains("authorization")); + assert!(h(header::ACCESS_CONTROL_ALLOW_METHODS).contains("post")); +} + +#[test] +fn token_comparison() { + assert!(same("abc", "abc")); + assert!(!same("abc", "abd")); + assert!(!same("abc", "abcd")); +} diff --git a/server/src/store.rs b/server/src/store.rs new file mode 100644 index 00000000..cb22661b --- /dev/null +++ b/server/src/store.rs @@ -0,0 +1,110 @@ +//! Persistent parts storage: one JSON file, written atomically on every change. + +use openecraft_parts::{default_catalog, Part}; +use serde::{Deserialize, Serialize}; +use std::io; +use std::path::{Path, PathBuf}; + +/// File format of the database. +#[derive(Default, Serialize, Deserialize)] +#[serde(default)] +struct StoredDb { + revision: u64, + parts: Vec, +} + +pub struct Store { + path: Option, + /// Incremented on every change (clients can detect updates). + pub revision: u64, + pub parts: Vec, +} + +impl Store { + /// A store that is not persisted (tests). + #[cfg(test)] + pub fn in_memory(parts: Vec) -> Store { + Store { path: None, revision: 1, parts } + } + + /// Opens the database file; a missing file is created with the example catalog. + pub fn open(path: &Path) -> io::Result { + if path.exists() { + let text = std::fs::read_to_string(path)?; + let db: StoredDb = + serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display())))?; + Ok(Store { path: Some(path.to_path_buf()), revision: db.revision.max(1), parts: db.parts }) + } else { + let store = Store { path: Some(path.to_path_buf()), revision: 1, parts: default_catalog() }; + store.save()?; + Ok(store) + } + } + + fn save(&self) -> io::Result<()> { + let Some(path) = &self.path else { return Ok(()) }; + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir)?; + } + let db = StoredDb { revision: self.revision, parts: self.parts.clone() }; + let json = serde_json::to_string_pretty(&db).map_err(io::Error::other)?; + // Write a temporary file first so a crash never leaves a half written database. + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, json)?; + std::fs::rename(&tmp, path) + } + + fn changed(&mut self) -> io::Result<()> { + self.revision += 1; + self.save() + } + + pub fn get(&self, number: &str) -> Option<&Part> { + self.parts.iter().find(|p| p.number == number) + } + + /// Inserts or replaces a part. Returns true if it was created. + pub fn upsert(&mut self, part: Part) -> io::Result { + let created = match self.parts.iter_mut().find(|p| p.number == part.number) { + Some(existing) => { + *existing = part; + false + } + None => { + self.parts.push(part); + true + } + }; + self.changed()?; + Ok(created) + } + + /// Removes a part. Returns false if it did not exist. + pub fn delete(&mut self, number: &str) -> io::Result { + let before = self.parts.len(); + self.parts.retain(|p| p.number != number); + if self.parts.len() == before { + return Ok(false); + } + self.changed()?; + Ok(true) + } + + /// Upserts many parts with a single revision step. + pub fn import(&mut self, parts: Vec) -> io::Result { + let n = parts.len(); + for part in parts { + match self.parts.iter_mut().find(|p| p.number == part.number) { + Some(existing) => *existing = part, + None => self.parts.push(part), + } + } + if n > 0 { + self.changed()?; + } + Ok(n) + } +} + +#[cfg(test)] +mod tests; diff --git a/server/src/store/tests.rs b/server/src/store/tests.rs new file mode 100644 index 00000000..157be3db --- /dev/null +++ b/server/src/store/tests.rs @@ -0,0 +1,53 @@ +use super::*; + +fn temp_file(name: &str) -> PathBuf { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + std::env::temp_dir().join(format!("openecraft-test-{}-{nanos}", std::process::id())).join(name) +} + +#[test] +fn new_database_is_seeded_and_changes_persist() { + let path = temp_file("parts.json"); + let mut store = Store::open(&path).unwrap(); + assert!(path.exists()); + assert_eq!(store.parts.len(), default_catalog().len()); + let rev = store.revision; + + let part = Part { number: "TEST.1".into(), description: "Test part".into(), ..Default::default() }; + assert!(store.upsert(part.clone()).unwrap()); + assert!(!store.upsert(part).unwrap()); + assert!(store.delete("GEN.CT-9A-24DC").unwrap()); + assert!(!store.delete("does-not-exist").unwrap()); + assert_eq!(store.revision, rev + 3); + + // Reopen: everything is still there, no temporary file left. + let again = Store::open(&path).unwrap(); + assert_eq!(again.revision, rev + 3); + assert_eq!(again.get("TEST.1").unwrap().description, "Test part"); + assert!(again.get("GEN.CT-9A-24DC").is_none()); + assert!(!path.with_extension("tmp").exists()); + std::fs::remove_dir_all(path.parent().unwrap()).ok(); +} + +#[test] +fn import_is_one_revision() { + let mut store = Store::in_memory(Vec::new()); + let parts = vec![ + Part { number: "A".into(), ..Default::default() }, + Part { number: "B".into(), ..Default::default() }, + ]; + assert_eq!(store.import(parts).unwrap(), 2); + assert_eq!(store.revision, 2); + assert_eq!(store.import(Vec::new()).unwrap(), 0); + assert_eq!(store.revision, 2); +} + +#[test] +fn invalid_file_is_an_error() { + let path = temp_file("broken.json"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "{ not json").unwrap(); + let err = Store::open(&path).err().unwrap(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + std::fs::remove_dir_all(path.parent().unwrap()).ok(); +} diff --git a/src/app.rs b/src/app.rs index 0576a56e..86b5b73a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -59,12 +59,18 @@ impl App { let mut prj: Option = None; let mut file_name = None; let mut parts_db: Option = None; + let mut server_url: Option = 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"); } let parts_db = parts_db.unwrap_or_default(); + let mut parts_ui = PartsUi::default(); + if let Some(url) = server_url { + parts_ui.server.url = url; + } let mut prj = prj.unwrap_or_else(sample::demo_project); prj.normalize(); let history = History::new(&prj); @@ -86,7 +92,7 @@ impl App { report_kind: ReportKind::DeviceList, show_project: false, parts_db, - parts_ui: PartsUi::default(), + parts_ui, workspace: Workspace::Schematic, panel_ui: PanelUi::default(), show_help: false, @@ -189,8 +195,16 @@ impl App { fn poll_loaded(&mut self, ctx: &egui::Context) { if let Some(loaded) = self.io.poll() { + if matches!(loaded.purpose, Purpose::Model2d | Purpose::Model3d) { + let msg = match self.parts_ui.apply_model(&loaded, &mut self.parts_db, &mut self.prj) { + Ok(m) => m, + Err(e) => format!("Model import failed: {e}"), + }; + self.notify(ctx, msg); + return; + } if loaded.purpose == Purpose::Parts { - match parts::import(&loaded.content) { + match parts::import(&loaded.text()) { Ok(list) => { let n = list.len(); for p in list { @@ -203,7 +217,7 @@ impl App { } return; } - match serde_json::from_str::(&loaded.content) { + match serde_json::from_str::(&loaded.text()) { Ok(prj) => { self.replace_project(prj, Some(loaded.name.clone())); self.notify(ctx, format!("Opened {}", io::short_name(&loaded.name))); @@ -1042,6 +1056,7 @@ impl App { for action in self.parts_ui.manager(ctx, &mut self.parts_db, &mut self.prj) { match action { PartsAction::Import => self.io.open(ctx, Purpose::Parts), + PartsAction::ImportModel(purpose) => self.io.open(ctx, purpose), PartsAction::Export { name, filter, content } => self.export(ctx, name, filter, content), PartsAction::Message(m) => self.notify(ctx, m), } @@ -1178,6 +1193,9 @@ impl eframe::App for App { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); self.poll_loaded(&ctx); + if let Some(msg) = self.parts_ui.poll_server(&mut self.parts_db) { + self.notify(&ctx, msg); + } self.shortcuts(&ctx); self.page = self.page.min(self.prj.pages.len().saturating_sub(1)); @@ -1265,5 +1283,6 @@ impl eframe::App for App { eframe::set_value(storage, "project", &self.prj); 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); } } diff --git a/src/conventions/tests.rs b/src/conventions/tests.rs index 45afb983..5771dd47 100644 --- a/src/conventions/tests.rs +++ b/src/conventions/tests.rs @@ -13,18 +13,44 @@ fn rust_files(dir: &Path) -> Vec { out } +/// Workspace root (the application crate is the root package). +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +/// `src` directories of all workspace members (from `[workspace] members` in Cargo.toml). +fn source_dirs() -> Vec { + let manifest = std::fs::read_to_string(root().join("Cargo.toml")).unwrap(); + let members = manifest.split("members = [").nth(1).and_then(|r| r.split(']').next()).expect("workspace members"); + let dirs: Vec = members + .split(',') + .map(|m| m.trim().trim_matches('"')) + .filter(|m| !m.is_empty()) + .map(|m| root().join(m).join("src")) + .collect(); + assert!(dirs.len() >= 2, "workspace members not found"); + dirs +} + +fn all_rust_files() -> Vec { + source_dirs().iter().flat_map(|d| rust_files(d)).collect() +} + +fn display(path: &Path) -> String { + path.strip_prefix(root()).unwrap_or(path).display().to_string().replace('\\', "/") +} + fn is_test_file(path: &Path) -> bool { path.file_name().and_then(|n| n.to_str()) == Some("tests.rs") } -/// Unit tests live in `src//tests.rs`, never inline in the module file. +/// Unit tests live in `/src//tests.rs`, never inline in the module file. #[test] fn unit_tests_are_in_separate_files() { - let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut violations = Vec::new(); - for path in rust_files(&src).into_iter().filter(|p| !is_test_file(p)) { + for path in all_rust_files().into_iter().filter(|p| !is_test_file(p)) { let text = std::fs::read_to_string(&path).unwrap(); - let name = path.strip_prefix(&src).unwrap().display().to_string(); + let name = display(&path); let lines: Vec<&str> = text.lines().collect(); for (i, line) in lines.iter().enumerate() { let t = line.trim(); @@ -45,9 +71,8 @@ fn unit_tests_are_in_separate_files() { /// Every `tests.rs` belongs to a module file next to its directory (`foo.rs` + `foo/tests.rs`). #[test] fn test_files_belong_to_a_module() { - let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut orphans = Vec::new(); - for path in rust_files(&src).into_iter().filter(|p| is_test_file(p)) { + for path in all_rust_files().into_iter().filter(|p| is_test_file(p)) { let dir = path.parent().unwrap(); let module_file = dir.with_extension("rs"); let declared = std::fs::read_to_string(&module_file) @@ -56,8 +81,8 @@ fn test_files_belong_to_a_module() { if !declared { orphans.push(format!( "{} is not declared via `#[cfg(test)] mod tests;` in {}", - path.strip_prefix(&src).unwrap().display(), - module_file.strip_prefix(&src).unwrap_or(&module_file).display() + display(&path), + display(&module_file) )); } } @@ -65,5 +90,13 @@ fn test_files_belong_to_a_module() { } fn tests_path(module_file: &str) -> String { - format!("src/{}/tests.rs", module_file.trim_end_matches(".rs")) + format!("{}/tests.rs", module_file.trim_end_matches(".rs")) +} + +#[test] +fn all_workspace_crates_are_checked() { + let dirs = source_dirs(); + for member in ["src", "crates/openecraft-parts/src", "server/src"] { + assert!(dirs.iter().any(|d| d.ends_with(member)), "{member} missing in {dirs:?}"); + } } diff --git a/src/glyphs/tests.rs b/src/glyphs/tests.rs index bdbfd80e..5dbfb2e3 100644 --- a/src/glyphs/tests.rs +++ b/src/glyphs/tests.rs @@ -25,12 +25,14 @@ fn source_files(dir: &Path) -> Vec { fn all_ui_characters_exist_in_bundled_fonts() { let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); let font = FontId::new(14.0, FontFamily::Proportional); - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + // The application and the parts library (catalog texts are shown in the UI). + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); let mut missing: BTreeMap> = BTreeMap::new(); let mut checked = 0; - for path in source_files(&dir) { + let files = [root.join("src"), root.join("crates/openecraft-parts/src")].iter().flat_map(|d| source_files(d)).collect::>(); + for path in files { let src = std::fs::read_to_string(&path).unwrap(); - let name = path.strip_prefix(&dir).unwrap_or(&path).display().to_string(); + let name = path.strip_prefix(root).unwrap_or(&path).display().to_string(); for (line, c) in literal_chars(&src) { if c.is_ascii() || c.is_whitespace() { continue; diff --git a/src/io.rs b/src/io.rs index 5787d07b..a882c169 100644 --- a/src/io.rs +++ b/src/io.rs @@ -9,6 +9,10 @@ pub enum Purpose { Project, /// Import into the parts database. Parts, + /// 2D front view of a part (SVG). + Model2d, + /// 3D model of a part (STL, OBJ). + Model3d, } impl Purpose { @@ -16,6 +20,8 @@ impl Purpose { match self { Purpose::Project => ("OpenECraft project", &[PROJECT_EXT, "json"]), Purpose::Parts => ("Parts (CSV, JSON)", &["csv", "json", "txt"]), + Purpose::Model2d => ("2D front view (SVG)", &["svg"]), + Purpose::Model3d => ("3D model (STL, OBJ)", &["stl", "obj"]), } } } @@ -24,7 +30,14 @@ pub struct Loaded { pub purpose: Purpose, /// Native: full path. Web: file name. pub name: String, - pub content: String, + /// Raw file content (binary STL files are not text). + pub bytes: Vec, +} + +impl Loaded { + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.bytes).into_owned() + } } #[derive(Default, Clone)] @@ -49,10 +62,10 @@ impl FileIo { else { return; }; - match std::fs::read_to_string(&path) { - Ok(content) => { + match std::fs::read(&path) { + Ok(bytes) => { if let Ok(mut inbox) = self.inbox.lock() { - inbox.push(Loaded { purpose, name: path.display().to_string(), content }); + inbox.push(Loaded { purpose, name: path.display().to_string(), bytes }); } } Err(e) => log::error!("Could not read {}: {e}", path.display()), @@ -73,9 +86,8 @@ impl FileIo { return; }; let bytes = file.read().await; - let content = String::from_utf8_lossy(&bytes).to_string(); if let Ok(mut inbox) = inbox.lock() { - inbox.push(Loaded { purpose, name: file.file_name(), content }); + inbox.push(Loaded { purpose, name: file.file_name(), bytes }); } ctx.request_repaint(); }); diff --git a/src/main.rs b/src/main.rs index 62d1199a..29b589a5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,6 +21,7 @@ mod ops; mod panel; mod panel_ui; mod parts; +mod parts_server; mod parts_ui; mod render; mod reports; diff --git a/src/model.rs b/src/model.rs index 16b483b6..dbf9b9bf 100644 --- a/src/model.rs +++ b/src/model.rs @@ -6,6 +6,7 @@ use crate::geom::{p, P}; pub use crate::panel::Layout; +pub use openecraft_parts::natural_cmp; pub use crate::parts::{Part, PartRef}; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -386,34 +387,6 @@ impl Project { } } -/// Comparison that orders "-K2" before "-K10". -pub fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering { - fn chunks(s: &str) -> Vec<(bool, String)> { - let mut out: Vec<(bool, String)> = Vec::new(); - for c in s.chars() { - let d = c.is_ascii_digit(); - match out.last_mut() { - Some((ld, buf)) if *ld == d => buf.push(c), - _ => out.push((d, c.to_string())), - } - } - out - } - let (ca, cb) = (chunks(a), chunks(b)); - for (x, y) in ca.iter().zip(cb.iter()) { - let ord = if x.0 && y.0 { - let nx: u64 = x.1.parse().unwrap_or(0); - let ny: u64 = y.1.parse().unwrap_or(0); - nx.cmp(&ny).then_with(|| x.1.cmp(&y.1)) - } else { - x.1.cmp(&y.1) - }; - if ord != std::cmp::Ordering::Equal { - return ord; - } - } - ca.len().cmp(&cb.len()) -} #[cfg(test)] mod tests; diff --git a/src/model/tests.rs b/src/model/tests.rs index 71bbcce2..c47d839a 100644 --- a/src/model/tests.rs +++ b/src/model/tests.rs @@ -1,12 +1,5 @@ use super::*; -#[test] -fn natural_order() { - let mut v = vec!["-K10", "-K2", "-F1", "-K1"]; - v.sort_by(|a, b| natural_cmp(a, b)); - assert_eq!(v, vec!["-F1", "-K1", "-K2", "-K10"]); -} - #[test] fn columns() { assert_eq!(column_of(p(AREA_X0 + 1.0, 50.0)), 1); diff --git a/src/panel.rs b/src/panel.rs index 9b528a76..f2a151e2 100644 --- a/src/panel.rs +++ b/src/panel.rs @@ -231,6 +231,66 @@ pub struct DeviceSize { pub from_part: bool, } +/// Width, height and depth of a part: the mounting data, or the size of its 3D model +/// when the part has no mounting data. +pub fn part_dims(part: &crate::parts::Part) -> Option<[f32; 3]> { + let model = part.model_3d.as_ref().map(|m| m.size()).filter(|s| s[0] > 0.0 && s[1] > 0.0); + if part.width > 0.0 && part.height > 0.0 { + let depth = if part.depth > 0.0 { part.depth } else { model.map(|s| s[2]).unwrap_or(0.0) }; + Some([part.width, part.height, depth]) + } else { + model + } +} + +/// Number of copies of a model of width `model_w` side by side in an item of width +/// `item_w` (terminal strips show one model per terminal). +pub fn tiles(item_w: f32, model_w: f32) -> usize { + if model_w <= 0.0 { + return 1; + } + let n = (item_w / model_w).round(); + if n >= 2.0 && (n * model_w - item_w).abs() < 0.5 { + n as usize + } else { + 1 + } +} + +/// Triangles of a part's 3D model placed into a device on the plate, in plate +/// coordinates (x right, y down, z = height above the plate). The model is fitted +/// into the device box; rotated devices turn the model by 90° about the front axis, +/// terminal strips repeat it once per terminal. Winding (outside) is preserved. +pub fn place_mesh(mesh: &crate::parts::Mesh3d, it: &PanelItem) -> Vec<[[f32; 3]; 3]> { + let (min, _) = mesh.bounds(); + let [mw, mh, md] = mesh.size(); + if mw <= 0.0 || mh <= 0.0 || md <= 0.0 { + return Vec::new(); + } + let same = |a: f32, b: f32| (a - b).abs() < 0.5; + let rotated = !same(mw, mh) && same(it.w, mh) && same(it.h, mw); + let n = if rotated { 1 } else { tiles(it.w, mw) }; + let cell_w = it.w / n as f32; + let sz = it.d / md; + let mut out = Vec::with_capacity(mesh.triangles.len() * n); + for tile in 0..n { + let x0 = it.x + tile as f32 * cell_w; + let tf = |v: [f32; 3]| { + let (x, y_up, z) = (v[0] - min[0], v[1] - min[1], v[2] - min[2]); + if rotated { + // Quarter turn: model up becomes plate right, model right becomes plate down. + [it.x + y_up * (it.w / mh), it.y + x * (it.h / mw), it.z + z * sz] + } else { + [x0 + x * (cell_w / mw), it.y + (mh - y_up) * (it.h / mh), it.z + z * sz] + } + }; + for t in &mesh.triangles { + out.push([tf(mesh.vertices[t[0] as usize]), tf(mesh.vertices[t[1] as usize]), tf(mesh.vertices[t[2] as usize])]); + } + } + out +} + /// Footprint of a device from its parts: the first part with mounting data gives /// width / height; further parts (e.g. auxiliary blocks) add their depth. Terminal /// strips are as wide as all their terminals together. @@ -241,19 +301,21 @@ pub fn device_size(prj: &Project, tag: &str) -> Option { .iter() .filter_map(|r| prj.parts.iter().find(|x| x.number == r.number).map(|pd| (pd, r.count.max(1)))) .collect(); - let (main, _) = parts.iter().find(|(pd, _)| pd.width > 0.0 && pd.height > 0.0)?; + let (main, [mw, mh, md]) = parts.iter().find_map(|(pd, _)| part_dims(pd).map(|dims| (*pd, dims)))?; let terminals = parts::placed_functions(prj, tag).iter().filter(|f| f.0 == FnKind::Terminal).count(); - let mut w = main.width; + let mut w = mw; if terminals > 0 && main.functions.iter().all(|f| f.kind == FnKind::Terminal) { - w = main.width * terminals as f32; + w = mw * terminals as f32; } - let mut d = main.depth; + let mut d = md; for (pd, count) in &parts { - if pd.number != main.number && pd.depth > 0.0 && pd.width > 0.0 && pd.width <= main.width + 1.0 { - d += pd.depth * *count as f32; + if let (true, Some([aw, _, ad])) = (pd.number != main.number, part_dims(pd)) { + if aw <= mw + 1.0 { + d += ad * *count as f32; + } } } - Some(DeviceSize { tag: tag.into(), part: main.number.clone(), w, h: main.height, d, from_part: true }) + Some(DeviceSize { tag: tag.into(), part: main.number.clone(), w, h: mh, d, from_part: true }) } /// Devices with parts that are not placed in any enclosure yet. Devices whose parts diff --git a/src/panel/tests.rs b/src/panel/tests.rs index 9e3af6ed..be2fde66 100644 --- a/src/panel/tests.rs +++ b/src/panel/tests.rs @@ -156,3 +156,88 @@ fn wire_hit_test_and_cycling() { assert_eq!(next_candidate(&[4, 7, 9], Some(1)), Some(4)); assert_eq!(next_candidate(&[], Some(1)), None); } + +fn within(tris: &[[[f32; 3]; 3]], it: &PanelItem) -> bool { + tris.iter().flatten().all(|v| { + v[0] >= it.x - 0.01 + && v[0] <= it.x + it.w + 0.01 + && v[1] >= it.y - 0.01 + && v[1] <= it.y + it.h + 0.01 + && v[2] >= it.z - 0.01 + && v[2] <= it.z + it.d + 0.01 + }) +} + +fn extent(tris: &[[[f32; 3]; 3]]) -> [f32; 3] { + 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]); + } + } + [max[0] - min[0], max[1] - min[1], max[2] - min[2]] +} + +#[test] +fn part_models_are_fitted_into_devices() { + let prj = demo_project(); + let (ei, k1) = prj.layout.find_device("-K1").unwrap(); + let part = prj.parts.iter().find(|p| p.number == k1.part).unwrap(); + let mesh = part.model_3d.as_ref().expect("catalog contactor has a 3D model"); + // Contactor + aux block: the model (73 deep) is stretched to the device depth (113). + let tris = place_mesh(mesh, k1); + assert_eq!(tris.len(), mesh.triangles.len()); + assert!(within(&tris, k1)); + let e = extent(&tris); + assert!((e[0] - k1.w).abs() < 0.01 && (e[1] - k1.h).abs() < 0.01 && (e[2] - k1.d).abs() < 0.01, "{e:?}"); + + // Rotated device: the model is turned, not squeezed. + let mut rotated = k1.clone(); + rotated.rotate(); + let tris = place_mesh(mesh, &rotated); + assert!(within(&tris, &rotated)); + assert!((extent(&tris)[0] - rotated.w).abs() < 0.01); + + // Terminal strip: one terminal model per terminal. + let (_, x1) = prj.layout.find_device("-X1").unwrap(); + let tb = prj.parts.iter().find(|p| p.number == x1.part).unwrap().model_3d.as_ref().unwrap(); + assert_eq!(tiles(x1.w, tb.size()[0]), 4); + let tris = place_mesh(tb, x1); + assert_eq!(tris.len(), tb.triangles.len() * 4); + assert!(within(&tris, x1)); + assert_eq!(ei, 0); +} + +#[test] +fn model_size_is_used_without_mounting_data() { + let mut prj = demo_project(); + // Remove the mounting data of the lamp part but give it a 3D model. + let part = prj.parts.iter_mut().find(|p| p.number == "GEN.LMP-GN-24").unwrap(); + part.width = 0.0; + part.height = 0.0; + part.depth = 0.0; + let mut mesh = crate::parts::Mesh3d::default(); + mesh.add_box([0.0, 0.0, 0.0], [22.0, 22.0, 50.0]); + part.model_3d = Some(mesh); + assert_eq!(part_dims(part), Some([22.0, 22.0, 50.0])); + let size = device_size(&prj, "-P1").unwrap(); + assert_eq!((size.w, size.h, size.d), (22.0, 22.0, 50.0)); + assert_eq!(tiles(20.8, 5.2), 4); + assert_eq!(tiles(45.0, 45.0), 1); + assert_eq!(tiles(30.0, 7.0), 1); +} + +#[test] +fn mounting_page_draws_part_models() { + let mut prj = demo_project(); + let page = prj.pages.iter().position(|pg| matches!(pg.kind, crate::model::PageKind::Mounting(_))).unwrap(); + let with = crate::svg::page_svg(&prj, page); + for p in &mut prj.parts { + p.model_2d = None; + } + let without = crate::svg::page_svg(&prj, page); + // Terminal screws of the generated front views are circles. + assert!(with.matches(" without.matches(", color: Color32, item: Option }, + Face { pts: Vec, color: Color32, item: Option, outline: bool }, Line { a: Pos2, b: Pos2, color: Color32, width: f32 }, } // (layer, depth, primitive): walls and plate are always behind the equipment @@ -911,7 +911,7 @@ impl PanelUi { if layer == OUTER_WALLS { color = color.gamma_multiply(0.6); } - prims.push((layer, depth, Prim::Face { pts: pr.into_iter().map(|x| x.0).collect(), color, item })); + prims.push((layer, depth, Prim::Face { pts: pr.into_iter().map(|x| x.0).collect(), color, item, outline: true })); } }; // Enclosure: rear wall and inner side walls (door open) @@ -947,6 +947,28 @@ impl PanelUi { ItemKind::Device => Color32::from_rgb(170, 186, 210), } }; + // Devices with a 3D model in their part are drawn with it instead of a box. + 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 n = norm(cross(sub3(w[1], w[0]), sub3(w[2], w[0]))); + if dot(n, sub3(eye, w[0])) <= 0.0 { + continue; // back face + } + let Some(pr) = w.iter().map(|q| project(*q)).collect::>>() else { continue }; + let depth = pr.iter().map(|x| x.1).sum::() / 3.0; + let shade = 0.55 + 0.45 * dot(n, light).max(0.0); + let color = Color32::from_rgb( + (base.r() as f32 * shade) as u8, + (base.g() as f32 * shade) as u8, + (base.b() as f32 * shade) as u8, + ); + let pts = pr.into_iter().map(|x| x.0).collect(); + prims.push((5, depth, Prim::Face { pts, color, item: Some(it.id), outline: false })); + } + 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 layer = match it.kind { @@ -984,8 +1006,10 @@ impl PanelUi { let mut pick: Vec<(f32, Vec, u64)> = Vec::new(); for (_, depth, prim) in &prims { match prim { - Prim::Face { pts, color, item } => { - painter.add(Shape::convex_polygon(pts.clone(), *color, Stroke::new(0.6, color.gamma_multiply(0.6)))); + Prim::Face { pts, color, item, outline } => { + // Mesh triangles get a hairline in their own colour to close the seams. + let stroke = if *outline { Stroke::new(0.6, color.gamma_multiply(0.6)) } else { Stroke::new(0.5, *color) }; + painter.add(Shape::convex_polygon(pts.clone(), *color, stroke)); if let Some(id) = item { pick.push((*depth, pts.clone(), *id)); } @@ -1061,6 +1085,53 @@ impl PanelUi { } } +/// Small shaded view of a mesh; drag to rotate. +pub fn mesh_preview(ui: &mut egui::Ui, mesh: &crate::parts::Mesh3d, size: Vec2) { + let (resp, painter) = ui.allocate_painter(size, Sense::drag()); + let id = resp.id.with("angles"); + let (mut yaw, mut pitch): (f32, f32) = ui.data(|d| d.get_temp(id)).unwrap_or((0.6, 0.35)); + if resp.dragged() { + yaw -= resp.drag_delta().x * 0.01; + pitch = (pitch + resp.drag_delta().y * 0.01).clamp(-1.5, 1.5); + ui.data_mut(|d| d.insert_temp(id, (yaw, pitch))); + } + let dark = ui.visuals().dark_mode; + painter.rect_filled(resp.rect, 4.0, if dark { Color32::from_rgb(30, 32, 36) } else { Color32::from_rgb(232, 235, 240) }); + let s = mesh.size(); + let (min, _) = mesh.bounds(); + let c = [min[0] + s[0] / 2.0, min[1] + s[1] / 2.0, min[2] + s[2] / 2.0]; + let cam = Camera { yaw, pitch, dist: 1.0, target: c }; + let (eye_dir, right, up, fwd) = cam_basis(&cam); + let view = sub3(eye_dir, c); // direction towards the viewer + let radius = (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt().max(1e-3) / 2.0; + let scale = size.x.min(size.y) * 0.45 / radius; + let center = resp.rect.center(); + let light = norm([0.35, 0.75, 0.55]); + let mut tris: Vec<(f32, [Pos2; 3], Color32)> = Vec::new(); + for t in &mesh.triangles { + let v = t.map(|i| mesh.vertices[i as usize]); + let n = norm(cross(sub3(v[1], v[0]), sub3(v[2], v[0]))); + if dot(n, view) <= 0.0 { + continue; + } + let pts = v.map(|q| { + let d = sub3(q, c); + center + vec2(dot(d, right), -dot(d, up)) * scale + }); + let depth = v.iter().map(|q| dot(sub3(*q, c), fwd)).sum::(); + let shade = 0.5 + 0.5 * dot(n, light).max(0.0); + let g = (190.0 * shade) as u8; + tris.push((depth, pts, Color32::from_rgb(g, g.saturating_add(6), g.saturating_add(14)))); + } + tris.sort_by(|a, b| b.0.total_cmp(&a.0)); + for (_, pts, color) in tris { + painter.add(Shape::convex_polygon(pts.to_vec(), color, Stroke::new(0.5, color))); + } + if resp.hovered() { + painter.text(resp.rect.left_bottom() + vec2(4.0, -4.0), egui::Align2::LEFT_BOTTOM, "drag to rotate", egui::FontId::proportional(10.0), Color32::GRAY); + } +} + fn apply_enclosure_part(ne: &mut NewEnclosure, db: &PartsDb) { if let Some(p) = db.get(&ne.part) { if p.width > 0.0 && p.height > 0.0 { diff --git a/src/parts.rs b/src/parts.rs index 173e757f..e351a72c 100644 --- a/src/parts.rs +++ b/src/parts.rs @@ -1,391 +1,42 @@ -//! Parts management modelled after EPLAN: a global parts database (independent of -//! projects) with product groups, commercial / technical / mounting data and -//! function templates; projects keep copies of the parts they use ("project parts"). +//! Parts management in the application: re-exports the shared part model of the +//! `openecraft-parts` library and adds everything that needs a project (project +//! parts, device functions, function template usage). -use crate::model::{natural_cmp, Project}; +use crate::model::Project; use crate::symbols::{self, Func}; -use serde::{Deserialize, Serialize}; +pub use openecraft_parts::*; use std::collections::BTreeMap; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub enum TopGroup { - #[default] - Electrical, - Fluid, - Mechanics, -} - -impl TopGroup { - pub const ALL: [TopGroup; 3] = [TopGroup::Electrical, TopGroup::Fluid, TopGroup::Mechanics]; - - pub fn title(self) -> &'static str { - match self { - TopGroup::Electrical => "Electrical engineering", - TopGroup::Fluid => "Fluid power", - TopGroup::Mechanics => "Mechanics", - } - } -} - -/// Suggested product groups / subgroups (free text is allowed as well). -pub const PRODUCT_GROUPS: &[(&str, &[&str])] = &[ - ("Relays, contactors", &["Power contactor", "Auxiliary contact block", "Relay", "Timer relay"]), - ("Safety devices", &["Motor protection switch", "Circuit breaker", "Fuse", "Overload relay", "Auxiliary switch"]), - ("Sensors, switches, pushbuttons", &["Pushbutton", "Emergency stop", "Selector switch", "Proximity sensor", "Position switch", "Contact block"]), - ("Signal devices", &["Indicator lamp", "Horn"]), - ("Motors", &["Three-phase motor", "Single-phase motor"]), - ("Power supplies, transformers", &["Power supply", "Control transformer"]), - ("Terminals", &["Feed-through terminal", "PE terminal", "Accessories"]), - ("PLC", &["Digital input module", "Digital output module", "CPU"]), - ("Valves", &["Solenoid valve"]), - ("Passive components", &["Resistor", "Capacitor", "Diode"]), - ("Mounting", &["Mounting rail", "Cable duct", "Enclosure"]), -]; - -/// Kinds of functions in a function template. Placed symbols map onto these kinds. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -pub enum FnKind { - Coil, - MainContacts3, - MainContact, - No, - Nc, - Changeover, - PushbuttonNo, - PushbuttonNc, - SwitchNo, - Sensor, - Breaker1, - Breaker3, - MotorProtection, - Overload, - Fuse, - Motor3, - Motor1, - Signal, - PowerSupply, - Transformer, - Terminal, - PlcInput, - PlcOutput, - Valve, - #[default] - Generic, -} - -impl FnKind { - pub const ALL: [FnKind; 25] = [ - FnKind::Coil, - FnKind::MainContacts3, - FnKind::MainContact, - FnKind::No, - FnKind::Nc, - FnKind::Changeover, - FnKind::PushbuttonNo, - FnKind::PushbuttonNc, - FnKind::SwitchNo, - FnKind::Sensor, - FnKind::Breaker1, - FnKind::Breaker3, - FnKind::MotorProtection, - FnKind::Overload, - FnKind::Fuse, - FnKind::Motor3, - FnKind::Motor1, - FnKind::Signal, - FnKind::PowerSupply, - FnKind::Transformer, - FnKind::Terminal, - FnKind::PlcInput, - FnKind::PlcOutput, - FnKind::Valve, - FnKind::Generic, - ]; - - pub fn title(self) -> &'static str { - match self { - FnKind::Coil => "Coil", - FnKind::MainContacts3 => "Main contacts 3-pole", - FnKind::MainContact => "Main contact 1-pole", - FnKind::No => "NO contact", - FnKind::Nc => "NC contact", - FnKind::Changeover => "Changeover contact", - FnKind::PushbuttonNo => "Pushbutton NO", - FnKind::PushbuttonNc => "Pushbutton NC", - FnKind::SwitchNo => "Switch NO", - FnKind::Sensor => "Sensor", - FnKind::Breaker1 => "Circuit breaker 1-pole", - FnKind::Breaker3 => "Circuit breaker 3-pole", - FnKind::MotorProtection => "Motor protection switch", - FnKind::Overload => "Overload relay", - FnKind::Fuse => "Fuse", - FnKind::Motor3 => "Motor 3-phase", - FnKind::Motor1 => "Motor 1-phase", - FnKind::Signal => "Signal device", - FnKind::PowerSupply => "Power supply", - FnKind::Transformer => "Transformer", - FnKind::Terminal => "Terminal", - FnKind::PlcInput => "PLC input", - FnKind::PlcOutput => "PLC output", - FnKind::Valve => "Valve coil", - FnKind::Generic => "Generic function", - } - } - - /// Function kind represented by a library symbol. - pub fn of_symbol(key: &str) -> Option { - Some(match key { - "coil" | "coil_on" | "coil_off" => FnKind::Coil, - "valve" => FnKind::Valve, - "no" => FnKind::No, - "nc" | "ol_nc" => FnKind::Nc, - "co" => FnKind::Changeover, - "main3" => FnKind::MainContacts3, - "main1" => FnKind::MainContact, - "pb_no" => FnKind::PushbuttonNo, - "pb_nc" | "estop" => FnKind::PushbuttonNc, - "sel" => FnKind::SwitchNo, - "prox" | "limit" => FnKind::Sensor, - "fuse" => FnKind::Fuse, - "cb1" => FnKind::Breaker1, - "cb3" => FnKind::Breaker3, - "mps3" => FnKind::MotorProtection, - "ol3" => FnKind::Overload, - "motor3" => FnKind::Motor3, - "motor1" => FnKind::Motor1, - "lamp" | "horn" => FnKind::Signal, - "psu" => FnKind::PowerSupply, - "trafo" => FnKind::Transformer, - "term" | "term_pe" => FnKind::Terminal, - "plc_in" => FnKind::PlcInput, - "plc_out" => FnKind::PlcOutput, - "res" | "cap" | "diode" => FnKind::Generic, - _ => return None, - }) - } - - fn short(self) -> &'static str { - match self { - FnKind::Coil => "Coil", - FnKind::MainContacts3 => "Main3", - FnKind::MainContact => "Main1", - FnKind::No => "NO", - FnKind::Nc => "NC", - FnKind::Changeover => "CO", - FnKind::PushbuttonNo => "PBNO", - FnKind::PushbuttonNc => "PBNC", - FnKind::SwitchNo => "SWNO", - FnKind::Sensor => "Sensor", - FnKind::Breaker1 => "CB1", - FnKind::Breaker3 => "CB3", - FnKind::MotorProtection => "MPS", - FnKind::Overload => "OL", - FnKind::Fuse => "Fuse", - FnKind::Motor3 => "M3", - FnKind::Motor1 => "M1", - FnKind::Signal => "Signal", - FnKind::PowerSupply => "PSU", - FnKind::Transformer => "Trafo", - FnKind::Terminal => "Terminal", - FnKind::PlcInput => "DI", - FnKind::PlcOutput => "DO", - FnKind::Valve => "Valve", - FnKind::Generic => "Generic", - } - } - - fn from_short(s: &str) -> Option { - FnKind::ALL.into_iter().find(|k| k.short().eq_ignore_ascii_case(s.trim())) - } -} - -/// One function of a function template. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct FunctionTemplate { - pub kind: FnKind, - /// Connection point designations in symbol order, separated by blanks ("13 14"). - pub pins: String, - pub description: String, -} - -impl FunctionTemplate { - pub fn new(kind: FnKind, pins: &str) -> FunctionTemplate { - FunctionTemplate { kind, pins: pins.into(), description: String::new() } - } - - pub fn pin_list(&self) -> Vec { - self.pins.split_whitespace().map(String::from).collect() - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct Part { - // General - /// Unique key, conventionally `MANUFACTURER.TYPE`. - pub number: String, - pub type_number: String, - pub order_number: String, - pub manufacturer: String, - pub supplier: String, - pub description: String, - pub note: String, - pub top_group: TopGroup, - pub group: String, - pub subgroup: String, - /// Identifying letter of devices using this part (device selection). - pub identifier: String, - // Commercial - pub price: f32, - pub currency: String, - /// The price refers to this many units. - pub price_unit: u32, - pub pack_quantity: u32, - pub quantity_unit: String, - // Technical - pub voltage: String, - pub current: String, - pub power: String, - pub tech_data: String, - pub certificates: String, - pub datasheet: String, - // Mounting - pub width: f32, - pub height: f32, - pub depth: f32, - pub weight: f32, - pub mounting: String, - // Logic - pub functions: Vec, - /// Part numbers of accessories. - pub accessories: Vec, -} - -impl Default for Part { - fn default() -> Self { - Part { - number: String::new(), - type_number: String::new(), - order_number: String::new(), - manufacturer: String::new(), - supplier: String::new(), - description: String::new(), - note: String::new(), - top_group: TopGroup::Electrical, - group: String::new(), - subgroup: String::new(), - identifier: String::new(), - price: 0.0, - currency: "EUR".into(), - price_unit: 1, - pack_quantity: 1, - quantity_unit: "pcs".into(), - voltage: String::new(), - current: String::new(), - power: String::new(), - tech_data: String::new(), - certificates: String::new(), - datasheet: String::new(), - width: 0.0, - height: 0.0, - depth: 0.0, - weight: 0.0, - mounting: String::new(), - functions: Vec::new(), - accessories: Vec::new(), - } - } -} - -impl Part { - /// Price of `qty` units, respecting the price unit. - pub fn total_price(&self, qty: f32) -> f32 { - self.price / self.price_unit.max(1) as f32 * qty - } - - pub fn matches_text(&self, f: &str) -> bool { - if f.is_empty() { - return true; - } - let f = f.to_lowercase(); - [&self.number, &self.type_number, &self.order_number, &self.manufacturer, &self.description, &self.group, &self.subgroup] - .iter() - .any(|s| s.to_lowercase().contains(&f)) - } - - /// Short summary of the function template, e.g. "Coil, Main3, NO". - pub fn template_summary(&self) -> String { - let mut counts: BTreeMap = BTreeMap::new(); - for f in &self.functions { - *counts.entry(f.kind).or_default() += 1; - } - counts - .iter() - .map(|(k, n)| if *n > 1 { format!("{n}× {}", k.title()) } else { k.title().to_string() }) - .collect::>() - .join(", ") - } -} - -/// Reference from a device to a part. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PartRef { - pub number: String, - pub count: u32, -} - -impl Default for PartRef { - fn default() -> Self { - PartRef { number: String::new(), count: 1 } - } -} - -/// The global parts database. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PartsDb { - pub parts: Vec, -} - -impl Default for PartsDb { - fn default() -> Self { - PartsDb { parts: default_catalog() } - } -} - -impl PartsDb { - pub fn get(&self, number: &str) -> Option<&Part> { - self.parts.iter().find(|p| p.number == number) - } - - /// Inserts or replaces a part (by part number). - pub fn upsert(&mut self, part: Part) { - upsert(&mut self.parts, part); - } - - pub fn sort(&mut self) { - self.parts.sort_by(|a, b| natural_cmp(&a.number, &b.number)); - } -} - -pub fn upsert(list: &mut Vec, part: Part) { - match list.iter_mut().find(|p| p.number == part.number) { - Some(existing) => *existing = part, - None => list.push(part), - } -} - -/// A part number that does not exist yet, based on `base`. -pub fn unique_number(list: &[Part], base: &str) -> String { - if !list.iter().any(|p| p.number == base) { - return base.to_string(); - } - (1..) - .map(|i| format!("{base}_{i}")) - .find(|n| !list.iter().any(|p| &p.number == n)) - .unwrap() +/// Function kind represented by a library symbol. +pub fn kind_of_symbol(key: &str) -> Option { + Some(match key { + "coil" | "coil_on" | "coil_off" => FnKind::Coil, + "valve" => FnKind::Valve, + "no" => FnKind::No, + "nc" | "ol_nc" => FnKind::Nc, + "co" => FnKind::Changeover, + "main3" => FnKind::MainContacts3, + "main1" => FnKind::MainContact, + "pb_no" => FnKind::PushbuttonNo, + "pb_nc" | "estop" => FnKind::PushbuttonNc, + "sel" => FnKind::SwitchNo, + "prox" | "limit" => FnKind::Sensor, + "fuse" => FnKind::Fuse, + "cb1" => FnKind::Breaker1, + "cb3" => FnKind::Breaker3, + "mps3" => FnKind::MotorProtection, + "ol3" => FnKind::Overload, + "motor3" => FnKind::Motor3, + "motor1" => FnKind::Motor1, + "lamp" | "horn" => FnKind::Signal, + "psu" => FnKind::PowerSupply, + "trafo" => FnKind::Transformer, + "term" | "term_pe" => FnKind::Terminal, + "plc_in" => FnKind::PlcInput, + "plc_out" => FnKind::PlcOutput, + "res" | "cap" | "diode" => FnKind::Generic, + _ => return None, + }) } // ---------------------------------------------------------------------- project @@ -467,7 +118,7 @@ pub fn placed_functions(prj: &Project, tag: &str) -> Vec<(FnKind, Vec, u let mut v = Vec::new(); for pg in &prj.pages { for s in pg.symbols.iter().filter(|s| s.tag == tag) { - if let Some(k) = FnKind::of_symbol(&s.sym) { + if let Some(k) = kind_of_symbol(&s.sym) { v.push((k, s.pins.clone(), s.id)); } } @@ -541,7 +192,7 @@ pub fn apply_designations(prj: &mut Project, db: Option<&PartsDb>, tag: &str) -> let mut changed = 0; for (pi, si) in placed { let s = &mut prj.pages[pi].symbols[si]; - let Some(kind) = FnKind::of_symbol(&s.sym) else { continue }; + let Some(kind) = kind_of_symbol(&s.sym) else { continue }; let n_pins = symbols::get(&s.sym).map(|d| d.pins.len()).unwrap_or(0); if let Some(i) = avail.iter().position(|f| f.kind == kind && f.pin_list().len() == n_pins) { let pins = avail.remove(i).pin_list(); @@ -573,366 +224,7 @@ pub fn main_kind(prj: &Project, tag: &str) -> Option { .flat_map(|pg| pg.symbols.iter()) .filter(|s| s.tag == tag) .find(|s| symbols::get(&s.sym).map(|d| matches!(d.func, Func::Main { .. })).unwrap_or(false)) - .and_then(|s| FnKind::of_symbol(&s.sym)) -} - -// ---------------------------------------------------------------------- CSV - -const CSV_FIELDS: [&str; 29] = [ - "Part number", - "Type number", - "Order number", - "Manufacturer", - "Supplier", - "Description", - "Note", - "Product top group", - "Product group", - "Product subgroup", - "Identifier", - "Price", - "Currency", - "Price unit", - "Pack quantity", - "Quantity unit", - "Voltage", - "Current", - "Power", - "Technical data", - "Certificates", - "Datasheet", - "Width", - "Height", - "Depth", - "Weight", - "Mounting", - "Functions", - "Accessories", -]; - -fn csv_escape(s: &str) -> String { - if s.contains([';', '"', '\n', '\r']) { - format!("\"{}\"", s.replace('"', "\"\"")) - } else { - s.to_string() - } -} - -pub fn to_csv(parts: &[Part]) -> String { - let mut out = CSV_FIELDS.join(";"); - out.push('\n'); - for p in parts { - let functions = p - .functions - .iter() - .map(|f| format!("{}:{}", f.kind.short(), f.pins)) - .collect::>() - .join("|"); - let top = match p.top_group { - TopGroup::Electrical => "Electrical", - TopGroup::Fluid => "Fluid", - TopGroup::Mechanics => "Mechanics", - }; - let row = [ - p.number.clone(), - p.type_number.clone(), - p.order_number.clone(), - p.manufacturer.clone(), - p.supplier.clone(), - p.description.clone(), - p.note.clone(), - top.to_string(), - p.group.clone(), - p.subgroup.clone(), - p.identifier.clone(), - format!("{:.2}", p.price), - p.currency.clone(), - p.price_unit.to_string(), - p.pack_quantity.to_string(), - p.quantity_unit.clone(), - p.voltage.clone(), - p.current.clone(), - p.power.clone(), - p.tech_data.clone(), - p.certificates.clone(), - p.datasheet.clone(), - p.width.to_string(), - p.height.to_string(), - p.depth.to_string(), - p.weight.to_string(), - p.mounting.clone(), - functions, - p.accessories.join(","), - ]; - out.push_str(&row.iter().map(|c| csv_escape(c)).collect::>().join(";")); - out.push('\n'); - } - out -} - -/// Splits CSV text (separator `;` or `,`) into records, honouring quotes. -fn parse_csv(text: &str) -> Vec> { - let sep = if text.lines().next().map(|l| l.contains(';')).unwrap_or(true) { ';' } else { ',' }; - let mut rows = Vec::new(); - let mut row = Vec::new(); - let mut cell = String::new(); - let mut quoted = false; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { - match c { - '"' if quoted && chars.peek() == Some(&'"') => { - cell.push('"'); - chars.next(); - } - '"' => quoted = !quoted, - c if c == sep && !quoted => row.push(std::mem::take(&mut cell)), - '\r' if !quoted => {} - '\n' if !quoted => { - row.push(std::mem::take(&mut cell)); - if row.iter().any(|c| !c.is_empty()) { - rows.push(std::mem::take(&mut row)); - } else { - row.clear(); - } - } - c => cell.push(c), - } - } - if !cell.is_empty() || !row.is_empty() { - row.push(cell); - rows.push(row); - } - rows -} - -/// Reads parts from CSV. Columns are matched by header name; unknown columns are ignored. -pub fn from_csv(text: &str) -> Result, String> { - let rows = parse_csv(text.trim_start_matches('\u{feff}')); - let Some((header, data)) = rows.split_first() else { return Err("empty file".into()) }; - let col = |name: &str| header.iter().position(|h| h.trim().eq_ignore_ascii_case(name)); - if col("Part number").is_none() { - return Err("column 'Part number' missing".into()); - } - let idx: Vec> = CSV_FIELDS.iter().map(|f| col(f)).collect(); - let mut parts = Vec::new(); - for r in data { - let get = |i: usize| idx[i].and_then(|c| r.get(c)).map(|s| s.trim().to_string()).unwrap_or_default(); - let num = |i: usize| get(i).replace(',', ".").parse::().unwrap_or(0.0); - let int = |i: usize, d: u32| get(i).parse::().unwrap_or(d); - let number = get(0); - if number.is_empty() { - continue; - } - let top_group = match get(7).to_lowercase().as_str() { - s if s.starts_with("fluid") => TopGroup::Fluid, - s if s.starts_with("mech") => TopGroup::Mechanics, - _ => TopGroup::Electrical, - }; - let functions = get(27) - .split('|') - .filter(|s| !s.trim().is_empty()) - .filter_map(|s| { - let (k, pins) = s.split_once(':').unwrap_or((s, "")); - FnKind::from_short(k).map(|k| FunctionTemplate::new(k, pins.trim())) - }) - .collect(); - parts.push(Part { - number, - type_number: get(1), - order_number: get(2), - manufacturer: get(3), - supplier: get(4), - description: get(5), - note: get(6), - top_group, - group: get(8), - subgroup: get(9), - identifier: get(10), - price: num(11), - currency: if get(12).is_empty() { "EUR".into() } else { get(12) }, - price_unit: int(13, 1).max(1), - pack_quantity: int(14, 1).max(1), - quantity_unit: if get(15).is_empty() { "pcs".into() } else { get(15) }, - voltage: get(16), - current: get(17), - power: get(18), - tech_data: get(19), - certificates: get(20), - datasheet: get(21), - width: num(22), - height: num(23), - depth: num(24), - weight: num(25), - mounting: get(26), - functions, - accessories: get(28).split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(), - }); - } - Ok(parts) -} - -/// Imports a parts file (JSON database / part list or CSV). Returns the parts. -pub fn import(text: &str) -> Result, String> { - let t = text.trim_start_matches('\u{feff}').trim_start(); - if t.starts_with('{') { - serde_json::from_str::(t).map(|d| d.parts).map_err(|e| e.to_string()) - } else if t.starts_with('[') { - serde_json::from_str::>(t).map_err(|e| e.to_string()) - } else { - from_csv(t) - } -} - -// ---------------------------------------------------------------------- catalog - -struct C { - parts: Vec, -} - -#[allow(clippy::too_many_arguments)] -impl C { - fn add( - &mut self, - number: &str, - desc: &str, - group: &str, - subgroup: &str, - ident: &str, - price: f32, - dims: (f32, f32, f32, f32), - functions: &[(FnKind, &str)], - ) -> &mut Part { - let (top, rest) = number.split_once('.').unwrap_or(("GEN", number)); - let manufacturer = if top == "GEN" { "Generic" } else { top }; - self.parts.push(Part { - number: number.into(), - type_number: rest.into(), - order_number: rest.into(), - manufacturer: manufacturer.into(), - supplier: "Generic distribution".into(), - description: desc.into(), - top_group: if group == "Mounting" { TopGroup::Mechanics } else if group == "Valves" { TopGroup::Fluid } else { TopGroup::Electrical }, - group: group.into(), - subgroup: subgroup.into(), - identifier: ident.into(), - price, - width: dims.0, - height: dims.1, - depth: dims.2, - weight: dims.3, - mounting: if dims.0 > 0.0 { "Mounting rail 35 mm".into() } else { String::new() }, - functions: functions.iter().map(|(k, p)| FunctionTemplate::new(*k, p)).collect(), - ..Default::default() - }); - self.parts.last_mut().unwrap() - } -} - -/// Generic example catalog with function templates. -pub fn default_catalog() -> Vec { - use FnKind::*; - let mut c = C { parts: Vec::new() }; - let rc = "Relays, contactors"; - let sd = "Safety devices"; - let sw = "Sensors, switches, pushbuttons"; - let main3 = "1 3 5 2 4 6"; - - let p = c.add("GEN.CT-9A-24DC", "Contactor 3P 9 A, coil 24 V DC, 1 NO aux", rc, "Power contactor", "K", 38.5, (45.0, 74.0, 73.0, 0.32), &[(Coil, "A1 A2"), (MainContacts3, main3), (No, "13 14")]); - p.voltage = "24 V DC".into(); - p.current = "9 A (AC-3)".into(); - p.power = "4 kW / 400 V".into(); - p.accessories = vec!["GEN.AUX-2NO2NC".into()]; - let p = c.add("GEN.CT-18A-24DC", "Contactor 3P 18 A, coil 24 V DC, 1 NO + 1 NC aux", rc, "Power contactor", "K", 52.0, (45.0, 84.0, 87.0, 0.45), &[(Coil, "A1 A2"), (MainContacts3, main3), (No, "13 14"), (Nc, "21 22")]); - p.voltage = "24 V DC".into(); - p.current = "18 A (AC-3)".into(); - p.power = "7.5 kW / 400 V".into(); - p.accessories = vec!["GEN.AUX-2NO2NC".into()]; - c.add("GEN.AUX-2NO2NC", "Auxiliary contact block 2 NO + 2 NC, front mounting", rc, "Auxiliary contact block", "K", 14.6, (45.0, 40.0, 40.0, 0.05), &[(No, "53 54"), (Nc, "61 62"), (Nc, "71 72"), (No, "83 84")]); - c.add("GEN.AUX-1NO1NC", "Auxiliary contact block 1 NO + 1 NC", rc, "Auxiliary contact block", "K", 9.8, (45.0, 40.0, 40.0, 0.03), &[(No, "53 54"), (Nc, "61 62")]); - let p = c.add("GEN.RLY-24DC-2CO", "Interface relay 24 V DC, 2 CO, with socket", rc, "Relay", "K", 12.4, (15.5, 78.0, 70.0, 0.04), &[(Coil, "A1 A2"), (Changeover, "11 12 14"), (Changeover, "21 22 24")]); - p.voltage = "24 V DC".into(); - p.current = "8 A".into(); - let p = c.add("GEN.TMR-24DC-OND", "Timer relay on-delay 24 V DC, 0.05 s - 100 h, 1 CO", rc, "Timer relay", "K", 34.9, (17.5, 90.0, 64.0, 0.07), &[(Coil, "A1 A2"), (Changeover, "15 16 18")]); - p.voltage = "24 V DC".into(); - - let p = c.add("GEN.MPS-2.5-4A", "Motor protection switch 2.5 - 4 A", sd, "Motor protection switch", "Q", 61.0, (45.0, 97.0, 97.0, 0.3), &[(MotorProtection, main3)]); - p.current = "2.5 - 4 A".into(); - p.accessories = vec!["GEN.MPS-AUX-1NO1NC".into()]; - let p = c.add("GEN.MPS-4-6.3A", "Motor protection switch 4 - 6.3 A", sd, "Motor protection switch", "Q", 63.0, (45.0, 97.0, 97.0, 0.3), &[(MotorProtection, main3)]); - p.current = "4 - 6.3 A".into(); - p.accessories = vec!["GEN.MPS-AUX-1NO1NC".into()]; - c.add("GEN.MPS-AUX-1NO1NC", "Auxiliary switch for motor protection switch, 1 NO + 1 NC", sd, "Auxiliary switch", "Q", 12.9, (9.0, 90.0, 60.0, 0.02), &[(No, "13 14"), (Nc, "21 22")]); - let p = c.add("GEN.MCB-1P-C6", "Miniature circuit breaker 1P C6", sd, "Circuit breaker", "F", 8.7, (18.0, 90.0, 70.0, 0.12), &[(Breaker1, "1 2")]); - p.current = "6 A".into(); - let p = c.add("GEN.MCB-1P-B10", "Miniature circuit breaker 1P B10", sd, "Circuit breaker", "F", 8.7, (18.0, 90.0, 70.0, 0.12), &[(Breaker1, "1 2")]); - p.current = "10 A".into(); - let p = c.add("GEN.MCB-3P-C16", "Miniature circuit breaker 3P C16", sd, "Circuit breaker", "Q", 27.3, (54.0, 90.0, 70.0, 0.36), &[(Breaker3, main3)]); - p.current = "16 A".into(); - let p = c.add("GEN.FUSE-5X20-2A", "Fuse holder 5x20 mm with fuse 2 A", sd, "Fuse", "F", 4.2, (8.0, 60.0, 50.0, 0.02), &[(Fuse, "1 2")]); - p.current = "2 A".into(); - let p = c.add("GEN.OL-2.8-4A", "Thermal overload relay 2.8 - 4 A, 1 NO + 1 NC", sd, "Overload relay", "F", 44.0, (45.0, 70.0, 80.0, 0.15), &[(Overload, main3), (Nc, "95 96"), (No, "97 98")]); - p.current = "2.8 - 4 A".into(); - - c.add("GEN.PB-GN-1NO", "Pushbutton green, 1 NO", sw, "Pushbutton", "S", 11.2, (30.0, 30.0, 45.0, 0.03), &[(PushbuttonNo, "13 14")]).accessories = vec!["GEN.CB-1NO".into(), "GEN.CB-1NC".into()]; - c.add("GEN.PB-RD-1NC", "Pushbutton red, 1 NC", sw, "Pushbutton", "S", 11.2, (30.0, 30.0, 45.0, 0.03), &[(PushbuttonNc, "11 12")]).accessories = vec!["GEN.CB-1NO".into(), "GEN.CB-1NC".into()]; - c.add("GEN.ESTOP-1NC", "Emergency stop mushroom 40 mm, twist release, 1 NC", sw, "Emergency stop", "S", 24.6, (40.0, 40.0, 60.0, 0.06), &[(PushbuttonNc, "11 12")]).accessories = vec!["GEN.CB-1NC".into()]; - c.add("GEN.SEL-2POS-1NO", "Selector switch 2 positions, 1 NO", sw, "Selector switch", "S", 15.9, (30.0, 30.0, 45.0, 0.03), &[(SwitchNo, "13 14")]); - c.add("GEN.CB-1NO", "Contact block 1 NO for front mounting", sw, "Contact block", "S", 4.9, (10.0, 30.0, 40.0, 0.01), &[(No, "13 14")]); - c.add("GEN.CB-1NC", "Contact block 1 NC for front mounting", sw, "Contact block", "S", 4.9, (10.0, 30.0, 40.0, 0.01), &[(Nc, "21 22")]); - let p = c.add("GEN.PROX-M12-PNP", "Inductive proximity sensor M12, PNP NO, Sn 4 mm", sw, "Proximity sensor", "B", 29.0, (12.0, 12.0, 60.0, 0.05), &[(Sensor, "BN BK")]); - p.voltage = "10 - 30 V DC".into(); - c.add("GEN.LIMIT-1NO1NC", "Position switch roller plunger, 1 NO + 1 NC", sw, "Position switch", "B", 32.0, (31.0, 60.0, 33.0, 0.1), &[(Sensor, "13 14"), (Nc, "21 22")]); - - let p = c.add("GEN.LMP-GN-24", "Indicator lamp green, LED 24 V", "Signal devices", "Indicator lamp", "P", 9.1, (30.0, 30.0, 45.0, 0.02), &[(Signal, "X1 X2")]); - p.voltage = "24 V AC/DC".into(); - let p = c.add("GEN.LMP-RD-24", "Indicator lamp red, LED 24 V", "Signal devices", "Indicator lamp", "P", 9.1, (30.0, 30.0, 45.0, 0.02), &[(Signal, "X1 X2")]); - p.voltage = "24 V AC/DC".into(); - c.add("GEN.HORN-24", "Panel buzzer 24 V, 85 dB", "Signal devices", "Horn", "P", 18.0, (30.0, 30.0, 50.0, 0.03), &[(Signal, "1 2")]); - - let p = c.add("GEN.MOT-0.75KW", "Three-phase motor 0.75 kW 400 V, 1400 rpm", "Motors", "Three-phase motor", "M", 180.0, (0.0, 0.0, 0.0, 9.5), &[(Motor3, "U1 V1 W1 PE")]); - p.voltage = "400 V".into(); - p.current = "1.9 A".into(); - p.power = "0.75 kW".into(); - let p = c.add("GEN.MOT-1PH-0.25KW", "Single-phase motor 0.25 kW 230 V", "Motors", "Single-phase motor", "M", 140.0, (0.0, 0.0, 0.0, 5.0), &[(Motor1, "L N PE")]); - p.power = "0.25 kW".into(); - - 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")]); - - 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()]; - c.add("GEN.TB-PE-2.5", "Protective earth terminal 2.5 mm², green-yellow", "Terminals", "PE terminal", "X", 1.8, (5.2, 48.0, 36.0, 0.01), &[(Terminal, "")]); - c.add("GEN.TB-END", "End plate for terminal 2.5 mm²", "Terminals", "Accessories", "X", 0.3, (1.5, 48.0, 36.0, 0.002), &[]); - - let di: Vec<(FnKind, String)> = (0..16).map(|i| (PlcInput, format!("I{}.{}", i / 8, i % 8))).collect(); - let di: Vec<(FnKind, &str)> = di.iter().map(|(k, s)| (*k, s.as_str())).collect(); - c.add("GEN.PLC-DI16", "PLC digital input module 16 x 24 V DC", "PLC", "Digital input module", "A", 145.0, (25.0, 100.0, 75.0, 0.15), &di); - let dq: Vec<(FnKind, String)> = (0..16).map(|i| (PlcOutput, format!("Q{}.{}", i / 8, i % 8))).collect(); - let dq: Vec<(FnKind, &str)> = dq.iter().map(|(k, s)| (*k, s.as_str())).collect(); - c.add("GEN.PLC-DO16", "PLC digital output module 16 x 24 V DC 0.5 A", "PLC", "Digital output module", "A", 165.0, (25.0, 100.0, 75.0, 0.15), &dq); - - let p = c.add("GEN.SV-24DC", "Solenoid valve coil 24 V DC, 4.8 W", "Valves", "Solenoid valve", "Y", 22.5, (0.0, 0.0, 0.0, 0.1), &[(Valve, "A1 A2")]); - p.voltage = "24 V DC".into(); - p.power = "4.8 W".into(); - - c.add("GEN.RES-1K", "Resistor 1 kΩ 0.6 W", "Passive components", "Resistor", "R", 0.1, (0.0, 0.0, 0.0, 0.0), &[(Generic, "1 2")]); - c.add("GEN.CAP-100N", "Capacitor 100 nF 63 V", "Passive components", "Capacitor", "C", 0.15, (0.0, 0.0, 0.0, 0.0), &[(Generic, "1 2")]); - c.add("GEN.DIODE-1N4007", "Rectifier diode 1 A 1000 V", "Passive components", "Diode", "V", 0.08, (0.0, 0.0, 0.0, 0.0), &[(Generic, "A K")]); - - let p = c.add("GEN.RAIL-TS35-1M", "Mounting rail TS 35 x 7.5, perforated, 1 m", "Mounting", "Mounting rail", "", 6.5, (1000.0, 35.0, 7.5, 0.35), &[]); - p.quantity_unit = "m".into(); - p.mounting.clear(); - let p = c.add("GEN.DUCT-40X60", "Cable duct 40 x 60 mm, 2 m", "Mounting", "Cable duct", "", 11.0, (2000.0, 40.0, 60.0, 0.9), &[]); - p.pack_quantity = 10; - 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(); - - let mut parts = c.parts; - parts.sort_by(|a, b| natural_cmp(&a.number, &b.number)); - parts + .and_then(|s| kind_of_symbol(&s.sym)) } #[cfg(test)] diff --git a/src/parts/tests.rs b/src/parts/tests.rs index 40cbb93e..00943962 100644 --- a/src/parts/tests.rs +++ b/src/parts/tests.rs @@ -1,30 +1,5 @@ use super::*; -#[test] -fn csv_roundtrip() { - let parts = default_catalog(); - let csv = to_csv(&parts); - let back = from_csv(&csv).unwrap(); - assert_eq!(parts.len(), back.len()); - for (a, b) in parts.iter().zip(&back) { - assert_eq!(a.number, b.number); - assert_eq!(a.functions, b.functions); - assert_eq!(a.accessories, b.accessories); - assert_eq!(a.description, b.description); - } -} - -#[test] -fn catalog_numbers_unique_and_accessories_exist() { - let parts = default_catalog(); - for (i, p) in parts.iter().enumerate() { - assert!(parts[i + 1..].iter().all(|q| q.number != p.number), "duplicate {}", p.number); - for a in &p.accessories { - assert!(parts.iter().any(|q| &q.number == a), "{} accessory {a} missing", p.number); - } - } -} - #[test] fn legacy_single_part_is_migrated() { let json = r#"{"devices": {"-K1": {"part": "CT-9A-24DC", "description": ""}}, @@ -61,10 +36,3 @@ fn designations_from_template_and_device_selection() { assert!(fits_device(db.get("GEN.CT-9A-24DC").unwrap(), &placed, main)); assert!(!fits_device(db.get("GEN.MCB-1P-C6").unwrap(), &placed, main)); } - -#[test] -fn json_import() { - let db = PartsDb::default(); - let json = serde_json::to_string(&db).unwrap(); - assert_eq!(import(&json).unwrap().len(), db.parts.len()); -} diff --git a/src/parts_server.rs b/src/parts_server.rs new file mode 100644 index 00000000..13f82098 --- /dev/null +++ b/src/parts_server.rs @@ -0,0 +1,157 @@ +//! Client for the global parts server (`openecraft-server`). Requests run in the +//! background (thread on desktop, fetch in the browser); results are collected with +//! [`ServerClient::poll`]. + +use crate::parts::{Part, PartsDb}; +use openecraft_parts::api::{self, ApiError, ImportResult, PartList, ServerInfo, API_PREFIX, DEFAULT_PORT}; +use serde::de::DeserializeOwned; +use std::sync::{Arc, Mutex}; + +enum Reply { + Info(Result), + Parts(Result), + Uploaded(Result), +} + +pub struct ServerClient { + pub url: String, + /// Access token for uploads (kept in memory only). + pub token: String, + pub info: Option, + pub status: String, + pending: usize, + inbox: Arc>>, +} + +impl Default for ServerClient { + fn default() -> Self { + ServerClient { + url: format!("http://127.0.0.1:{DEFAULT_PORT}"), + token: String::new(), + info: None, + status: String::new(), + pending: 0, + inbox: Arc::default(), + } + } +} + +/// Turns an HTTP result into the expected JSON type or a readable error. +pub fn decode(result: ehttp::Result) -> Result { + match result { + Err(e) => Err(format!("connection failed: {e}")), + Ok(resp) if resp.ok => serde_json::from_slice(&resp.bytes).map_err(|e| format!("unexpected answer: {e}")), + Ok(resp) => Err(serde_json::from_slice::(&resp.bytes) + .map(|e| e.error) + .unwrap_or_else(|_| format!("{} {}", resp.status, resp.status_text))), + } +} + +/// Adds / replaces downloaded parts in the local database. Returns (added, updated). +pub fn merge(db: &mut PartsDb, parts: Vec) -> (usize, usize) { + let (mut added, mut updated) = (0, 0); + for part in parts { + match db.parts.iter_mut().find(|p| p.number == part.number) { + Some(existing) if *existing != part => { + *existing = part; + updated += 1; + } + Some(_) => {} + None => { + db.parts.push(part); + added += 1; + } + } + } + db.sort(); + (added, updated) +} + +impl ServerClient { + pub fn busy(&self) -> bool { + self.pending > 0 + } + + fn send( + &mut self, + ctx: &egui::Context, + request: ehttp::Request, + wrap: impl 'static + Send + FnOnce(Result) -> Reply, + ) { + self.pending += 1; + let inbox = self.inbox.clone(); + let ctx = ctx.clone(); + ehttp::fetch(request, move |result| { + if let Ok(mut inbox) = inbox.lock() { + inbox.push(wrap(decode(result))); + } + ctx.request_repaint(); + }); + } + + /// GET /api/v1/info + pub fn check(&mut self, ctx: &egui::Context) { + self.status = "Connecting…".into(); + let req = ehttp::Request::get(api::url(&self.url, &format!("{API_PREFIX}/info"))); + self.send(ctx, req, Reply::Info); + } + + /// GET /api/v1/parts (all parts) + pub fn download(&mut self, ctx: &egui::Context) { + self.status = "Downloading parts…".into(); + let req = ehttp::Request::get(api::url(&self.url, &format!("{API_PREFIX}/parts"))); + self.send(ctx, req, Reply::Parts); + } + + /// POST /api/v1/import with the parts as JSON (needs the access token). + pub fn upload(&mut self, ctx: &egui::Context, parts: &[Part]) { + let body = serde_json::to_vec(parts).unwrap_or_default(); + let mut req = ehttp::Request::post(api::url(&self.url, &format!("{API_PREFIX}/import")), body); + req.headers.insert("Content-Type", "application/json"); + if !self.token.trim().is_empty() { + req.headers.insert("Authorization", format!("Bearer {}", self.token.trim())); + } + self.status = format!("Uploading {} parts…", parts.len()); + self.send(ctx, req, Reply::Uploaded); + } + + /// Applies finished requests. Returns a message for the status bar. + pub fn poll(&mut self, db: &mut PartsDb) -> Option { + let replies: Vec = self.inbox.lock().map(|mut i| std::mem::take(&mut *i)).unwrap_or_default(); + let mut message = None; + for reply in replies { + self.pending = self.pending.saturating_sub(1); + let text = match reply { + Reply::Info(Ok(info)) => { + let text = format!( + "Connected: {} {} – {} parts, revision {}, {}", + info.name, + info.version, + info.parts, + info.revision, + if info.writable { "uploads with token" } else { "read-only" } + ); + self.info = Some(info); + text + } + Reply::Parts(Ok(list)) => { + let n = list.parts.len(); + let (added, updated) = merge(db, list.parts); + format!("Downloaded {n} parts (revision {}): {added} new, {updated} updated", list.revision) + } + Reply::Uploaded(Ok(r)) => format!("Uploaded {} parts, server revision {}", r.imported, r.revision), + Reply::Info(Err(e)) => { + self.info = None; + format!("Parts server: {e}") + } + Reply::Parts(Err(e)) | Reply::Uploaded(Err(e)) => format!("Parts server: {e}"), + }; + self.status = text.clone(); + message = Some(text); + } + message + } +} + +#[cfg(test)] +mod tests; diff --git a/src/parts_server/tests.rs b/src/parts_server/tests.rs new file mode 100644 index 00000000..c3107879 --- /dev/null +++ b/src/parts_server/tests.rs @@ -0,0 +1,41 @@ +use super::*; + +fn response(status: u16, body: &str) -> ehttp::Result { + Ok(ehttp::Response { + url: "http://test".into(), + ok: (200..300).contains(&status), + status, + status_text: "Status".into(), + headers: ehttp::Headers::default(), + bytes: body.as_bytes().to_vec(), + }) +} + +#[test] +fn decode_success_and_errors() { + let info: ServerInfo = decode(response(200, r#"{"name": "srv", "parts": 3, "writable": true}"#)).unwrap(); + assert_eq!((info.name.as_str(), info.parts, info.writable), ("srv", 3, true)); + // Server error messages are passed through. + let err = decode::(response(401, r#"{"error": "missing or wrong access token"}"#)).unwrap_err(); + assert_eq!(err, "missing or wrong access token"); + // Non-JSON errors fall back to the HTTP status. + let err = decode::(response(502, "Bad gateway")).unwrap_err(); + assert!(err.starts_with("502")); + let err = decode::(Err("refused".into())).unwrap_err(); + assert!(err.contains("refused")); + let err = decode::(response(200, "")).unwrap_err(); + assert!(err.starts_with("unexpected answer")); +} + +#[test] +fn merge_adds_and_updates() { + let mut db = PartsDb { parts: vec![Part { number: "A".into(), description: "old".into(), ..Default::default() }] }; + let incoming = vec![ + Part { number: "A".into(), description: "new".into(), ..Default::default() }, + Part { number: "B".into(), ..Default::default() }, + ]; + assert_eq!(merge(&mut db, incoming.clone()), (1, 1)); + assert_eq!(db.get("A").unwrap().description, "new"); + // Same data again: nothing changes. + assert_eq!(merge(&mut db, incoming), (0, 0)); +} diff --git a/src/parts_ui.rs b/src/parts_ui.rs index c9ec5135..08f297b4 100644 --- a/src/parts_ui.rs +++ b/src/parts_ui.rs @@ -1,7 +1,11 @@ //! Parts management window and part selection dialog. use crate::model::{natural_cmp, Project}; -use crate::parts::{self, FnKind, FunctionTemplate, Part, PartRef, PartsDb, TopGroup, PRODUCT_GROUPS}; +use crate::editor::{EguiDraw, Palette}; +use crate::parts::{self, FnKind, FunctionTemplate, Model2d, Part, PartRef, PartsDb, TopGroup, PRODUCT_GROUPS}; +use crate::render::{Draw, Ink}; +use crate::io::{Loaded, Purpose}; +use crate::parts_server::ServerClient; use egui::{vec2, Color32, RichText}; use std::collections::BTreeMap; @@ -19,11 +23,14 @@ enum Tab { Mounting, Functions, Accessories, + Graphics, } /// Requests the application has to carry out (file dialogs, messages). pub enum PartsAction { Import, + /// Pick a 2D / 3D model file for the selected part. + ImportModel(Purpose), Export { name: String, filter: (&'static str, &'static str), content: String }, Message(String), } @@ -42,6 +49,12 @@ pub struct PartsUi { sel_filter: String, sel_matching: bool, sel_part: Option, + /// Connection to the global parts server. + pub server: ServerClient, + show_server: bool, + /// Part (source, number) that receives the next imported model. + model_target: Option<(Source, String)>, + model_scale: f32, } impl Default for PartsUi { @@ -56,6 +69,10 @@ impl Default for PartsUi { sel_filter: String::new(), sel_matching: true, sel_part: None, + server: ServerClient::default(), + show_server: false, + model_target: None, + model_scale: 25.4, } } } @@ -123,7 +140,16 @@ fn num_row(ui: &mut egui::Ui, label: &str, value: &mut f32, suffix: &str) { } /// Tabbed editor for one part. -fn part_editor(ui: &mut egui::Ui, part: &mut Part, tab: &mut Tab, all_numbers: &[String], duplicate: bool) { +/// Tabbed editor for one part. Returns a requested model import. +fn part_editor( + ui: &mut egui::Ui, + part: &mut Part, + tab: &mut Tab, + all_numbers: &[String], + duplicate: bool, + model_scale: &mut f32, +) -> Option { + let mut request = None; ui.horizontal_wrapped(|ui| { for (t, name) in [ (Tab::General, "General"), @@ -132,6 +158,7 @@ fn part_editor(ui: &mut egui::Ui, part: &mut Part, tab: &mut Tab, all_numbers: & (Tab::Mounting, "Mounting data"), (Tab::Functions, "Function template"), (Tab::Accessories, "Accessories"), + (Tab::Graphics, "Graphics"), ] { ui.selectable_value(tab, t, name); } @@ -298,7 +325,108 @@ fn part_editor(ui: &mut egui::Ui, part: &mut Part, tab: &mut Tab, all_numbers: & part.accessories.push(n); } } + Tab::Graphics => request = graphics_tab(ui, part, model_scale), }); + request +} + +/// 2D front view and 3D model of a part. +fn graphics_tab(ui: &mut egui::Ui, part: &mut Part, model_scale: &mut f32) -> Option { + let mut request = None; + ui.weak("The 2D front view is used in the panel front view and on mounting layout pages, the 3D model in the 3D panel view. Both are fitted to the mounting data (width × height × depth)."); + ui.add_space(4.0); + ui.label(RichText::new("2D front view").strong()); + ui.horizontal(|ui| { + model_2d_preview(ui, part.model_2d.as_ref(), vec2(180.0, 140.0)); + ui.vertical(|ui| { + match &part.model_2d { + Some(m) => ui.label(format!("{:.1} × {:.1} mm, {} elements", m.width, m.height, m.prims.len())), + None => ui.weak("none – a plain rectangle is drawn"), + }; + if ui.button("Import SVG…").clicked() { + request = Some(Purpose::Model2d); + } + if part.model_2d.is_some() && ui.button("🗑 Remove").clicked() { + part.model_2d = None; + } + }); + }); + ui.separator(); + ui.label(RichText::new("3D model").strong()); + ui.horizontal(|ui| { + match &part.model_3d { + Some(m) => crate::panel_ui::mesh_preview(ui, m, vec2(180.0, 160.0)), + None => { + ui.allocate_space(vec2(180.0, 40.0)); + } + } + ui.vertical(|ui| { + match &part.model_3d { + Some(m) => { + let s = m.size(); + ui.label(format!("{:.1} × {:.1} × {:.1} mm, {} triangles", s[0], s[1], s[2], m.triangles.len())); + } + None => { + ui.weak("none – a box of the mounting dimensions is drawn"); + } + } + if ui.button("Import STL / OBJ…").clicked() { + request = Some(Purpose::Model3d); + } + if part.model_3d.is_some() && ui.button("🗑 Remove").clicked() { + part.model_3d = None; + } + }); + }); + if let Some(m) = &mut part.model_3d { + ui.horizontal_wrapped(|ui| { + ui.label("Rotate 90°:"); + for (axis, label) in [(0, "X"), (1, "Y"), (2, "Z")] { + if ui.button(label).on_hover_text("Turn the model so that its front faces the viewer (+Z) and its top is +Y").clicked() { + m.rotate90(axis); + } + } + ui.separator(); + ui.label("Scale ×"); + ui.add(egui::DragValue::new(model_scale).speed(0.01).range(0.001..=10000.0)); + if ui.button("Apply").on_hover_text("e.g. 25.4 for models in inch, 1000 for models in metres").clicked() { + m.scale(*model_scale); + } + }); + let s = m.size(); + let differs = [(s[0], part.width), (s[1], part.height), (s[2], part.depth)].iter().any(|(a, b)| (a - b).abs() > 0.5); + if differs { + ui.colored_label( + Color32::from_rgb(220, 140, 0), + format!( + "The model ({:.1} × {:.1} × {:.1}) differs from the mounting data ({:.1} × {:.1} × {:.1}); it is stretched to the mounting data.", + s[0], s[1], s[2], part.width, part.height, part.depth + ), + ); + if ui.button("Use model size as mounting data").clicked() { + part.width = (s[0] * 10.0).round() / 10.0; + part.height = (s[1] * 10.0).round() / 10.0; + part.depth = (s[2] * 10.0).round() / 10.0; + } + } + } + request +} + +/// Scaled drawing of a 2D front view. +pub fn model_2d_preview(ui: &mut egui::Ui, model: Option<&Model2d>, 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 Some(m) = model.filter(|m| m.width > 0.0 && m.height > 0.0) else { + painter.text(resp.rect.center(), egui::Align2::CENTER_CENTER, "no 2D model", egui::FontId::proportional(12.0), pal.frame); + return; + }; + let zoom = ((size.x - 12.0) / m.width).min((size.y - 12.0) / m.height); + let origin = resp.rect.center() - vec2(m.width, m.height) * zoom / 2.0; + let mut d = EguiDraw { painter: &painter, origin, zoom, pal: &pal, force: None }; + d.rect(crate::geom::p(0.0, 0.0), crate::geom::p(m.width, m.height), 0.0, Ink::Fill, true); + crate::render::draw_prims_2d(&mut d, &m.prims, &|q| crate::geom::p(q[0], q[1]), 1.0, 0.15, Ink::Line); } /// Read only summary used in the selection dialog. @@ -328,6 +456,91 @@ fn part_summary(ui: &mut egui::Ui, p: &Part) { impl PartsUi { /// Opens the management window with a part selected. + /// Puts an imported 2D / 3D model into the part it was requested for. + pub fn apply_model(&mut self, loaded: &Loaded, db: &mut PartsDb, prj: &mut Project) -> Result { + let (source, number) = self.model_target.take().ok_or("no part selected for the model")?; + let list = match source { + Source::Database => &mut db.parts, + Source::Project => &mut prj.parts, + }; + let part = list.iter_mut().find(|p| p.number == number).ok_or(format!("part {number} not found"))?; + let file = crate::io::short_name(&loaded.name).to_string(); + match loaded.purpose { + Purpose::Model2d => { + let m = parts::parse_svg(&loaded.text())?; + let msg = format!("{file}: 2D front view with {} elements assigned to {number}", m.prims.len()); + part.model_2d = Some(m); + Ok(msg) + } + Purpose::Model3d => { + let m = parts::parse_mesh(&file, &loaded.bytes)?; + let s = m.size(); + // Parts without mounting data take the model size. + if part.width <= 0.0 || part.height <= 0.0 { + part.width = s[0]; + part.height = s[1]; + part.depth = s[2]; + } + let msg = format!("{file}: 3D model with {} triangles ({:.1} × {:.1} × {:.1} mm) assigned to {number}", m.triangles.len(), s[0], s[1], s[2]); + part.model_3d = Some(m); + Ok(msg) + } + _ => Err("not a model file".into()), + } + } + + /// Applies finished parts server requests (call every frame). + pub fn poll_server(&mut self, db: &mut PartsDb) -> Option { + self.server.poll(db) + } + + /// Server URL, token and transfer buttons. + fn server_panel(&mut self, ui: &mut egui::Ui, db: &PartsDb, selected: Option) { + let ctx = ui.ctx().clone(); + egui::Grid::new("server").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { + ui.label("Server URL"); + ui.add(egui::TextEdit::singleline(&mut self.server.url).desired_width(320.0)); + ui.end_row(); + ui.label("Access token"); + ui.add(egui::TextEdit::singleline(&mut self.server.token).password(true).desired_width(320.0).hint_text("only needed for uploads")); + ui.end_row(); + }); + let busy = self.server.busy(); + ui.horizontal_wrapped(|ui| { + if ui.add_enabled(!busy, egui::Button::new("Test connection")).clicked() { + self.server.check(&ctx); + } + if ui + .add_enabled(!busy, egui::Button::new("⬇ Download into database")) + .on_hover_text("Adds new parts and updates existing ones in the local parts database") + .clicked() + { + self.server.download(&ctx); + } + let upload_one = ui.add_enabled(!busy && selected.is_some(), egui::Button::new("⬆ Upload selected part")); + if upload_one.clicked() { + if let Some(p) = &selected { + self.server.upload(&ctx, std::slice::from_ref(p)); + } + } + if ui + .add_enabled(!busy && !db.parts.is_empty(), egui::Button::new(format!("⬆ Upload database ({})", db.parts.len()))) + .on_hover_text("Adds / replaces all parts of the local database on the server") + .clicked() + { + self.server.upload(&ctx, &db.parts); + } + if busy { + ui.spinner(); + } + }); + if !self.server.status.is_empty() { + let ok = !self.server.status.starts_with("Parts server:"); + let color = if ok { ui.visuals().text_color() } else { Color32::from_rgb(220, 60, 60) }; + ui.label(RichText::new(&self.server.status).color(color)); + } + } + pub fn show_part(&mut self, number: &str, in_project: bool) { self.open = true; self.source = if in_project { Source::Project } else { Source::Database }; @@ -404,6 +617,19 @@ impl PartsUi { actions.push(PartsAction::Message(format!("{n} unused project parts removed"))); } ui.separator(); + if ui + .button("Refresh example catalog parts (GEN.*)") + .on_hover_text("Replaces the GEN.* parts in the database with the current example catalog (including models)") + .clicked() + { + let catalog = parts::default_catalog(); + let n = catalog.len(); + for p in catalog { + db.upsert(p); + } + db.sort(); + actions.push(PartsAction::Message(format!("{n} example catalog parts refreshed"))); + } if ui.button("Add missing parts of the example catalog").clicked() { let mut n = 0; for p in parts::default_catalog() { @@ -415,8 +641,19 @@ impl PartsUi { actions.push(PartsAction::Message(format!("{n} catalog parts added"))); } }); + ui.separator(); + ui.toggle_value(&mut self.show_server, "🌐 Parts server") + .on_hover_text("Exchange parts with a global parts database (openecraft-server)"); }); ui.separator(); + if self.show_server { + let selected = self.selected.as_ref().and_then(|n| match self.source { + Source::Database => db.get(n).cloned(), + Source::Project => prj.parts.iter().find(|p| &p.number == n).cloned(), + }); + self.server_panel(ui, db, selected); + ui.separator(); + } // ---------------------------------------------------------- body let numbers: Vec = db.parts.iter().chain(prj.parts.iter()).map(|p| p.number.clone()).collect(); @@ -441,7 +678,10 @@ impl PartsUi { Some(i) => { let duplicate = list.iter().filter(|p| p.number == list[i].number).count() > 1; let before = list[i].number.clone(); - part_editor(ui, &mut list[i], &mut self.tab, &numbers, duplicate); + if let Some(purpose) = part_editor(ui, &mut list[i], &mut self.tab, &numbers, duplicate, &mut self.model_scale) { + self.model_target = Some((self.source, list[i].number.clone())); + actions.push(PartsAction::ImportModel(purpose)); + } if list[i].number != before { self.selected = Some(list[i].number.clone()); } @@ -533,3 +773,6 @@ impl PartsUi { } } } + +#[cfg(test)] +mod tests; diff --git a/src/parts_ui/tests.rs b/src/parts_ui/tests.rs new file mode 100644 index 00000000..e26eecf6 --- /dev/null +++ b/src/parts_ui/tests.rs @@ -0,0 +1,36 @@ +use super::*; +use crate::sample::demo_project; + +fn loaded(purpose: Purpose, name: &str, bytes: &[u8]) -> Loaded { + Loaded { purpose, name: name.into(), bytes: bytes.to_vec() } +} + +#[test] +fn imported_models_go_to_the_requested_part() { + let mut prj = demo_project(); + let mut db = PartsDb::default(); + let mut ui = PartsUi::default(); + let svg = r#""#; + // Without a requested target nothing happens. + assert!(ui.apply_model(&loaded(Purpose::Model2d, "front.svg", svg.as_bytes()), &mut db, &mut prj).is_err()); + + ui.model_target = Some((Source::Database, "GEN.CT-9A-24DC".into())); + ui.apply_model(&loaded(Purpose::Model2d, "front.svg", svg.as_bytes()), &mut db, &mut prj).unwrap(); + assert_eq!(db.get("GEN.CT-9A-24DC").unwrap().model_2d.as_ref().unwrap().prims.len(), 1); + assert!(ui.model_target.is_none()); + + // 3D into a project part without mounting data: it takes the model size. + let obj = "v 0 0 0\nv 30 0 0\nv 30 20 0\nv 0 20 10\nf 1 2 3\nf 1 3 4\n"; + prj.parts.push(Part { number: "NEW.PART".into(), ..Default::default() }); + ui.model_target = Some((Source::Project, "NEW.PART".into())); + let msg = ui.apply_model(&loaded(Purpose::Model3d, "C:/models/part.obj", obj.as_bytes()), &mut db, &mut prj).unwrap(); + assert!(msg.contains("part.obj"), "{msg}"); + let part = prj.parts.iter().find(|p| p.number == "NEW.PART").unwrap(); + assert_eq!((part.width, part.height, part.depth), (30.0, 20.0, 10.0)); + assert_eq!(part.model_3d.as_ref().unwrap().triangles.len(), 2); + + // Broken files are reported, the part keeps its model. + ui.model_target = Some((Source::Project, "NEW.PART".into())); + assert!(ui.apply_model(&loaded(Purpose::Model3d, "bad.stl", b"garbage"), &mut db, &mut prj).is_err()); + assert!(prj.parts.iter().find(|p| p.number == "NEW.PART").unwrap().model_3d.is_some()); +} diff --git a/src/render.rs b/src/render.rs index 4d5506f9..e0a868b9 100644 --- a/src/render.rs +++ b/src/render.rs @@ -6,6 +6,7 @@ use crate::index::{Index, Loc}; use crate::model::*; use crate::netlist; use crate::panel::{self, Enclosure, ItemKind, PanelItem}; +use crate::parts::{Model2d, Part, Prim2d}; use crate::parts::{self, FnKind}; use crate::reports::Analysis; use crate::symbols::{self, Anchor, ContactKind, FieldKind, Func, Prim, SymbolDef}; @@ -494,6 +495,7 @@ pub fn draw_enclosure( 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); d.rect(origin, origin + p(e.width * k, e.height * k), 0.5, Ink::Line, false); @@ -559,10 +561,67 @@ pub fn draw_enclosure( } ItemKind::Device => { d.rect(a, b, 0.0, Ink::Fill, true); - d.rect(a, b, 0.3, ink, false); - let size = (it.w.min(it.h) * 0.22).clamp(3.0, 9.0) * k; + let model = parts.iter().find(|x| x.number == it.part).and_then(|x| x.model_2d.as_ref()); let text_ink = if ink == Ink::Line { Ink::Text } else { ink }; - d.text(tf(it.x + it.w / 2.0, it.y + it.h / 2.0), &it.tag, size, Anchor::Center, VAnchor::Middle, text_ink); + let size = (it.w.min(it.h) * 0.22).clamp(3.0, 9.0) * k; + let c = tf(it.x + it.w / 2.0, it.y + it.h / 2.0); + match model { + Some(m) => { + draw_model_2d(d, m, it, &tf, k, ink); + // Tag on a small label so it stays readable on the drawing + let size = size * 0.8; + let half = p(it.tag.chars().count() as f32 * size * 0.33 + size * 0.2, size * 0.6); + d.rect(c - half, c + half, 0.0, Ink::Plate, true); + d.text(c, &it.tag, size, Anchor::Center, VAnchor::Middle, text_ink); + } + None => d.text(c, &it.tag, size, Anchor::Center, VAnchor::Middle, text_ink), + } + d.rect(a, b, 0.3, ink, false); + } + } + } +} + +/// Draws a part's 2D front view into a placed device. Rotated devices (width and +/// height swapped) get the drawing turned by 90°, other size differences are scaled. +fn draw_model_2d(d: &mut dyn Draw, m: &Model2d, it: &PanelItem, tf: &dyn Fn(f32, f32) -> P, k: f32, ink: Ink) { + if m.width <= 0.0 || m.height <= 0.0 { + return; + } + let same = |a: f32, b: f32| (a - b).abs() < 0.5; + let rotated = !same(m.width, m.height) && same(it.w, m.height) && same(it.h, m.width); + // Terminal strips: one drawing per terminal side by side. + let n = if rotated { 1 } else { panel::tiles(it.w, m.width) }; + let cell_w = it.w / n as f32; + let (sx, sy) = if rotated { (it.w / m.height, it.h / m.width) } else { (cell_w / m.width, it.h / m.height) }; + let s = (sx + sy) / 2.0; + let w = 0.15; + for tile in 0..n { + let x0 = it.x + tile as f32 * cell_w; + let map = |q: [f32; 2]| { + let (x, y) = if rotated { (m.height - q[1], q[0]) } else { (q[0], q[1]) }; + tf(x0 + x * sx, it.y + y * sy) + }; + draw_prims_2d(d, &m.prims, &map, s * k, w, ink); + } +} + +pub fn draw_prims_2d(d: &mut dyn Draw, prims: &[Prim2d], map: &dyn Fn([f32; 2]) -> P, s: f32, w: f32, ink: Ink) { + for prim in prims { + match prim { + Prim2d::Line { a, b } => d.line(map(*a), map(*b), w, ink, false), + Prim2d::Rect { min, max, fill } => { + let corners = [*min, [max[0], min[1]], *max, [min[0], max[1]]].map(map); + d.poly(&corners, true, if *fill { 0.0 } else { w }, ink, *fill); + } + Prim2d::Circle { c, r, fill } => d.circle(map(*c), r * s, if *fill { 0.0 } else { w }, ink, *fill), + Prim2d::Polyline { pts, closed, fill } => { + let v: Vec

= pts.iter().map(|q| map(*q)).collect(); + d.poly(&v, *closed, if *fill { 0.0 } else { w }, ink, *fill && *closed); + } + Prim2d::Text { pos, text, size } => { + let ink = if ink == Ink::Line { Ink::Text } else { ink }; + d.text(map(*pos), text, size * s, Anchor::Left, VAnchor::Middle, ink) } } } @@ -588,7 +647,7 @@ fn draw_mounting_page(d: &mut dyn Draw, prj: &Project, id: u64) { 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()); + draw_enclosure(d, e, origin, k, &BTreeSet::new(), &BTreeSet::new(), &prj.parts); // Dimensions let bottom = origin.y + h + 6.0; d.line(p(origin.x, bottom), p(origin.x + w, bottom), 0.18, Ink::Frame, false);