From aed95bf971a21422447300189ad55dafe8e78f8f Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:15:38 +0100 Subject: [PATCH 01/10] =?UTF-8?q?Research:=20SolidCraft=20designs=20(.sc)?= =?UTF-8?q?=20=E2=80=93=20container,=20links,=20properties,=20BOM,=20CLI?= =?UTF-8?q?=20(#363)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Findings and sources for reading SolidCraft designs, recorded before the readers are implemented; linked from the research index, SUMMARY, interop page and OPEN_WORK. Closes #363 Co-Authored-By: Claude Opus 5.5 --- docs/OPEN_WORK.md | 12 +++ docs/src/SUMMARY.md | 1 + docs/src/reference/interop.md | 3 + docs/src/research/index.md | 1 + docs/src/research/solidcraft-design.md | 127 +++++++++++++++++++++++++ 5 files changed, 144 insertions(+) create mode 100644 docs/src/research/solidcraft-design.md diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index 46796dce..d55264d8 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -695,6 +695,18 @@ real files and belong to section 3 once such files are at hand. - [ ] STEP export through the local NX (NX Open / journal), on Windows and Linux - [ ] NX load options for the workspace only on request, in the workspace wizard; NX part of the tutorial +**SolidCraft** (research page *SolidCraft designs*) + +- [x] Research page on the `.sc` design container and its sources (#363) +- [ ] Preview image from the embedded thumbnail (#364) +- [ ] Linked designs as file references with quantities (#365) +- [ ] BOM import from SolidCraft's BOM CSV and from the design (#366) +- [ ] Design properties read, shown, searchable, mismatches with the item flagged (#367) +- [ ] Desktop: STEP export through `solidcraft-cli` at check-in, all OSes (#368) +- [ ] Desktop: item number and revision written into the design properties (#369) +- [ ] Desktop: designs open in SolidCraft (lock file) shown, warning at check-in (#370) +- [ ] (research first) 3D preview from the `.sc` file alone (#371) + ### 5. Feature demand (backlog) What users ask of PLM/PDM systems (reviews of commercial and open-source PLM/PDM systems, vendor community diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index fe7fef57..28df86a3 100755 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -93,3 +93,4 @@ - [Read permissions for project groups](research/read-permissions.md) - [As-built records](research/as-built.md) - [Fluent, STAR-CCM+ and Simcenter 3D files](research/solver-files.md) + - [SolidCraft designs](research/solidcraft-design.md) diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index cab9ddb1..e7d993dd 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -22,3 +22,6 @@ references it. The three projects share their approach – one Rust build, a desktop app and a command line, open formats – but not code: TeamCraft is licensed under the MPL-2.0 and does not include SolidCraft or FieldCraft code. + +What TeamCraft reads from a `.sc` design, and the sources of those findings, are +recorded in the research page [SolidCraft designs](../research/solidcraft-design.md). diff --git a/docs/src/research/index.md b/docs/src/research/index.md index 774d57f8..e37d0a6d 100755 --- a/docs/src/research/index.md +++ b/docs/src/research/index.md @@ -16,6 +16,7 @@ accepted in TeamCraft, from people or from AI agents | Topic | Decision | Date | |---------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------| +| [SolidCraft designs (`.sc`)](solidcraft-design.md) | read thumbnail, linked designs, BOM and design properties from the ZIP or JSON design with own bounded readers – unknown versions or malformed parts are "nothing found", never an error; `solidcraft-cli` only from the desktop app (STEP export, property write-back); the native B-rep model cache not now | 2026-11-21 | | [A hosted live demo](live-demo.md) | one public read-only account (`TEAMCRAFT_DEMO_USER`, password on the login page; every non-`GET` request refused, per-address sign-in throttle only) on an instance seeded with the README demo data (NIST CAD models), reset nightly to a database snapshot; no open sign-up, no editing, no per-visitor instances | 2026-11-14 | | [One download to try TeamCraft on a laptop](local-test-server.md) | bundle PostgreSQL's programs (theseus-rs builds, PostgreSQL Licence, newest 18.x, checksum-checked) with the desktop app and the server as `teamcraft-server`; `teamcraft local` runs a private cluster (scram, random password, 127.0.0.1 only, free port, no socket) and the server, and stops both when the app's stdin pipe closes; separate *with local server* installers for Windows x64, macOS Apple silicon and Linux x86_64; no new crate, no SQLite, no `postgresql_embedded` | 2026-11-14 | | [Deprovisioning through the identity provider (SCIM 2.0)](scim-deprovisioning.md) | not now: the target audience's IdPs (university SAML/OIDC proxies, Keycloak) send no SCIM; the idle-SSO report, idle token lifetimes and OIDC back-channel logout cover what they can signal (#173 step 9). Later: `active: false` (boolean or string, `PATCH` or `PUT`) → *Offboard and deactivate* with a configured default, soft delete only | 2026-11-12 | diff --git a/docs/src/research/solidcraft-design.md b/docs/src/research/solidcraft-design.md new file mode 100644 index 00000000..e7f80438 --- /dev/null +++ b/docs/src/research/solidcraft-design.md @@ -0,0 +1,127 @@ +# SolidCraft designs (`.sc`) + +*2026-11-21* + +## Question + +What can TeamCraft read from a SolidCraft design without SolidCraft – a +picture, the linked designs, the bill of materials, the design properties – +and what does it take to keep up with a format that changes with almost +every release? (Issues #363–#371.) + +## Sources + +All findings come from SolidCraft's public documentation and its source +code, licensed MIT OR Apache-2.0, as of SolidCraft 0.46.1 (commit +`18c9760e3`, ). They were read as +a specification; TeamCraft's readers are its own code and no SolidCraft code +is copied or vendored (see [FieldCraft and SolidCraft](../reference/interop.md)). + +| Topic | Source | +|-------------------------------------------|------------------------------------------------------------| +| Container, blobs, caches, limits | `docs/design-container.md` | +| Document model (components, links, parts) | `crates/doc/src/document.rs`, `crates/doc/src/assembly.rs` | +| Design and part properties | `crates/doc/src/metadata.rs`, `crates/engine/src/cmd/metadata.rs` | +| Linked designs | `crates/engine/src/cmd/component_link.rs` | +| Bill of materials and its CSV | `crates/doc/src/bom.rs`, `crates/engine/src/cmd/bom.rs` | +| Lock and backup files | `crates/io/src/design_lock.rs`, `crates/io/src/safe_write.rs` | +| Command-line tool | `apps/solidcraft-cli/src/main.rs` (usage texts) | +| Plugin runtime (no network) | `docs/plugin-runtime.md` | + +## Findings + +### Two encodings, one extension + +* **ZIP container** (new designs): starts with `PK\x03\x04`. + `container.json` = `{"format":"solidcraft-container/1"}` (earlier drafts: + `solvecraft-container/1`), `document.json` = the parametric document. +* **Plain JSON**: the same document as one JSON object, + `"format": "solidcraft/N"`. Still written by *Save As JSON*, scripts and + MCP, and fully supported. +* The legacy extension `.solidcraft` holds either encoding. `.sc` is also used + for command scripts, which is why `cadformat.rs` checks the content. +* The document format number `N` changes often (0.22.0 wrote 35); an older + SolidCraft refuses a newer design. Unknown fields must be ignored by any + reader outside SolidCraft. + +### Container entries + +| Entry | Present | Content | +|---------------------------------------------|-----------------------------------------------------------|---------| +| `container.json`, `document.json` | always | format marker; the document, imports' payloads replaced by blob references | +| `blobs/.` | when the design imports STEP/meshes or holds images | content-addressed inputs (SHA-256 of the uncompressed payload) | +| `cache/thumbnail.json`, `cache/thumbnail.png` | warm desktop saves with `cache: true` (the default); not in browser downloads, not with errors or an active sketch | 240 × 150 PNG (≤ 256 KiB), isometric view; key `solidcraft-thumbnail/1`, app version, SHA-256 of `document.json` and of the PNG | +| `cache/preview.json`, `cache/preview.bin` | only saves with `preview: true` (not the default) | display meshes, `SCMESH01`, ≤ 8 MiB / 100,000 triangles | +| `cache/model.json`, `cache/bodies.bin` | desktop saves with `cache: true` | the evaluated model: native exact B-rep per body (`docs/native-brep.md`), mesh bodies as `SCMESH01` slices; keyed by a build digest | + +SolidCraft's own reader limits: 256 MiB per part, 512 MiB expanded, at most +10,000 entries; ZIP64, multi-disk archives, duplicate names and path +traversal refused. Metadata is Deflate level 1, STEP/mesh blobs stored or +Deflate, PNG stored. + +### Document contents TeamCraft can use + +* `metadata` (design properties): text keys `project`, `part_number`, + `revision`, `author`, `organization`, `description`, `license`; another + tool's data as an object under a reverse-DNS key, kept untouched by + SolidCraft. Limits: keys ≤ 128 bytes, text ≤ 4 KiB, ≤ 256 keys, ≤ 256 KiB. +* `components[]`: `id`, `name`, `parent` (0 = root), `metadata` (the same keys + plus part-only `bom_type`, `material`, `bom_quantity`, `virtual`) and free + `properties` (name → text). +* `occurrences[]`: `id`, `component`, `parent`, `name`, `transform`, + `grounded`, optional `bom_type` override – the placements counted by the + bill of materials. +* `links`: map component id → `DesignLink { path, feature, configuration?, … }`. + `path` is relative to the assembly's folder once it is saved, `/` + separators (absolute for an unsaved assembly). The linked bodies are also + kept in the assembly, so a missing file is a stale link, not a broken + assembly. +* `parts`: map component id → standard part (rebuilt from parameters, no + file) – not a file reference; a purchased part for the BOM. + +### Bill of materials CSV + +`assembly.bom` writes the fixed columns `item, part_number, description, +revision, count, definition, material, quantity`, every field quoted; nested +rows numbered `1.1`, `1.1.1`. `count` is the number of placements, `quantity` +an amount (length, area …) where the definition has one. + +### Files next to a design + +* `.~.lock`: JSON (computer, user, app version, process, opened and + refreshed times) while the desktop app has the design open; refreshed every + 60 s, stale after 180 s, at most 4 KiB read. +* `.bak`: the previous version, written on save. + +Both are already skipped by the desktop app's `is_ignored`. + +### Command-line tool + +* `solidcraft-cli run --in design.sc --out design.step` (also `.3mf`, `.stl`, + `.glb`; several `--out`). A failing feature fails the run and writes + nothing unless `--allow-errors`. +* `solidcraft-cli snapshot --in design.sc --out shot.png [--view iso]`. +* `solidcraft-cli run script.json --in design.sc --save design.sc` runs + commands such as `document.metadata.set` headless. +* Installers put it beside the app, not always on `PATH`. + +### Plugins + +SolidCraft's plugins are sandboxed WebAssembly components without sockets, +HTTP or fetch: an add-in inside SolidCraft cannot talk to a TeamCraft server. + +## Decision + +* Read `.sc` designs on the server with TeamCraft's own bounded ZIP/JSON + reading: the thumbnail (#364), linked designs as references (#365), the + BOM (#366) and the design properties (#367). **An unknown version, a + missing entry or a malformed part is "nothing found", never an error** – + the format moves daily and a file must never fail an upload. +* Parse only the fields needed, with serde defaults and unknown fields + ignored; never depend on the format number. +* Shell out to `solidcraft-cli` only in the desktop app (#368, #369), like the + Inventor and Solid Edge exports; conversions on the server stay pure Rust. +* The model cache (native B-rep) is not read now; a 3D preview without an + export is a separate investigation (#371). +* Fixtures: small designs built in the tests (JSON, and ZIPs written with the + `zip` crate) plus designs saved by SolidCraft once available. From 8097aba690ba6f9cd40f486f829e4a4c297e5f39 Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:18:23 +0100 Subject: [PATCH 02/10] SolidCraft designs: preview image from the embedded thumbnail (#364) src/scdesign.rs opens the .sc ZIP design container with bounded, size- and CRC-checked reads and returns cache/thumbnail.png only when its key (solidcraft-thumbnail/1) names the SHA-256 of this document.json and of the PNG. Unknown versions, drawing containers, damaged or oversized entries are 'no picture', never an error. thumbnail.rs supports solidcraft-design; the existing thumbnail fuzz target covers the new path. Docs: guide/files.md, reference/formats.md, reference/interop.md, README, CHANGELOG, OPEN_WORK, CLAUDE.md architecture map; scdesign.rs added to the mutation-testing globs. Closes #364 Co-Authored-By: Claude Opus 5.5 --- .cargo/mutants.toml | 1 + CHANGELOG.md | 8 ++ CLAUDE.md | 1 + README.md | 2 +- docs/OPEN_WORK.md | 2 +- docs/src/guide/files.md | 4 +- docs/src/reference/formats.md | 3 + docs/src/reference/interop.md | 2 +- src/lib.rs | 1 + src/scdesign.rs | 262 ++++++++++++++++++++++++++++++++++ src/thumbnail.rs | 28 +++- 11 files changed, 309 insertions(+), 5 deletions(-) create mode 100644 src/scdesign.rs diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index a4001495..25c7785e 100755 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -20,6 +20,7 @@ examine_globs = [ "src/cadformat.rs", "src/cadrefs.rs", "src/stepbom.rs", + "src/scdesign.rs", # the 3D readers: pure, untrusted input, unit tests per format "src/mesh.rs", "src/mesh/**/*.rs", diff --git a/CHANGELOG.md b/CHANGELOG.md index b3e432c0..f3bfdf88 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,14 @@ see the notices in the README. ## [Unreleased] +### Added + +- **SolidCraft designs show their picture** (#364). The preview image of a + `.sc` design is the PNG SolidCraft embeds when saving with its model, read + from the ZIP container with size and CRC checks and shown only when its key + names the SHA-256 of this document and of the picture; unknown versions or + damaged archives simply show none (`src/scdesign.rs`). + ## [0.2.11] - 2026-11-21 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 31c22338..c40f56ba 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -162,6 +162,7 @@ src/nxpart.rs NX part stream container (SPLMSSTR): directory, reference str src/nxasm.rs NX assemblies: components + placements from /Root/FastLoad/Structure (OM objects, hash map instance→record); services/assemblies.rs composes the assembly preview from the parts' previews (found by file name) src/fusion.rs Fusion design archives (.f3d): ZIP with Zstandard entries (ruzstd), size/CRC-checked; sample archives for tests +src/scdesign.rs SolidCraft designs (.sc): ZIP design container (bounded, size/CRC-checked, unknown versions = nothing found), embedded thumbnail src/swpart.rs SOLIDWORKS 2015+ section container: Deflate sections (bounded, CRC-checked), PreviewPNG, component tree (COMPINSTANCETREE): referenced files and placements (assembly previews, also via services/assemblies.rs) src/invpart.rs Inventor files: OLE storage RSeStorage, zlib or Zstandard segments (meta stream: section lengths + class UUID table), diff --git a/README.md b/README.md index e4aef89f..e5dd147b 100755 --- a/README.md +++ b/README.md @@ -321,7 +321,7 @@ end-to-end tests against a real PostgreSQL. service, or a local model (Ollama, vLLM). In the desktop app it is the *Agent* view's company AI. - **SolidCraft and FieldCraft** – [SolidCraft](https://github.com/tangency-labs/solidcraft) designs (`.sc`, checked by content) and - [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised and their STEP and 3MF + [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised, SolidCraft's embedded picture is the preview image, and their STEP and 3MF exports previewed – design, export and analysis in one revision ([more](https://warr-ev.github.io/TeamCraft/reference/interop.html)). diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index d55264d8..f68f2883 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -698,7 +698,7 @@ real files and belong to section 3 once such files are at hand. **SolidCraft** (research page *SolidCraft designs*) - [x] Research page on the `.sc` design container and its sources (#363) -- [ ] Preview image from the embedded thumbnail (#364) +- [x] Preview image from the embedded thumbnail (#364); left: rendered pictures for designs saved without one (#368) - [ ] Linked designs as file references with quantities (#365) - [ ] BOM import from SolidCraft's BOM CSV and from the design (#366) - [ ] Design properties read, shown, searchable, mismatches with the item flagged (#367) diff --git a/docs/src/guide/files.md b/docs/src/guide/files.md index e3753d72..e27a310d 100755 --- a/docs/src/guide/files.md +++ b/docs/src/guide/files.md @@ -199,7 +199,9 @@ For the rest TeamCraft shows what other PLM systems show: assemblies none of whose parts are in TeamCraft, keep the stored image. * **The preview image stored in the file.** Inventor drawings and presentations (`.idw`, `.ipn`), Solid Edge (`.par`, `.psm`, `.asm`, `.pwd`, `.dft`), NX assemblies and drawings - (`.prt`, a JPEG) and + (`.prt`, a JPEG), SolidCraft designs (`.sc`, the picture SolidCraft keeps in the + design when it was saved with its model – shown only while it still belongs to the + saved design) and SolidWorks files (up to 2014 in their OLE container, from 2015 on in a compressed section that TeamCraft inflates) carry a picture the CAD program wrote when saving. It appears next to the file on the revision page and in the desktop app (`GET /api/v1/files/{id}/thumbnail`). Only the diff --git a/docs/src/reference/formats.md b/docs/src/reference/formats.md index db7db75d..5dd00648 100755 --- a/docs/src/reference/formats.md +++ b/docs/src/reference/formats.md @@ -232,6 +232,9 @@ from CAD…* reads the counts from the file and works without it). `.prt` and `.asm` are told apart by content (Creo's `#UGC:` header, Solid Edge's OLE container); `.sc` must be a SolidCraft ZIP or JSON design. +A SolidCraft ZIP design shows the picture it embeds (`cache/thumbnail.png`) +when its key (`cache/thumbnail.json`, `solidcraft-thumbnail/1`) names the +SHA-256 of this `document.json` and of the PNG; otherwise none. ## BIM / architecture diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index e7d993dd..3598e322 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -8,7 +8,7 @@ program: | File | TeamCraft | |-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| -| SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs) | +| SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs); the picture SolidCraft embeds (`cache/thumbnail.png`) is the preview image when its key still names this document | | FieldCraft model `.fieldcraft` (ZIP: `fieldcraft.json`, `model.json`, `mesh.bin`, `journal.json`) | recognised as *FieldCraft analysis model* | | STEP, 3MF (incl. SolidCraft's face-tagged 3MF), STL, OBJ exports | 3D preview in the browser and the desktop app; STEP is searchable and scanned for references | | Abaqus input decks (`.inp`) written by FieldCraft | recognised as *Abaqus input file* | diff --git a/src/lib.rs b/src/lib.rs index caf98a68..a4ddda60 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,6 +53,7 @@ pub mod pagecontext; pub mod pdftext; pub mod preview; pub mod resultscan; +pub mod scdesign; pub mod services; pub mod shape; pub mod simmesh; diff --git a/src/scdesign.rs b/src/scdesign.rs new file mode 100644 index 00000000..e483c905 --- /dev/null +++ b/src/scdesign.rs @@ -0,0 +1,262 @@ +//! SolidCraft designs (`.sc`, legacy `.solidcraft`): the ZIP design +//! container and the parts TeamCraft reads from it. Findings and sources in +//! `docs/src/research/solidcraft-design.md`. +//! +//! The format changes with almost every SolidCraft release, so nothing here +//! is an error for the caller: an unknown container version, a missing or +//! oversized entry, a damaged archive or a stale cache is "nothing found" +//! (`None`). Entries are read into memory within fixed limits; nothing is +//! extracted to disk. Only stored and Deflate entries are read, with their +//! size and CRC-32 checked. +#![deny( + clippy::unwrap_used, + clippy::expect_used, + clippy::indexing_slicing, + clippy::panic, + clippy::unreachable +)] + +use std::io::{Read, Seek}; + +use sha2::{Digest, Sha256}; +use zip::CompressionMethod; + +const ZIP_MAGIC: &[u8; 4] = b"PK\x03\x04"; +/// SolidCraft's own limit on the number of entries. +const MAX_ENTRIES: usize = 10_000; +/// `container.json` and the thumbnail key are a few dozen bytes. +const MAX_SMALL: u64 = 4096; +/// SolidCraft caps the thumbnail at 256 KiB. +const MAX_THUMBNAIL: u64 = 256 * 1024; +/// Largest `document.json` read (what SolidCraft allows for previews). +pub const MAX_DOCUMENT: u64 = 16 * 1024 * 1024; +/// Container formats of designs (`solvecraft-` from early drafts). +const CONTAINER_FORMATS: [&str; 2] = ["solidcraft-container/", "solvecraft-container/"]; +/// The thumbnail key's format this reader knows. +const THUMBNAIL_FORMAT: &str = "solidcraft-thumbnail/1"; + +/// Whether `head` (the first bytes of a file) starts a ZIP archive. +pub fn is_zip(head: &[u8]) -> bool { + head.starts_with(ZIP_MAGIC) +} + +/// An opened SolidCraft design container. +pub struct Container { + zip: zip::ZipArchive, +} + +impl Container { + /// Opens a design container; `None` when the file is not a ZIP, has too + /// many entries, or its `container.json` does not name a design + /// container (a drawing container, another program's ZIP). + pub fn open(reader: R) -> Option { + let zip = zip::ZipArchive::new(reader).ok()?; + if zip.len() > MAX_ENTRIES { + return None; + } + let mut container = Container { zip }; + let marker = container.read("container.json", MAX_SMALL)?; + let marker: serde_json::Value = serde_json::from_slice(&marker).ok()?; + let format = marker.get("format")?.as_str()?; + let content = marker.get("content").and_then(serde_json::Value::as_str); + let design = CONTAINER_FORMATS.iter().any(|f| format.starts_with(f)) + && content.is_none_or(|c| c == "design"); + design.then_some(container) + } + + /// The content of the entry `name`, if it exists, is at most `limit` + /// bytes, is stored or Deflate-compressed and matches its size and CRC. + pub fn read(&mut self, name: &str, limit: u64) -> Option> { + let mut file = self.zip.by_name(name).ok()?; + let method = file.compression(); + if method != CompressionMethod::Stored && method != CompressionMethod::Deflated { + return None; + } + let size = file.size(); + let crc = file.crc32(); + if size > limit { + return None; + } + let mut data = Vec::with_capacity(usize::try_from(size).unwrap_or(0)); + (&mut file) + .take(size.saturating_add(1)) + .read_to_end(&mut data) + .ok()?; + (data.len() as u64 == size && crc32fast::hash(&data) == crc).then_some(data) + } + + /// The embedded picture (`cache/thumbnail.png`), when its key + /// (`cache/thumbnail.json`) has a known format and names the SHA-256 of + /// both this exact `document.json` and the PNG. A picture left from an + /// older document (another tool rewrote the document) is not shown. + pub fn thumbnail(&mut self) -> Option> { + let key = self.read("cache/thumbnail.json", MAX_SMALL)?; + let key: serde_json::Value = serde_json::from_slice(&key).ok()?; + let field = |name: &str| key.get(name).and_then(serde_json::Value::as_str); + if field("format") != Some(THUMBNAIL_FORMAT) { + return None; + } + let png = self.read("cache/thumbnail.png", MAX_THUMBNAIL)?; + if !field("payload").is_some_and(|d| same_digest(d, &png)) { + return None; + } + let document = self.read("document.json", MAX_DOCUMENT)?; + field("document") + .is_some_and(|d| same_digest(d, &document)) + .then_some(png) + } +} + +/// Whether `hex_digest` is the SHA-256 of `data` (hex, either case). +fn same_digest(hex_digest: &str, data: &[u8]) -> bool { + hex_digest.eq_ignore_ascii_case(&hex::encode(Sha256::digest(data))) +} + +/// Builders for small design containers, for the tests and the fuzz corpus. +#[doc(hidden)] +pub mod sample { + use std::io::{Cursor, Write}; + + use sha2::{Digest, Sha256}; + + /// A ZIP of `entries` (name, content), Deflate-compressed. + pub fn zip(entries: &[(&str, &[u8])]) -> Vec { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + for (name, data) in entries { + if writer.start_file(*name, options).is_err() || writer.write_all(data).is_err() { + return Vec::new(); + } + } + writer.finish().map(Cursor::into_inner).unwrap_or_default() + } + + /// The thumbnail key SolidCraft writes for `png` beside `document`. + pub fn thumbnail_key(document: &[u8], png: &[u8]) -> Vec { + let digest = |d: &[u8]| hex::encode(Sha256::digest(d)); + serde_json::json!({ + "format": "solidcraft-thumbnail/1", + "app": "0.46.1", + "document": digest(document), + "payload": digest(png), + }) + .to_string() + .into_bytes() + } + + /// A design container with `document` and, if given, a thumbnail. + pub fn design(document: &[u8], png: Option<&[u8]>) -> Vec { + let container: &[u8] = br#"{"format":"solidcraft-container/1"}"#; + match png { + Some(png) => { + let key = thumbnail_key(document, png); + zip(&[ + ("document.json", document), + ("container.json", container), + ("cache/thumbnail.json", &key), + ("cache/thumbnail.png", png), + ]) + } + None => zip(&[("document.json", document), ("container.json", container)]), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + use std::io::Cursor; + + const DOC: &[u8] = br#"{"format":"solidcraft/35","metadata":{}}"#; + + fn thumbnail(bytes: Vec) -> Option> { + Container::open(Cursor::new(bytes))?.thumbnail() + } + + #[test] + fn the_keyed_thumbnail_is_found() { + let png = crate::thumbnail::tests::png(240, 150); + assert_eq!(thumbnail(sample::design(DOC, Some(&png))), Some(png)); + } + + #[test] + fn no_thumbnail_is_none() { + assert_eq!(thumbnail(sample::design(DOC, None)), None); + } + + #[test] + fn a_picture_of_another_document_is_not_shown() { + let png = crate::thumbnail::tests::png(240, 150); + let key = sample::thumbnail_key(b"{\"older\":1}", &png); + let bytes = sample::zip(&[ + ("document.json", DOC), + ("container.json", br#"{"format":"solidcraft-container/1"}"#), + ("cache/thumbnail.json", &key), + ("cache/thumbnail.png", &png), + ]); + assert_eq!(thumbnail(bytes), None); + } + + #[test] + fn a_changed_picture_or_unknown_key_is_not_shown() { + let png = crate::thumbnail::tests::png(240, 150); + let other = crate::thumbnail::tests::png(16, 16); + let key = sample::thumbnail_key(DOC, &png); + let container: &[u8] = br#"{"format":"solidcraft-container/1"}"#; + let swapped = sample::zip(&[ + ("document.json", DOC), + ("container.json", container), + ("cache/thumbnail.json", &key), + ("cache/thumbnail.png", &other), + ]); + assert_eq!(thumbnail(swapped), None); + let newer = String::from_utf8(key) + .unwrap() + .replace("solidcraft-thumbnail/1", "solidcraft-thumbnail/2"); + let bytes = sample::zip(&[ + ("document.json", DOC), + ("container.json", container), + ("cache/thumbnail.json", newer.as_bytes()), + ("cache/thumbnail.png", &png), + ]); + assert_eq!(thumbnail(bytes), None); + } + + #[test] + fn only_design_containers_open() { + let doc = + |marker: &[u8]| sample::zip(&[("document.json", DOC), ("container.json", marker)]); + assert!( + Container::open(Cursor::new(doc(br#"{"format":"solidcraft-container/1"}"#))).is_some() + ); + assert!( + Container::open(Cursor::new(doc(br#"{"format":"solvecraft-container/1"}"#))).is_some() + ); + assert!(Container::open(Cursor::new(doc(br#"{"format":"other/1"}"#))).is_none()); + assert!(Container::open(Cursor::new(doc( + br#"{"content":"drawing","format":"solidcraft-container/1"}"# + ))) + .is_none()); + assert!(Container::open(Cursor::new(sample::zip(&[("document.json", DOC)]))).is_none()); + assert!(Container::open(Cursor::new(b"PK\x03\x04garbage".to_vec())).is_none()); + } + + #[test] + fn a_truncated_or_oversized_entry_is_none() { + let png = crate::thumbnail::tests::png(240, 150); + let bytes = sample::design(DOC, Some(&png)); + for cut in [bytes.len() / 2, bytes.len() - 10] { + assert_eq!(thumbnail(bytes[..cut].to_vec()), None, "cut at {cut}"); + } + let big = vec![0u8; MAX_SMALL as usize + 1]; + let bytes = sample::zip(&[ + ("document.json", DOC), + ("container.json", br#"{"format":"solidcraft-container/1"}"#), + ("cache/thumbnail.json", &big), + ("cache/thumbnail.png", &png), + ]); + assert_eq!(thumbnail(bytes), None); + } +} diff --git a/src/thumbnail.rs b/src/thumbnail.rs index 7571ef76..97344626 100755 --- a/src/thumbnail.rs +++ b/src/thumbnail.rs @@ -14,6 +14,9 @@ //! and poor, so NX parts get a thumbnail rendered from their 3D preview //! instead ([`rendered`], [`render_mesh`]); the JPEG stays the fallback //! for NX files without one (assemblies, drawings). +//! * SolidCraft designs (`.sc`) keep a PNG in their ZIP container +//! (`cache/thumbnail.png`), shown only when its key names this exact +//! document and picture (`scdesign`). //! //! Every candidate is validated (PNG chunk structure and checksums, plausible //! DIB header and sizes); the summary information wins, then streams named @@ -76,6 +79,7 @@ pub fn supports(format_id: &str) -> bool { | "creo-part" | "creo-assembly" | "fusion-design" + | "solidcraft-design" ) } @@ -135,6 +139,15 @@ pub fn extract_from(mut file: R) -> io::Result if crate::fusion::is_archive(head) { return from_fusion(file); } + if crate::scdesign::is_zip(head) { + if let Some(mut design) = crate::scdesign::Container::open(&mut file) { + return Ok(design + .thumbnail() + .and_then(|png| png_at(&png)) + .map(|f| f.thumbnail)); + } + file.rewind()?; + } let mut data = Vec::new(); file.take(MAX_SCAN).read_to_end(&mut data)?; Ok(find_in(&data, false).map(|f| f.thumbnail)) @@ -528,7 +541,7 @@ pub fn render_mesh(mesh_bytes: &[u8]) -> Option { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use std::io::{Cursor, Write}; @@ -860,4 +873,17 @@ mod tests { let _ = jpeg_size(&full[..cut]); } } + + #[test] + fn solidcraft_designs_show_their_embedded_picture() { + let doc: &[u8] = br#"{"format":"solidcraft/35"}"#; + let picture = png(240, 150); + let design = crate::scdesign::sample::design(doc, Some(&picture)); + let found = extract_from(Cursor::new(design)).unwrap().unwrap(); + assert_eq!(found.content_type, "image/png"); + assert_eq!(found.bytes, picture); + let bare = crate::scdesign::sample::design(doc, None); + assert_eq!(extract_from(Cursor::new(bare)).unwrap(), None); + assert!(supports("solidcraft-design")); + } } From 8e5fdc966fe265c513e34281532cd0a9b52c45fe Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:21:55 +0100 Subject: [PATCH 03/10] SolidCraft assemblies: linked designs as file references (#365) scdesign::document reads the document of a ZIP or plain-JSON design (bounded, 16 MiB), scdesign::linked_designs the file names of its links with the placements of the linked components as counts (a component without a placement counts once; standard parts are no files). cadrefs uses them for .sc files instead of the text heuristic and as instance counts. The JSON design check moved from cadformat to scdesign. New fuzz target scdesign (harness, target, seed, CI matrix). Docs: guide/structure.md, reference/formats.md (incl. rescan), reference/interop.md, dev/fuzzing.md, README, CHANGELOG, OPEN_WORK, CLAUDE.md architecture map. Closes #365 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/fuzz.yml | 2 +- CHANGELOG.md | 7 ++ CLAUDE.md | 3 +- README.md | 3 +- docs/OPEN_WORK.md | 2 +- docs/src/dev/fuzzing.md | 4 +- docs/src/guide/structure.md | 5 +- docs/src/reference/formats.md | 9 +- docs/src/reference/interop.md | 2 +- fuzz/Cargo.toml | 7 ++ fuzz/fuzz_targets/scdesign.rs | 7 ++ fuzz/seeds/scdesign/assembly.sc | 1 + src/cadformat.rs | 12 +-- src/cadrefs.rs | 50 ++++++++++- src/fuzz_harness.rs | 13 +++ src/scdesign.rs | 142 ++++++++++++++++++++++++++++++++ 16 files changed, 248 insertions(+), 21 deletions(-) create mode 100644 fuzz/fuzz_targets/scdesign.rs create mode 100644 fuzz/seeds/scdesign/assembly.sc diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 5141e8ab..0f9928f4 100755 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -52,7 +52,7 @@ jobs: strategy: fail-fast: false matrix: - target: [stepbom, swpart, nxpart, invpart, cadrefs, bomtable, thumbnail, textindex, htmltext, mesh, mesh_step, cadformat, resultscan, solversummary] + target: [stepbom, swpart, nxpart, invpart, cadrefs, bomtable, thumbnail, scdesign, textindex, htmltext, mesh, mesh_step, cadformat, resultscan, solversummary] steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master diff --git a/CHANGELOG.md b/CHANGELOG.md index f3bfdf88..a9bafd47 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,13 @@ see the notices in the README. from the ZIP container with size and CRC checks and shown only when its key names the SHA-256 of this document and of the picture; unknown versions or damaged archives simply show none (`src/scdesign.rs`). +- **SolidCraft assemblies reference their linked designs** (#365). The + designs an assembly links (*Insert Design*) are its file references, with + the number of placements as instance count, so where-used, *Create BOM + from CAD references* and the desktop's dependent files work for SolidCraft; + read from the ZIP or JSON document, unknown fields ignored. New fuzz target + `scdesign`. Run `teamcraft rescan-references --format solidcraft-design` + once for designs stored before. ## [0.2.11] - 2026-11-21 diff --git a/CLAUDE.md b/CLAUDE.md index c40f56ba..c72c38f7 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -162,7 +162,8 @@ src/nxpart.rs NX part stream container (SPLMSSTR): directory, reference str src/nxasm.rs NX assemblies: components + placements from /Root/FastLoad/Structure (OM objects, hash map instance→record); services/assemblies.rs composes the assembly preview from the parts' previews (found by file name) src/fusion.rs Fusion design archives (.f3d): ZIP with Zstandard entries (ruzstd), size/CRC-checked; sample archives for tests -src/scdesign.rs SolidCraft designs (.sc): ZIP design container (bounded, size/CRC-checked, unknown versions = nothing found), embedded thumbnail +src/scdesign.rs SolidCraft designs (.sc): ZIP design container (bounded, size/CRC-checked, unknown versions = nothing found), embedded thumbnail, + document of ZIP or JSON designs, linked designs with placement counts (cadrefs) src/swpart.rs SOLIDWORKS 2015+ section container: Deflate sections (bounded, CRC-checked), PreviewPNG, component tree (COMPINSTANCETREE): referenced files and placements (assembly previews, also via services/assemblies.rs) src/invpart.rs Inventor files: OLE storage RSeStorage, zlib or Zstandard segments (meta stream: section lengths + class UUID table), diff --git a/README.md b/README.md index e5dd147b..567efae9 100755 --- a/README.md +++ b/README.md @@ -321,7 +321,8 @@ end-to-end tests against a real PostgreSQL. service, or a local model (Ollama, vLLM). In the desktop app it is the *Agent* view's company AI. - **SolidCraft and FieldCraft** – [SolidCraft](https://github.com/tangency-labs/solidcraft) designs (`.sc`, checked by content) and - [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised, SolidCraft's embedded picture is the preview image, and their STEP and 3MF + [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised, SolidCraft's embedded picture is the preview image, linked designs are + file references with quantities, and their STEP and 3MF exports previewed – design, export and analysis in one revision ([more](https://warr-ev.github.io/TeamCraft/reference/interop.html)). diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index f68f2883..d2b1da37 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -699,7 +699,7 @@ real files and belong to section 3 once such files are at hand. - [x] Research page on the `.sc` design container and its sources (#363) - [x] Preview image from the embedded thumbnail (#364); left: rendered pictures for designs saved without one (#368) -- [ ] Linked designs as file references with quantities (#365) +- [x] Linked designs as file references with quantities (#365); left: rewriting link paths after a rename (with #369) - [ ] BOM import from SolidCraft's BOM CSV and from the design (#366) - [ ] Design properties read, shown, searchable, mismatches with the item flagged (#367) - [ ] Desktop: STEP export through `solidcraft-cli` at check-in, all OSes (#368) diff --git a/docs/src/dev/fuzzing.md b/docs/src/dev/fuzzing.md index 1e63213b..b821f8ff 100755 --- a/docs/src/dev/fuzzing.md +++ b/docs/src/dev/fuzzing.md @@ -18,7 +18,7 @@ allocate what a file only claims. The targets are `stepbom`, `swpart`, `nxpart`, `invpart` (Inventor segments, part meshes and assembly placements), `creopart` (the Creo B-rep container, tagged format and tessellation), `cadrefs`, `bomtable`, -`thumbnail`, `textindex`, `htmltext` (HTML reports and the charset detection of text files), `mesh` (STL, OBJ, PLY, OFF, +`thumbnail`, `scdesign` (SolidCraft designs: document, linked designs, thumbnail), `textindex`, `htmltext` (HTML reports and the charset detection of text files), `mesh` (STL, OBJ, PLY, OFF, 3MF, AMF, glTF, 3DS, points, LAS, VTK legacy and XML, CalculiX FRD) and `mesh_step` (the STEP tessellation through `truck`, kept apart because it is slow), `cadformat` (the @@ -38,7 +38,7 @@ crash only when it reaches the harness. Every reader of untrusted files denies `clippy::unwrap_used`, `expect_used`, `indexing_slicing`, `panic` and `unreachable` with `#![deny(...)]` at the top of the module. These are `swpart`, `mesh` with its submodules, -`simmesh`, `stepbom`, `nxpart`, `thumbnail`, `cadrefs`, `bomtable`, +`simmesh`, `stepbom`, `nxpart`, `thumbnail`, `scdesign`, `cadrefs`, `bomtable`, `textindex`, `htmltext`, `resultscan` and `cadformat`, and `config` too. Clippy in CI therefore refuses a new `data[at]`, `data[a..b]` or `.unwrap()` there. Read through the bounded helpers in `mesh` (`bytes_at`, `u16_le`, `u32_le`, `f32_le`, `range`, diff --git a/docs/src/guide/structure.md b/docs/src/guide/structure.md index 0647c253..27d5824f 100755 --- a/docs/src/guide/structure.md +++ b/docs/src/guide/structure.md @@ -148,8 +148,9 @@ cannot see are only counted. Besides the BOM, revisions reference other items: *drawing of*, *specification for*, *references*. CAD files are scanned for the files they reference (assemblies, drawings, STEP, KiCad; ASCII and UTF-16 paths as -written by SolidWorks, Inventor, Solid Edge, CATIA, …; NX parts and -SOLIDWORKS 2015+ files through their containers, see +written by SolidWorks, Inventor, Solid Edge, CATIA, …; NX parts, +SOLIDWORKS 2015+ files and SolidCraft assemblies (their linked designs) +through their structure, see [Formats](../reference/formats.md)) and matched against the vault: referenced files that are *not in TeamCraft* are flagged and the missing BOM lines are suggested. The other direction warns before damage: diff --git a/docs/src/reference/formats.md b/docs/src/reference/formats.md index 5dd00648..5ec4a074 100755 --- a/docs/src/reference/formats.md +++ b/docs/src/reference/formats.md @@ -219,7 +219,10 @@ to a `DOCUMENT_FILE` – through `APPLIED_DOCUMENT_REFERENCE`, their own occurrences) and Inventor assemblies (the occurrences of each referenced file from the file descriptor table in `UFRxDoc`, suppressed occurrences left out – a file with only suppressed ones counts 0, see -[the research note](../research/inventor-instance-counts.md)) +[the research note](../research/inventor-instance-counts.md)) and SolidCraft assemblies (the +placements – `occurrences` – of the components linked to each design through +`links`; a linked component without a placement counts once, see +[the research note](../research/solidcraft-design.md)) the scan also stores how often each referenced file is placed (`file_references.instances`, `instances` in `GET …/references`); the desktop folder import uses it as the BOM quantity, *Quantities from CAD…* @@ -228,7 +231,9 @@ store no count (`null`): their references are found by name only. The current versions of SOLIDWORKS, NX and referencing STEP files stored before this are read again once at the next start; for Inventor assemblies stored before run `teamcraft rescan-references --format inventor-assembly` once (*Quantities -from CAD…* reads the counts from the file and works without it). +from CAD…* reads the counts from the file and works without it). SolidCraft designs +stored before are scanned again with +`teamcraft rescan-references --format solidcraft-design`. `.prt` and `.asm` are told apart by content (Creo's `#UGC:` header, Solid Edge's OLE container); `.sc` must be a SolidCraft ZIP or JSON design. diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index 3598e322..8edc0ef7 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -8,7 +8,7 @@ program: | File | TeamCraft | |-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| -| SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs); the picture SolidCraft embeds (`cache/thumbnail.png`) is the preview image when its key still names this document | +| SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs); the picture SolidCraft embeds (`cache/thumbnail.png`) is the preview image when its key still names this document; an assembly's linked designs (`links`) are its file references, counted by their placements | | FieldCraft model `.fieldcraft` (ZIP: `fieldcraft.json`, `model.json`, `mesh.bin`, `journal.json`) | recognised as *FieldCraft analysis model* | | STEP, 3MF (incl. SolidCraft's face-tagged 3MF), STL, OBJ exports | 3D preview in the browser and the desktop app; STEP is searchable and scanned for references | | Abaqus input decks (`.inp`) written by FieldCraft | recognised as *Abaqus input file* | diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 08927dcc..4cd5def9 100755 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -76,6 +76,13 @@ test = false doc = false bench = false +[[bin]] +name = "scdesign" +path = "fuzz_targets/scdesign.rs" +test = false +doc = false +bench = false + [[bin]] name = "textindex" path = "fuzz_targets/textindex.rs" diff --git a/fuzz/fuzz_targets/scdesign.rs b/fuzz/fuzz_targets/scdesign.rs new file mode 100644 index 00000000..8a3d15ae --- /dev/null +++ b/fuzz/fuzz_targets/scdesign.rs @@ -0,0 +1,7 @@ +//! `cargo fuzz run scdesign` – see fuzz/README.md and `teamcraft::fuzz_harness::scdesign`. +#![no_main] + +use libfuzzer_sys::fuzz_target; +use teamcraft::fuzz_harness::{guarded, quiet_panics, scdesign}; + +fuzz_target!(init: quiet_panics(), |data: &[u8]| guarded(scdesign, data)); diff --git a/fuzz/seeds/scdesign/assembly.sc b/fuzz/seeds/scdesign/assembly.sc new file mode 100644 index 00000000..3eaa876c --- /dev/null +++ b/fuzz/seeds/scdesign/assembly.sc @@ -0,0 +1 @@ +{"format":"solidcraft/40","metadata":{"part_number":"TC-100","revision":"B","description":"Frame"},"components":[{"id":1,"name":"Plate","metadata":{"part_number":"TC-101","bom_type":"purchased"}},{"id":2,"name":"Bolt"}],"occurrences":[{"id":5,"component":1,"parent":0,"name":"Plate:1"},{"id":6,"component":1,"parent":0,"name":"Plate:2"},{"id":7,"component":2,"parent":0,"name":"Bolt:1"}],"links":{"1":{"path":"parts/plate.sc","feature":3},"2":{"path":"../lib/bolt.sc","feature":4}},"parts":{}} diff --git a/src/cadformat.rs b/src/cadformat.rs index ccaba3c3..7aaa10f0 100755 --- a/src/cadformat.rs +++ b/src/cadformat.rs @@ -597,7 +597,10 @@ pub fn detect(name: &str, head: &[u8]) -> Option<&'static CadFormat> { "pdf" => by_id("pdf"), // SolidCraft: a ZIP container or a JSON document; other .sc files // (scripts) are not CAD files. - "sc" if head.is_empty() || head.starts_with(b"PK\x03\x04") || is_solidcraft_json(head) => { + "sc" if head.is_empty() + || head.starts_with(b"PK\x03\x04") + || crate::scdesign::is_json_design(head) => + { by_id("solidcraft-design") } "sc" => None, @@ -792,13 +795,6 @@ fn is_netcdf_or_hdf5(head: &[u8]) -> bool { || head.starts_with(b"\x89HDF\r\n\x1a\n") } -/// JSON design of SolidCraft (`"format": "solidcraft/N"`). -fn is_solidcraft_json(head: &[u8]) -> bool { - let text = String::from_utf8_lossy(head); - text.trim_start().starts_with('{') - && (text.contains("\"solidcraft/") || text.contains("\"solvecraft/")) -} - /// Whether a PDF embeds a 3D model: the 3D stream dictionaries (`/Subtype /// /U3D` or `/PRC`) are never compressed, so a byte search finds them. async fn pdf_has_3d(path: &std::path::Path) -> bool { diff --git a/src/cadrefs.rs b/src/cadrefs.rs index 8caf81be..1e098be9 100755 --- a/src/cadrefs.rs +++ b/src/cadrefs.rs @@ -17,9 +17,11 @@ //! (`nxpart`: only the reference streams) and SOLIDWORKS 2015+ files //! (`swpart`: the component tree of an assembly, otherwise the document //! manager's section – both inflated from their compressed sections). The -//! rest of such a file (history, old names) is never scanned. +//! rest of such a file (history, old names) is never scanned. SolidCraft +//! designs (`scdesign`) list the designs their assembly links, read from +//! the document; nothing else in them is scanned. //! -//! For those two – and for STEP assemblies with external references – the +//! For those three – and for STEP assemblies with external references – the //! scan also tells how often an assembly places each component //! ([`instance_counts`], stored as `file_references.instances`); every //! other format gives names only. @@ -534,6 +536,8 @@ fn count_key(name: &str) -> String { /// * Inventor assemblies: the occurrences of each referenced file from the /// file descriptor table without the suppressed ones /// (`invasm::file_occurrence_counts`; only suppressed ones count 0). +/// * SolidCraft assemblies: the placements of the components linked to each +/// design (`scdesign::linked_designs`). /// /// `None` for every other format and for files without component data. /// Blocking (reads the file). @@ -571,6 +575,14 @@ pub fn instance_counts(path: &Path, format: &str) -> Option *total = total.saturating_add(n); } } + "solidcraft-design" => { + let mut file = std::io::BufReader::new(std::fs::File::open(path).ok()?); + let document = crate::scdesign::document(&mut file)?; + for (name, n) in crate::scdesign::linked_designs(&document)? { + let total = counts.entry(count_key(&name)).or_default(); + *total = total.saturating_add(n); + } + } "inventor-assembly" => { let file = std::io::BufReader::new(std::fs::File::open(path).ok()?); let found = crate::invasm::file_occurrence_counts(file, MAX_SCAN).ok()??; @@ -631,6 +643,12 @@ fn names_in_file(path: &Path, own: &str) -> std::io::Result> { if let Some(data) = crate::swpart::reference_data(&mut file, MAX_SCAN)? { return Ok(from_sw_sections(data, own)); } + if let Some(document) = crate::scdesign::document(&mut file) { + let names = crate::scdesign::linked_designs(&document) + .map(|links| links.into_keys().collect()) + .unwrap_or_default(); + return Ok(finish(names, own)); + } let mut content = Vec::new(); file.seek(std::io::SeekFrom::Start(0))?; file.take(MAX_SCAN).read_to_end(&mut content)?; @@ -1017,6 +1035,34 @@ mod tests { ); } + #[tokio::test] + async fn solidcraft_assemblies_list_their_linked_designs_with_counts() { + let document = br#"{"format":"solidcraft/40", + "occurrences":[{"id":5,"component":1,"name":"a"},{"id":6,"component":1,"name":"b"}, + {"id":7,"component":2,"name":"c"}], + "links":{"1":{"path":"parts/Plate.sc","feature":3}, + "2":{"path":"frame.sc","feature":4}, + "9":{"path":"","feature":5}}, + "notes":"mentions old_bracket.step in a text"}"#; + // frame.sc is the scanned file itself, never its own reference; the + // text field is not scanned. + let expected = vec![FileRef { + name: "Plate.sc".into(), + instances: Some(2), + }]; + for (encoding, bytes) in [ + ("json", document.to_vec()), + ("zip", crate::scdesign::sample::design(document, None)), + ] { + let path = + std::env::temp_dir().join(format!("teamcraft-sc-{}.sc", uuid::Uuid::new_v4())); + std::fs::write(&path, &bytes).unwrap(); + let found = scan_file(&path, "frame.sc", "solidcraft-design").await; + std::fs::remove_file(&path).ok(); + assert_eq!(found, expected, "{encoding}"); + } + } + #[tokio::test] async fn scan_file_reads_stored_files() { let path = std::env::temp_dir().join(format!("teamcraft-cadrefs-{}", uuid::Uuid::new_v4())); diff --git a/src/fuzz_harness.rs b/src/fuzz_harness.rs index 41f4af64..e2dbd19e 100755 --- a/src/fuzz_harness.rs +++ b/src/fuzz_harness.rs @@ -113,6 +113,18 @@ pub fn thumbnail(data: &[u8]) { let _ = crate::thumbnail::extract_from(Cursor::new(data)); } +/// SolidCraft designs: the document of a ZIP or JSON design, its linked +/// designs, and the embedded thumbnail. +pub fn scdesign(data: &[u8]) { + let _ = crate::scdesign::linked_designs(data); + if let Some(document) = crate::scdesign::document(&mut Cursor::new(data)) { + let _ = crate::scdesign::linked_designs(&document); + } + if let Some(mut design) = crate::scdesign::Container::open(Cursor::new(data)) { + let _ = design.thumbnail(); + } +} + /// Text extraction for the full-text search. pub fn textindex(data: &[u8]) { for name in TEXT_NAMES { @@ -254,6 +266,7 @@ pub const TARGETS: &[Target] = &[ ("cadrefs", cadrefs), ("bomtable", bomtable), ("thumbnail", thumbnail), + ("scdesign", scdesign), ("textindex", textindex), ("htmltext", htmltext), ("mesh", mesh), diff --git a/src/scdesign.rs b/src/scdesign.rs index e483c905..22bae7c8 100644 --- a/src/scdesign.rs +++ b/src/scdesign.rs @@ -16,6 +16,7 @@ clippy::unreachable )] +use std::collections::{BTreeMap, HashMap}; use std::io::{Read, Seek}; use sha2::{Digest, Sha256}; @@ -112,6 +113,92 @@ fn same_digest(hex_digest: &str, data: &[u8]) -> bool { hex_digest.eq_ignore_ascii_case(&hex::encode(Sha256::digest(data))) } +/// Whether `head` (the first bytes of a file) starts a plain-JSON design +/// (`"format": "solidcraft/N"`, early drafts `solvecraft/N`). +pub fn is_json_design(head: &[u8]) -> bool { + let text = String::from_utf8_lossy(head); + text.trim_start().starts_with('{') + && (text.contains("\"solidcraft/") || text.contains("\"solvecraft/")) +} + +/// The parametric document of a design file: `document.json` of a ZIP +/// design container, or the whole file when it is a plain-JSON design. +/// `None` for any other file and for a document larger than +/// [`MAX_DOCUMENT`]. Reads from the start of `file`. +pub fn document(file: &mut R) -> Option> { + file.rewind().ok()?; + let mut head = Vec::new(); + file.by_ref().take(1024).read_to_end(&mut head).ok()?; + file.rewind().ok()?; + if is_zip(&head) { + return Container::open(&mut *file)?.read("document.json", MAX_DOCUMENT); + } + if !is_json_design(&head) { + return None; + } + let mut data = Vec::new(); + file.by_ref() + .take(MAX_DOCUMENT.saturating_add(1)) + .read_to_end(&mut data) + .ok()?; + (data.len() as u64 <= MAX_DOCUMENT).then_some(data) +} + +/// Longest file name taken from a link (as `cadrefs` accepts). +const MAX_NAME: usize = 160; + +/// The designs an assembly links (*Insert Design*, `links` of the +/// document): the file name each link's path ends in, with how often the +/// components linked to it are placed – each placement is an occurrence; a +/// component without one counts once. Several links to one file add up. +/// Standard parts (`parts`) are no files and are not listed. `None` when +/// `document` is not a readable document. +pub fn linked_designs(document: &[u8]) -> Option> { + #[derive(serde::Deserialize)] + struct Doc { + #[serde(default)] + links: HashMap, + #[serde(default)] + occurrences: Vec, + } + #[derive(serde::Deserialize)] + struct Link { + #[serde(default)] + path: String, + } + #[derive(serde::Deserialize)] + struct Occurrence { + #[serde(default)] + component: Option, + } + let doc: Doc = serde_json::from_slice(document).ok()?; + let mut placed: HashMap = HashMap::new(); + for component in doc.occurrences.iter().filter_map(|o| o.component) { + let n = placed.entry(component).or_default(); + *n = n.saturating_add(1); + } + let mut found: BTreeMap = BTreeMap::new(); + for (id, link) in &doc.links { + let Some(name) = link + .path + .rsplit(['/', '\\']) + .next() + .map(str::trim) + .filter(|n| !n.is_empty() && n.len() <= MAX_NAME) + else { + continue; + }; + let count = id + .parse::() + .ok() + .and_then(|id| placed.get(&id).copied()) + .unwrap_or(1); + let total = found.entry(name.to_string()).or_default(); + *total = total.saturating_add(count); + } + Some(found) +} + /// Builders for small design containers, for the tests and the fuzz corpus. #[doc(hidden)] pub mod sample { @@ -259,4 +346,59 @@ mod tests { ]); assert_eq!(thumbnail(bytes), None); } + + /// An assembly linking `plate.sc` (placed three times) and `bolt.sc` + /// through two components (one placed twice, one without placement), + /// and a standard part, which is no file. + const ASSEMBLY: &str = r#"{ + "format": "solidcraft/40", + "components": [{"id": 1, "name": "Plate"}, {"id": 2, "name": "Bolt"}, + {"id": 3, "name": "Bolt long"}, {"id": 4, "name": "Nut"}], + "occurrences": [ + {"id": 10, "component": 1, "name": "Plate:1"}, + {"id": 11, "component": 1, "name": "Plate:2"}, + {"id": 12, "component": 1, "name": "Plate:3"}, + {"id": 13, "component": 2, "name": "Bolt:1"}, + {"id": 14, "component": 2, "name": "Bolt:2"}, + {"id": 15, "component": 4, "name": "Nut:1"} + ], + "links": { + "1": {"path": "plate.sc", "feature": 7}, + "2": {"path": "../lib/bolt.sc", "feature": 8, "configuration": 3}, + "3": {"path": "C:\\parts\\lib\\bolt.sc", "feature": 9} + }, + "parts": {"4": {"standard": "iso4032", "size": "M5"}}, + "unknown_future_field": [1, 2, 3] + }"#; + + #[test] + fn linked_designs_are_counted_by_placement() { + let links = linked_designs(ASSEMBLY.as_bytes()).unwrap(); + assert_eq!( + links.into_iter().collect::>(), + vec![("bolt.sc".to_string(), 3), ("plate.sc".to_string(), 3)] + ); + assert_eq!( + linked_designs(DOC), + Some(BTreeMap::new()), + "a part links nothing" + ); + assert_eq!(linked_designs(br#"{"links": 5}"#), None); + assert_eq!(linked_designs(b"not json"), None); + } + + #[test] + fn the_document_comes_from_either_encoding() { + let json = ASSEMBLY.as_bytes().to_vec(); + assert_eq!(document(&mut Cursor::new(json.clone())), Some(json.clone())); + let zipped = sample::design(&json, None); + assert_eq!(document(&mut Cursor::new(zipped)), Some(json)); + let other = br#"{"format":"other/1"}"#.to_vec(); + assert_eq!(document(&mut Cursor::new(other)), None); + assert_eq!( + document(&mut Cursor::new(sample::zip(&[("a.txt", b"x")]))), + None + ); + assert_eq!(document(&mut Cursor::new(Vec::new())), None); + } } From 798fa14a9da142ad105b39183259e9d706f74817 Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:23:52 +0100 Subject: [PATCH 04/10] Desktop: show SolidCraft designs that are open in SolidCraft (#370) desktop/src/cadlock.rs reads SolidCraft's .~.lock beside a design (regular file only, at most 4 KiB, stale after 180 s either way) into LocalFile.open_in (program, computer, user, since). The Workspace tab marks such files 'Open in SolidCraft', the check-in dialog warns that unsaved changes there are not checked in. Tests for fresh, stale, future, malformed, oversized locks, other formats, and that lock and backup files are never uploaded. Docs: desktop/README.md, guide/desktop.md, reference/interop.md, CHANGELOG, OPEN_WORK. Closes #370 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + desktop/README.md | 3 +- desktop/src/cadlock.rs | 174 ++++++++++++++++++++++++++++++++++ desktop/src/main.rs | 1 + desktop/src/workspace.rs | 4 + desktop/ui/js/workspace.js | 14 +++ docs/OPEN_WORK.md | 2 +- docs/src/guide/desktop.md | 7 ++ docs/src/reference/interop.md | 1 + 9 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 desktop/src/cadlock.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a9bafd47..2fce8977 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,10 @@ see the notices in the README. read from the ZIP or JSON document, unknown fields ignored. New fuzz target `scdesign`. Run `teamcraft rescan-references --format solidcraft-design` once for designs stored before. +- **Desktop: designs open in SolidCraft** (#370). The Workspace tab marks a + SolidCraft design that SolidCraft has open (its `.~.lock`, stale + locks ignored) with the computer and user, and the check-in dialog warns + that unsaved changes there are not checked in. ## [0.2.11] - 2026-11-21 diff --git a/desktop/README.md b/desktop/README.md index 4ba183ec..4c45a43a 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -27,7 +27,7 @@ TeamCraft server – it is a client, not an offline copy. | Tab order | Drag a tab to move it (pointer events, an insertion bar shows the landing place, the strip scrolls at its edges, `Esc` cancels; a plain click still activates, a dragged tab keeps its state and is not activated). Keyboard: arrow keys, `Home`, `End` move the focus between the tabs (WAI-ARIA tabs, roving tabindex, `Enter`/`Space` activates), `Ctrl+Shift+PageUp/PageDown` move the active tab. Right click (or the menu key): *Move to start*, *Move to end*, *Close*, *Close others*, *Close tabs to the right*. The order is kept while the app runs (open tabs are not restored on start). Rules in `ui/js/tab-order.js`, tested by `scripts/desktop-tab-order.test.mjs` (`node`); the dragging itself is checked by hand | | Revision tabs | Overview (with *At a glance*: the preview image from the CAD file, files, BOM lines, where used, references, change orders, open requests – and a link to the similar parts in the browser), Files (versions, restore, open), Structure (multi-level BOM, revision rules, roll-up), Where used, References, **Graph** (see below), Changes, History, **3D viewer** (STEP, meshes, point clouds – converted by the server), Workspace | | Graph | A navigable reference/BOM graph around the revision: the focused item in the middle, its BOM children and references below, the assemblies that use it above. Node **colour** = lifecycle state, **size** and the ⚙ badge = the item's own BOM complexity, **×n in the top-left corner** = how many instances of that part or sub-assembly the assembly contains (summed over its BOM lines, ×1 included). Every node is clickable and takes the tab to that item – a sub-assembly shows its own graph, anything else its overview, the item in the middle its own overview – with a **back control that stays in the same place** (the left of the sub-tab row) and leads back the way you came, one step per click; `Ctrl`/`⌘`+click opens a node in a tab of its own. Mouse-wheel zooms on the cursor; drag to pan; the view fits itself while details load until you zoom or pan, a double-click on the background fits it again. More than 8 neighbours on one side are laid out in rows; above 48 only the first 48 are fetched for preview and complexity (one request each), the rest keep a basic card. Preview images and filenames on the nodes; pure SVG, no external engine | -| Working folder | One folder per project group that **mirrors the folder structure of the files** (`///`, the folder is stored with every file on the server), one copy of each file – the revision is metadata in `/.teamcraft/state.json` (item, revision, file id, version, SHA-256, checked out). Files you have not checked out are **read-only** on disk; *Check out* takes the lock and makes them writable; *Check in…* uploads the chosen files as new versions, releases the lock in one step and makes them read-only again (files above 32 MiB go first as chunked, resumable uploads, then join the same check-in transaction). The check-in dialog shows the progress, and **Cancel** stops the check-in until its last byte is sent – before the next STEP export, between two chunks (the upload sessions are discarded, `DELETE /uploads/{id}`) or half-way through the streamed request with the small files: nothing is stored, the revision stays checked out (`src/abortable.rs`). Every check-in names the version each file is based on, so the server refuses (409) to overwrite a version somebody else checked in meanwhile. The Workspace tab shows *up to date* / *modified* / *outdated* / *conflict* / *new* / *missing* / *name clash* per file (from the server's file status) with its path, read-only flag and the lock owner. Two items with the same folder and file name are reported, never overwritten. Lock and backup files of the CAD programs are skipped; Creo iterations count as one file. A tracked revision the server no longer shows (you left a restricted project group) is listed as *No longer accessible*: its local copies stay untouched and are never synced again – delete them yourself if you must In *Check in…*, a new part or assembly file next to a revision that has a model already is offered unticked, with *New item from this file* (#359) | +| Working folder | One folder per project group that **mirrors the folder structure of the files** (`///`, the folder is stored with every file on the server), one copy of each file – the revision is metadata in `/.teamcraft/state.json` (item, revision, file id, version, SHA-256, checked out). Files you have not checked out are **read-only** on disk; *Check out* takes the lock and makes them writable; *Check in…* uploads the chosen files as new versions, releases the lock in one step and makes them read-only again (files above 32 MiB go first as chunked, resumable uploads, then join the same check-in transaction). The check-in dialog shows the progress, and **Cancel** stops the check-in until its last byte is sent – before the next STEP export, between two chunks (the upload sessions are discarded, `DELETE /uploads/{id}`) or half-way through the streamed request with the small files: nothing is stored, the revision stays checked out (`src/abortable.rs`). Every check-in names the version each file is based on, so the server refuses (409) to overwrite a version somebody else checked in meanwhile. The Workspace tab shows *up to date* / *modified* / *outdated* / *conflict* / *new* / *missing* / *name clash* per file (from the server's file status) with its path, read-only flag and the lock owner. Two items with the same folder and file name are reported, never overwritten. Lock and backup files of the CAD programs are skipped; a SolidCraft design that is open in SolidCraft (a fresh `.~.lock` beside it, `src/cadlock.rs`) is marked *Open in SolidCraft* with the computer and user, and the check-in dialog warns that unsaved changes there are not checked in; Creo iterations count as one file. A tracked revision the server no longer shows (you left a restricted project group) is listed as *No longer accessible*: its local copies stay untouched and are never synced again – delete them yourself if you must In *Check in…*, a new part or assembly file next to a revision that has a model already is offered unticked, with *New item from this file* (#359) | | Get | *Get…* on a revision: the item with its BOM (revision rule *latest* or *released*) and the parts its CAD files reference, resolved by the server (`…/workset`); only missing and outdated files are downloaded (SHA-256, checked after the download), recorded one by one so an interrupted Get continues where it stopped – also inside a large file: the bytes received stay in `..teamcraft-download` and the next Get asks only for the rest (`Range` / `If-Range`, `src/resume.rs`), checks the SHA-256 of the whole file and renames it into place; progress and *Cancel* in the status bar. No browser downloads | | Add files | *Add files…* (Files section and *More ▾*): file picker → the files are **copied** into the working folder of the revision (checked out first if needed; sub-folder selectable, originals untouched) and listed as *new* in *Check in…* (option *Check in now*; remembered in `.teamcraft/added.json` until checked in). A name that exists is a new version and asks first. The Files section says why it is unavailable (locked by someone else, in review, released = frozen → Revise). Pure logic and tests in `src/addfiles.rs`; drag and drop onto the window is not supported (`dragDropEnabled` is off) | | Old workspaces | Folders of the older layout `///` (and `//`) are found after the sign-in; the app offers to move the files into the new layout – never overwriting a file, keeping files whose place is taken and listing them, writing every step to `.teamcraft/migration.log` | @@ -181,6 +181,7 @@ src/resume.rs Get resumes a large file half-way: partial file per content, src/workspace.rs Get, status, read-only handling, check-in, migration of the old layout src/settings.rs settings.json (incl. the configured agents), the token in the OS keychain (file fallback), http:// check src/update.rs update notice: latest GitHub release at most daily, version comparison +src/cadlock.rs files a CAD program has open, from its lock files (SolidCraft `.~.lock`; stale locks ignored) src/crash.rs crash reports: panic hook, session markers (unexpected exits), UI errors – redacted, kept locally until the user shares them src/acp.rs Agent Client Protocol client: agent subprocess, JSON-RPC over stdio, session, permissions, workspace-only reads src/autoallow.rs (pure) which permission requests are allowed without a prompt: read-only TeamCraft MCP tools only, fail closed diff --git a/desktop/src/cadlock.rs b/desktop/src/cadlock.rs new file mode 100644 index 00000000..3c062c3d --- /dev/null +++ b/desktop/src/cadlock.rs @@ -0,0 +1,174 @@ +//! Which local files a CAD program has open, from the lock files the +//! program keeps next to them – shown in the Workspace tab and as a warning +//! at check-in (the file may have unsaved changes). +//! +//! SolidCraft (`.sc`, `.solidcraft`): while its desktop app has a design +//! open it keeps `.~.lock` beside it, a JSON object with the +//! computer (`host`), the `user`, the app version, the process and when the +//! design was opened and the lock last `refreshed` (Unix seconds). It is +//! refreshed every 60 s and removed on close; a lock not refreshed for +//! 180 s – or dated that far ahead – belongs to an app that is gone and is +//! ignored. Only a regular file of at most 4 KiB is read; a link or anything +//! else at that place is no lock. Sources: `docs/src/research/solidcraft-design.md`. +//! These lock files are never uploaded (`layout::is_ignored`: hidden names). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::Serialize; + +/// SolidCraft refreshes its lock every 60 s; three missed refreshes = stale. +const STALE_SECS: u64 = 180; +/// A real lock is a few hundred bytes. +const MAX_LOCK_BYTES: u64 = 4096; + +/// A CAD program that has a local file open. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct OpenIn { + /// The program, as shown (`SolidCraft`). + pub program: &'static str, + /// The computer it runs on. + pub computer: String, + /// The user it runs as (may be empty). + pub user: String, + /// When the file was opened (Unix seconds). + pub since: u64, +} + +/// The program that has `path` open now, if its lock file says so. +pub fn open_in(path: &Path) -> Option { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + open_in_at(path, now) +} + +fn open_in_at(path: &Path, now: u64) -> Option { + let ext = path.extension()?.to_string_lossy().to_ascii_lowercase(); + if ext != "sc" && ext != "solidcraft" { + return None; + } + let lock = read_lock(&solidcraft_lock_path(path)?)?; + #[derive(serde::Deserialize)] + struct Lock { + #[serde(default)] + host: String, + #[serde(default)] + user: String, + #[serde(default)] + opened: u64, + refreshed: u64, + } + let lock: Lock = serde_json::from_slice(&lock).ok()?; + let stale = now.saturating_sub(lock.refreshed) > STALE_SECS + || lock.refreshed.saturating_sub(now) > STALE_SECS; + if stale { + return None; + } + let computer = lock.host.trim(); + Some(OpenIn { + program: "SolidCraft", + computer: if computer.is_empty() { + "another computer".into() + } else { + computer.into() + }, + user: lock.user.trim().to_string(), + since: lock.opened, + }) +} + +/// `.~.lock` in the design's folder. +fn solidcraft_lock_path(path: &Path) -> Option { + let name = path.file_name()?.to_string_lossy(); + Some(path.with_file_name(format!(".~{name}.lock"))) +} + +/// The lock's bytes: only a regular file (links are not followed) of at +/// most [`MAX_LOCK_BYTES`]. +fn read_lock(path: &Path) -> Option> { + let meta = std::fs::symlink_metadata(path).ok()?; + if !meta.is_file() || meta.len() > MAX_LOCK_BYTES { + return None; + } + let mut data = Vec::new(); + std::fs::File::open(path) + .ok()? + .take(MAX_LOCK_BYTES + 1) + .read_to_end(&mut data) + .ok()?; + (data.len() as u64 <= MAX_LOCK_BYTES).then_some(data) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir() -> tempfile::TempDir { + tempfile::tempdir().unwrap() + } + + const NOW: u64 = 1_800_000_000; + + fn lock(refreshed: u64) -> String { + format!( + r#"{{"host":"WS-12","user":"kim","app":"0.46.1","pid":4242,"opened":{},"refreshed":{refreshed}}}"#, + NOW - 600 + ) + } + + #[test] + fn a_fresh_lock_names_computer_and_user() { + let d = dir(); + let design = d.path().join("Bracket.sc"); + std::fs::write(&design, b"{}").unwrap(); + assert_eq!(open_in_at(&design, NOW), None, "no lock"); + std::fs::write(d.path().join(".~Bracket.sc.lock"), lock(NOW - 30)).unwrap(); + assert_eq!( + open_in_at(&design, NOW), + Some(OpenIn { + program: "SolidCraft", + computer: "WS-12".into(), + user: "kim".into(), + since: NOW - 600, + }) + ); + assert!( + crate::layout::is_ignored(".~Bracket.sc.lock"), + "never uploaded" + ); + assert!( + crate::layout::is_ignored("Bracket.sc.bak"), + "backup never uploaded" + ); + } + + #[test] + fn stale_future_malformed_and_oversized_locks_are_ignored() { + let d = dir(); + let design = d.path().join("plate.solidcraft"); + let lock_file = d.path().join(".~plate.solidcraft.lock"); + for (content, why) in [ + (lock(NOW - 181), "stale"), + (lock(NOW + 181), "dated far ahead"), + ("not json".to_string(), "malformed"), + (r#"{"host":"x"}"#.to_string(), "no refresh time"), + (" ".repeat(MAX_LOCK_BYTES as usize + 1), "oversized"), + ] { + std::fs::write(&lock_file, content).unwrap(); + assert_eq!(open_in_at(&design, NOW), None, "{why}"); + } + std::fs::write(&lock_file, lock(NOW)).unwrap(); + assert!(open_in_at(&design, NOW).is_some()); + } + + #[test] + fn only_solidcraft_designs_are_checked() { + let d = dir(); + std::fs::write(d.path().join(".~bracket.ipt.lock"), lock(NOW)).unwrap(); + assert_eq!(open_in_at(&d.path().join("bracket.ipt"), NOW), None); + assert_eq!(open_in_at(&d.path().join("noext"), NOW), None); + } +} diff --git a/desktop/src/main.rs b/desktop/src/main.rs index b40e1ac1..6e44e054 100755 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -13,6 +13,7 @@ mod api; mod autoallow; mod bomimport; mod cadexport; +mod cadlock; mod cadlaunch; mod commands; mod compat; diff --git a/desktop/src/workspace.rs b/desktop/src/workspace.rs index c78a77eb..8329d65c 100755 --- a/desktop/src/workspace.rs +++ b/desktop/src/workspace.rs @@ -709,6 +709,8 @@ pub struct LocalFile { pub read_only: bool, /// The file at this place belongs to another item. pub clash_with: Option, + /// A CAD program has the file open now (its lock file, `cadlock`). + pub open_in: Option, } #[derive(Clone, Debug, Serialize)] @@ -826,6 +828,7 @@ pub fn inaccessible_status(root: &Path, project: Option<&str>, item: &str, code: base_version: Some(e.version), read_only: is_read_only(&path), clash_with: None, + open_in: None, } }) .collect(); @@ -979,6 +982,7 @@ pub async fn status( name: f.name, local_name, path: f.rel, + open_in: f.path.as_deref().and_then(crate::cadlock::open_in), state: state_name.to_string(), clash_with: f.clash_with, }); diff --git a/desktop/ui/js/workspace.js b/desktop/ui/js/workspace.js index e61803ea..0f79a6d6 100755 --- a/desktop/ui/js/workspace.js +++ b/desktop/ui/js/workspace.js @@ -141,6 +141,11 @@ export function revWorkspace(tab, el) { var stateBadge = badge(f.state, SYNC_LABEL[f.state] || label(f.state)); if (f.state === "clash") stateBadge.title = "Another file is at this place: " + f.clash_with + " – it is never overwritten."; if (lockedByOther && f.state !== "missing") stateBadge = h("span", null, [stateBadge, " ", badge("lock", "Locked by " + rev.checked_out_by_name)]); + if (f.open_in) { + var openBadge = badge("pending", "Open in " + f.open_in.program); + openBadge.title = openInText(f) + " – save there before checking in."; + stateBadge = h("span", null, [stateBadge, " ", openBadge]); + } return { cls: f.state === "conflict" ? "row-conflict" : f.state === "clash" ? "row-clash" : null, cells: [h("span", null, [ @@ -426,6 +431,12 @@ export function doCancelCheckout(tab) { /** Follows the check-in upload of the open check-in dialog (`upload-progress`). */ export var uploadWatcher = null; +/** "bracket.sc is open in SolidCraft on WS-12 (kim)" – from the lock file the program keeps (cadlock.rs). */ +function openInText(f) { + var o = f.open_in; + return f.name + " is open in " + o.program + " on " + o.computer + (o.user ? " (" + o.user + ")" : ""); +} + /** "Check in…" (`park` false) or "Park…" (`park` true, issue #173 step 10): * the same dialog with both buttons; `park` only decides the default one. */ export function checkinDialog(tab, park) { @@ -463,6 +474,9 @@ export function checkinDialog(tab, park) { } } }, "New item from this file") ])]); })) : h("p.empty", { text: "No modified or new files – checking in only ends your check-out; the revision stays in work." }), + candidates.some(function (f) { return f.open_in; }) ? h("p.notice", { text: "Still open: " + + candidates.filter(function (f) { return f.open_in; }).map(openInText).join("; ") + + ". Unsaved changes there are not checked in – save first, or check in anyway." }) : null, boxes.some(function (b) { return b.state === "conflict"; }) ? h("p.notice.error", { text: "Conflict: these files changed on the server since you got them. " + "The server refuses to overwrite the newer version (nothing is stored) – save your copy under another name, get the current files and merge." }) : null, stepNote, diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index d2b1da37..e2bb27bc 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -704,7 +704,7 @@ real files and belong to section 3 once such files are at hand. - [ ] Design properties read, shown, searchable, mismatches with the item flagged (#367) - [ ] Desktop: STEP export through `solidcraft-cli` at check-in, all OSes (#368) - [ ] Desktop: item number and revision written into the design properties (#369) -- [ ] Desktop: designs open in SolidCraft (lock file) shown, warning at check-in (#370) +- [x] Desktop: designs open in SolidCraft (lock file) shown, warning at check-in (#370) - [ ] (research first) 3D preview from the `.sc` file alone (#371) ### 5. Feature demand (backlog) diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index 189d3967..99c4405d 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -491,6 +491,13 @@ the folder import and the working folder use composed names on every system, and a file an older app version wrote under a decomposed name is renamed at the next Get or when the Workspace tab looks at it. +**Files open in SolidCraft.** While SolidCraft has a design of the working +folder open, the Workspace tab marks it *Open in SolidCraft* and names the +computer and user (from the lock file SolidCraft keeps next to the design; +locks not refreshed for three minutes are ignored). The check-in dialog warns +about such files: changes not saved in SolidCraft are not checked in. You can +check in anyway. + **Read-only rule.** Files you have **not** checked out are read-only on disk (the read-only attribute on Windows, no write permission on Linux and macOS). CAD programs then open them read-only, and nobody edits a file that cannot be diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index 8edc0ef7..bd5112a8 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -9,6 +9,7 @@ program: | File | TeamCraft | |-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| | SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs); the picture SolidCraft embeds (`cache/thumbnail.png`) is the preview image when its key still names this document; an assembly's linked designs (`links`) are its file references, counted by their placements | +| SolidCraft lock file `.~.lock` (JSON: computer, user, refresh time) | never uploaded; the desktop app shows a design that is open in SolidCraft and warns at check-in | | FieldCraft model `.fieldcraft` (ZIP: `fieldcraft.json`, `model.json`, `mesh.bin`, `journal.json`) | recognised as *FieldCraft analysis model* | | STEP, 3MF (incl. SolidCraft's face-tagged 3MF), STL, OBJ exports | 3D preview in the browser and the desktop app; STEP is searchable and scanned for references | | Abaqus input decks (`.inp`) written by FieldCraft | recognised as *Abaqus input file* | From d1bbba626db82f8429aed6745ee6536692035215 Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:28:59 +0100 Subject: [PATCH 05/10] Desktop: STEP export of SolidCraft designs via solidcraft-cli on every system (#368) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cadexport gains CadProgram::SolidCraft: .sc/.solidcraft files that are designs (ZIP container or JSON solidcraft/N, not scripts) are exported with 'solidcraft-cli run --in --out .stp', found through SOLIDCRAFT_CLI, PATH or SolidCraft's install folders (Windows, macOS app bundle, Linux packages, ~/.local/bin, snap), run without a shell or window under the same 15-minute limit; the wait loop is shared with the PowerShell exports. available() lists it on every system. Check-in: a failed or impossible STEP export (any program) no longer stops the check-in – the file goes without its STEP and the result says why (lessons from #342). Docs: desktop/README.md, guide/desktop.md, guide/files.md, reference/interop.md, README, CHANGELOG, OPEN_WORK. Closes #368 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + README.md | 2 +- desktop/README.md | 2 +- desktop/src/cadexport.rs | 314 ++++++++++++++++++++++++++++------ desktop/ui/js/revision.js | 5 +- desktop/ui/js/workspace.js | 12 +- docs/OPEN_WORK.md | 2 +- docs/src/guide/desktop.md | 6 + docs/src/guide/files.md | 2 + docs/src/reference/interop.md | 1 + 10 files changed, 292 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fce8977..337018ae 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,12 @@ see the notices in the README. SolidCraft design that SolidCraft has open (its `.~.lock`, stale locks ignored) with the computer and user, and the check-in dialog warns that unsaved changes there are not checked in. +- **Desktop: STEP export of SolidCraft designs** (#368). *STEP* in the + Workspace tab and *Create STEP exports … first* at check-in export `.sc` + designs through SolidCraft's `solidcraft-cli` on Windows, macOS and Linux + (`SOLIDCRAFT_CLI`, `PATH` or the default install folders). A failed export + – any program – no longer stops the check-in: the file is checked in + without its STEP and the result says why. ## [0.2.11] - 2026-11-21 diff --git a/README.md b/README.md index 567efae9..7365b011 100755 --- a/README.md +++ b/README.md @@ -322,7 +322,7 @@ end-to-end tests against a real PostgreSQL. - **SolidCraft and FieldCraft** – [SolidCraft](https://github.com/tangency-labs/solidcraft) designs (`.sc`, checked by content) and [FieldCraft](https://github.com/tangency-labs/fieldcraft) models (`.fieldcraft`) are recognised, SolidCraft's embedded picture is the preview image, linked designs are - file references with quantities, and their STEP and 3MF + file references with quantities, the desktop app exports designs to STEP with `solidcraft-cli`, and their STEP and 3MF exports previewed – design, export and analysis in one revision ([more](https://warr-ev.github.io/TeamCraft/reference/interop.html)). diff --git a/desktop/README.md b/desktop/README.md index 4c45a43a..895335f6 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -33,7 +33,7 @@ TeamCraft server – it is a client, not an offline copy. | Old workspaces | Folders of the older layout `///` (and `//`) are found after the sign-in; the app offers to move the files into the new layout – never overwriting a file, keeping files whose place is taken and listing them, writing every step to `.teamcraft/migration.log` | | Check in all | *Check in all* in the worklist (navigator and home page): the check-outs with local changes (modified, new, conflicting files) are listed first, with the offer to check them in with their files; then every check-out without local changes is checked in on the server (lock released, one revision at a time); check-outs with a conflict stay checked out. *Sign out* asks the same: *Check in and sign out*, *Park and sign out*, *Sign out anyway*. The list is the pure `layout::local_changes` | | Park | *Park…* (Workspace tab, *More ▾*, the check-in dialog): the ticked files go up as new versions through the upload endpoint (`POST …/files`) and the check-out **stays** – work in progress survives a lost laptop. After somebody else released your check-out, the Workspace tab shows *Released by X; your local changes are kept and need a new check-out* (`released` of the server's file status) | -| Native CAD previews | The preview image stored in Inventor and Solid Edge files in the Files tab, a picture of the 3D preview for NX and SOLIDWORKS files; on Windows *STEP* in the Workspace tab and *Create STEP exports … first* at check-in export with the installed Inventor or Solid Edge (COM automation through Windows PowerShell; uses your own licence) | +| Native CAD previews | The preview image stored in Inventor and Solid Edge files in the Files tab, a picture of the 3D preview for NX and SOLIDWORKS files; on Windows *STEP* in the Workspace tab and *Create STEP exports … first* at check-in export with the installed Inventor or Solid Edge (COM automation through Windows PowerShell; uses your own licence); on every system SolidCraft designs (`.sc`) export through SolidCraft's `solidcraft-cli run --in … --out ….stp` (found through `SOLIDCRAFT_CLI`, `PATH` or the default install folders). A failed export never stops the check-in: the file goes without its STEP and the result says why | | Check out and open | *Check out and open* on the revision toolbar (*Open in CAD* for one's own check-out) takes the lock, gets the files and opens the main CAD file; the chip next to it names the program (e.g. *Inventor 2026*). The program: the project group's default CAD program (`default_cad`, `default_cad_version` of `GET /api/v1/projects`) in its version, else its newest installed version; without a default, or for a file of another program, the newest installed version of the program that fits the file (`format_info.family`); else the system's default application. Installed programs are found by their install folders (Windows *Program Files*, SOLIDWORKS via `reg query`; macOS `/Applications`; FreeCAD on the Linux `PATH`), once per start – `src/cadlaunch.rs`, `ui/js/cad-open.js`; *Open* in the Files tab uses the same choice. On Windows an Inventor that already runs – the chosen installation, with the working folder's Inventor project active (the `.ipj` in the nearest folder up to the working folder root) – opens the file as a new window instead of a second instance (#350; asked through COM by a Windows PowerShell script: `GetActiveObject`, `InstallPath`, `ActiveDesignProject`, `Documents.Open`); otherwise a new instance starts and the message says why. After *Cancel* during the download, or with files that could not be copied, nothing is opened (#348, `ui/js/get-rules.js`). *Import CAD folder* detects the folder's program (Inventor with the release year read from the files, `folderimport::inventor_year`) and offers to set it as the group's default | | Preferred CAD program | The account setting of the web UI (`preferred_cad` of `GET /api/v1/me`, read at sign-in): when a revision has files of that program, the Files tab lists the native files of other CAD programs (`format_info.family`) in a collapsed *N files in other CAD formats (…)* group; neutral files (STEP, JT, STL, PDF, …) stay visible. Grouped in `ui/js/revision.js` (`groupByFamily`) with the same rule as the server's `cadformat::group_by_family`; display only | | Whole project groups locally | the download icon in the navigator (*Tools → Get Project Groups…*): copies the files of every item of the chosen groups – latest revision (also in work, the default since #355) or latest released – into the working folder with their folder structure; unchanged files are skipped, locally modified files kept, name clashes reported. For new team members or a fresh computer | diff --git a/desktop/src/cadexport.rs b/desktop/src/cadexport.rs index 4c983178..02e0d0c1 100755 --- a/desktop/src/cadexport.rs +++ b/desktop/src/cadexport.rs @@ -10,16 +10,22 @@ //! included, within their terms) does the export. A document the user already //! has open is exported as it is and left open. Not tested against real //! Inventor or Solid Edge installations in the development environment. +//! +//! SolidCraft designs (`.sc`, `.solidcraft`) on every system: SolidCraft's +//! headless `solidcraft-cli run --in --out .stp` writes the +//! export (found through `SOLIDCRAFT_CLI`, `PATH` or the default install +//! folders, [`solidcraft_cli`]). A design whose timeline has a failing +//! feature is not exported – SolidCraft writes nothing then and says why. use std::{ path::{Path, PathBuf}, + process::Child, time::Duration, }; use serde::Serialize; /// Longest time an export may take (large assemblies). -#[cfg_attr(not(windows), allow(dead_code))] pub const TIME_LIMIT: Duration = Duration::from_secs(15 * 60); #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] @@ -27,17 +33,21 @@ pub const TIME_LIMIT: Duration = Duration::from_secs(15 * 60); pub enum CadProgram { Inventor, SolidEdge, + #[serde(rename = "solidcraft")] + SolidCraft, } #[cfg_attr(not(windows), allow(dead_code))] impl CadProgram { - pub const ALL: [CadProgram; 2] = [CadProgram::Inventor, CadProgram::SolidEdge]; + /// The programs driven through COM on Windows. + pub const COM: [CadProgram; 2] = [CadProgram::Inventor, CadProgram::SolidEdge]; - /// COM class of the application. + /// COM class of the application (none for SolidCraft). pub fn prog_id(self) -> &'static str { match self { CadProgram::Inventor => "Inventor.Application", CadProgram::SolidEdge => "SolidEdge.Application", + CadProgram::SolidCraft => "", } } @@ -45,6 +55,7 @@ impl CadProgram { match self { CadProgram::Inventor => "Autodesk Inventor", CadProgram::SolidEdge => "Siemens Solid Edge", + CadProgram::SolidCraft => "SolidCraft", } } @@ -52,6 +63,7 @@ impl CadProgram { match self { CadProgram::Inventor => INVENTOR_SCRIPT, CadProgram::SolidEdge => SOLID_EDGE_SCRIPT, + CadProgram::SolidCraft => "", } } } @@ -67,6 +79,149 @@ fn is_ole(path: &Path) -> bool { && head == OLE_MAGIC } +/// A SolidCraft design rather than a script with the same extension: a ZIP +/// design container, or a JSON document with `"format": "solidcraft/N"`. +fn is_solidcraft_design(path: &Path) -> bool { + use std::io::Read; + let mut head = Vec::new(); + let read = std::fs::File::open(path).and_then(|f| f.take(1024).read_to_end(&mut head)); + if read.is_err() { + return false; + } + let text = String::from_utf8_lossy(&head); + head.starts_with(b"PK\x03\x04") + || (text.trim_start().starts_with('{') + && (text.contains("\"solidcraft/") || text.contains("\"solvecraft/"))) +} + +/// SolidCraft's command-line tool: `SOLIDCRAFT_CLI` (a path), else +/// `solidcraft-cli` on `PATH`, else the folders SolidCraft's installers use +/// (Windows `Program Files\SolidCraft`, the macOS app bundle, Linux +/// packages, `~/.local/bin` of the AppImage, the snap's `solidcraft.cli`). +pub fn solidcraft_cli() -> Option { + let env = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()); + let home = env("HOME") + .or_else(|| env("USERPROFILE")) + .map(PathBuf::from); + let candidates = cli_candidates( + env("SOLIDCRAFT_CLI").map(PathBuf::from), + env("PATH") + .map(|p| std::env::split_paths(&p).collect()) + .unwrap_or_default(), + home, + env("ProgramFiles").map(PathBuf::from), + env("LOCALAPPDATA").map(PathBuf::from), + ); + candidates.into_iter().find(|p| p.is_file()) +} + +/// Where to look for `solidcraft-cli`, in order (see [`solidcraft_cli`]). +fn cli_candidates( + explicit: Option, + path: Vec, + home: Option, + program_files: Option, + local_app_data: Option, +) -> Vec { + let exe = if cfg!(windows) { + "solidcraft-cli.exe" + } else { + "solidcraft-cli" + }; + let mut out: Vec = explicit.into_iter().collect(); + out.extend(path.into_iter().map(|d| d.join(exe))); + if cfg!(windows) { + let pf = program_files.unwrap_or_else(|| PathBuf::from(r"C:\Program Files")); + out.push(pf.join("SolidCraft").join(exe)); + if let Some(local) = local_app_data { + out.push(local.join("Programs").join("SolidCraft").join(exe)); + } + } else if cfg!(target_os = "macos") { + out.push(PathBuf::from("/Applications/SolidCraft.app/Contents/MacOS").join(exe)); + if let Some(h) = &home { + out.push( + h.join("Applications/SolidCraft.app/Contents/MacOS") + .join(exe), + ); + } + } else { + for dir in ["/usr/bin", "/usr/local/bin", "/opt/solidcraft"] { + out.push(PathBuf::from(dir).join(exe)); + } + if let Some(h) = &home { + out.push(h.join(".local/bin").join(exe)); + } + out.push(PathBuf::from("/snap/bin/solidcraft.cli")); + } + out +} + +/// Waits for an export process within [`TIME_LIMIT`]; the first non-empty +/// line of its error output says why it failed. +fn wait_for(mut child: Child, program: CadProgram) -> Result<(), String> { + // read the error output on the side, so a full pipe never blocks + let reader = child.stderr.take().map(|mut err| { + std::thread::spawn(move || { + use std::io::Read; + let mut text = String::new(); + let _ = err.read_to_string(&mut text); + text + }) + }); + let started = std::time::Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if started.elapsed() > TIME_LIMIT => { + let _ = child.kill(); + return Err(format!( + "{} did not finish the export within {} minutes.", + program.label(), + TIME_LIMIT.as_secs() / 60 + )); + } + Ok(None) => std::thread::sleep(Duration::from_millis(250)), + Err(e) => return Err(format!("Export failed: {e}")), + } + }; + if status.success() { + return Ok(()); + } + let stderr = reader.and_then(|r| r.join().ok()).unwrap_or_default(); + let reason = stderr + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or("no details"); + Err(format!( + "{} could not export the file: {reason}", + program.label() + )) +} + +/// `solidcraft-cli run --in --out ` – no shell, no window. +fn run_solidcraft(cli: &Path, input: &Path, output: &Path) -> Result<(), String> { + let mut command = std::process::Command::new(cli); + command + .arg("run") + .arg("--in") + .arg(input) + .arg("--out") + .arg(output) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + let child = command + .spawn() + .map_err(|e| format!("Cannot start {}: {e}", cli.display()))?; + wait_for(child, CadProgram::SolidCraft) +} + /// The program that exports a file: Inventor parts and assemblies, Solid /// Edge parts, sheet metal, weldments and assemblies (`.asm` only when it is /// an OLE file – Creo assemblies use the same extension). @@ -76,6 +231,7 @@ pub fn program_for(path: &Path) -> Option { "ipt" | "iam" => Some(CadProgram::Inventor), "par" | "psm" | "pwd" => Some(CadProgram::SolidEdge), "asm" if is_ole(path) => Some(CadProgram::SolidEdge), + "sc" | "solidcraft" if is_solidcraft_design(path) => Some(CadProgram::SolidCraft), _ => None, } } @@ -157,7 +313,7 @@ mod platform { } fn wait(program: CadProgram, script: &Path, input: &Path, output: &Path) -> Result<(), String> { - let mut child = Command::new("powershell.exe") + let child = Command::new("powershell.exe") .args([ "-NoProfile", "-NonInteractive", @@ -175,60 +331,23 @@ mod platform { .creation_flags(CREATE_NO_WINDOW) .spawn() .map_err(|e| format!("Cannot start Windows PowerShell: {e}"))?; - // read the error output on the side, so a full pipe never blocks - let reader = child.stderr.take().map(|mut err| { - std::thread::spawn(move || { - use std::io::Read; - let mut text = String::new(); - let _ = err.read_to_string(&mut text); - text - }) - }); - let started = std::time::Instant::now(); - let status = loop { - match child.try_wait() { - Ok(Some(status)) => break status, - Ok(None) if started.elapsed() > TIME_LIMIT => { - let _ = child.kill(); - return Err(format!( - "{} did not finish the export within {} minutes.", - program.label(), - TIME_LIMIT.as_secs() / 60 - )); - } - Ok(None) => std::thread::sleep(Duration::from_millis(250)), - Err(e) => return Err(format!("Export failed: {e}")), - } - }; - if status.success() { - return Ok(()); - } - let stderr = reader.and_then(|r| r.join().ok()).unwrap_or_default(); - let reason = stderr - .lines() - .map(str::trim) - .find(|l| !l.is_empty()) - .unwrap_or("no details"); - Err(format!( - "{} could not export the file: {reason}", - program.label() - )) + wait_for(child, program) } } /// The CAD programs installed on this computer that can export STEP. pub fn available() -> Vec { #[cfg(windows)] - { - CadProgram::ALL - .into_iter() - .filter(|p| platform::registered(*p)) - .collect() - } + let mut found: Vec = CadProgram::COM + .into_iter() + .filter(|p| platform::registered(*p)) + .collect(); #[cfg(not(windows))] - { - Vec::new() + let mut found: Vec = Vec::new(); + if solidcraft_cli().is_some() { + found.push(CadProgram::SolidCraft); } + found } /// Exports `input` to a STEP file next to it with the installed CAD program; @@ -236,11 +355,27 @@ pub fn available() -> Vec { pub fn export_step(input: &Path) -> Result { let program = program_for(input).ok_or_else(|| { format!( - "{} is not an Inventor or Solid Edge part or assembly.", + "{} is not an Inventor, Solid Edge or SolidCraft part or assembly.", input.display() ) })?; let output = step_path(input); + if program == CadProgram::SolidCraft { + let cli = solidcraft_cli().ok_or_else(|| { + "SolidCraft's command-line tool (solidcraft-cli) was not found – install SolidCraft \ + or set SOLIDCRAFT_CLI to its path." + .to_string() + })?; + run_solidcraft(&cli, input, &output)?; + return if output.is_file() { + Ok(output) + } else { + Err(format!( + "SolidCraft finished, but {} was not written.", + output.display() + )) + }; + } #[cfg(windows)] { platform::run(program, input, &output)?; @@ -307,8 +442,83 @@ mod tests { #[cfg(not(windows))] #[test] fn other_systems_explain_the_limit() { - assert!(available().is_empty()); + let found = available(); + assert!(!found.contains(&CadProgram::Inventor) && !found.contains(&CadProgram::SolidEdge)); let err = export_step(Path::new("/w/Bracket.ipt")).unwrap_err(); assert!(err.contains("Windows only"), "{err}"); } + + #[test] + fn solidcraft_designs_but_not_scripts() { + let dir = tempfile::tempdir().unwrap(); + let zip = dir.path().join("frame.sc"); + std::fs::write(&zip, b"PK\x03\x04rest").unwrap(); + let json = dir.path().join("plate.solidcraft"); + std::fs::write(&json, br#"{"format":"solidcraft/40","features":[]}"#).unwrap(); + let script = dir.path().join("build.sc"); + std::fs::write(&script, b"#!/bin/sh\necho hi\n").unwrap(); + assert_eq!(program_for(&zip), Some(CadProgram::SolidCraft)); + assert_eq!(program_for(&json), Some(CadProgram::SolidCraft)); + assert_eq!(program_for(&script), None, "a script named .sc"); + assert_eq!(program_for(&dir.path().join("missing.sc")), None); + } + + #[test] + fn the_cli_is_looked_for_in_order() { + let c = cli_candidates( + Some(PathBuf::from("/opt/x/solidcraft-cli")), + vec![PathBuf::from("/p1"), PathBuf::from("/p2")], + Some(PathBuf::from("/home/kim")), + None, + None, + ); + assert_eq!( + c[0], + PathBuf::from("/opt/x/solidcraft-cli"), + "SOLIDCRAFT_CLI first" + ); + assert!( + c[1].starts_with("/p1") && c[2].starts_with("/p2"), + "then PATH: {c:?}" + ); + assert!(c.len() > 3, "then the install folders"); + if cfg!(target_os = "linux") { + assert!(c.contains(&PathBuf::from("/home/kim/.local/bin/solidcraft-cli"))); + assert!(c.contains(&PathBuf::from("/snap/bin/solidcraft.cli"))); + } + } + + #[cfg(unix)] + #[test] + fn solidcraft_export_runs_the_cli_and_reports_its_error() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let fake = |name: &str, body: &str| { + let path = dir.path().join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + }; + // run --in IN --out OUT + let ok = fake( + "ok-cli", + r#"[ "$1" = run ] && [ "$2" = --in ] && [ "$4" = --out ] && echo step > "$5""#, + ); + let failing = fake( + "bad-cli", + "echo '1 timeline feature(s) failed, so nothing was written:' >&2; exit 1", + ); + let design = dir.path().join("plate.sc"); + std::fs::write(&design, b"PK\x03\x04").unwrap(); + let out = step_path(&design); + run_solidcraft(&ok, &design, &out).unwrap(); + assert_eq!(std::fs::read_to_string(&out).unwrap(), "step\n"); + let err = run_solidcraft(&failing, &design, &out).unwrap_err(); + assert!( + err.starts_with("SolidCraft could not export the file: 1 timeline feature"), + "{err}" + ); + let err = run_solidcraft(&dir.path().join("none"), &design, &out).unwrap_err(); + assert!(err.contains("Cannot start"), "{err}"); + } } diff --git a/desktop/ui/js/revision.js b/desktop/ui/js/revision.js index 7b61fd95..3719e1e3 100755 --- a/desktop/ui/js/revision.js +++ b/desktop/ui/js/revision.js @@ -427,13 +427,13 @@ export function thumbImage(f) { } export var cadProgramsPromise = null; -/** CAD programs on this computer that export STEP: "inventor", "solid-edge" (Windows). */ +/** CAD programs on this computer that export STEP: "inventor", "solid-edge" (Windows), "solidcraft" (solidcraft-cli, every system). */ export function cadPrograms() { if (!cadProgramsPromise) cadProgramsPromise = call("cad_programs").catch(function () { return []; }); return cadProgramsPromise; } -export var PROGRAM_LABEL = { "inventor": "Inventor", "solid-edge": "Solid Edge" }; +export var PROGRAM_LABEL = { "inventor": "Inventor", "solid-edge": "Solid Edge", "solidcraft": "SolidCraft" }; /** The local program that can export this file to STEP, or null. */ export function exportProgram(name, programs) { @@ -441,6 +441,7 @@ export function exportProgram(name, programs) { var ext = m ? m[1].toLowerCase() : ""; if ((ext === "ipt" || ext === "iam") && programs.indexOf("inventor") >= 0) return "inventor"; if (["par", "psm", "pwd", "asm"].indexOf(ext) >= 0 && programs.indexOf("solid-edge") >= 0) return "solid-edge"; + if ((ext === "sc" || ext === "solidcraft") && programs.indexOf("solidcraft") >= 0) return "solidcraft"; return null; } diff --git a/desktop/ui/js/workspace.js b/desktop/ui/js/workspace.js index 0f79a6d6..13dc2afc 100755 --- a/desktop/ui/js/workspace.js +++ b/desktop/ui/js/workspace.js @@ -512,12 +512,16 @@ export function checkinDialog(tab, park) { running = true; cancelled = false; opts.modal = true; var toExport = stepNote && withStep.checked ? files.filter(function (n) { return exportProgram(n, programs); }) : []; function show(text) { if (!cancelled) { progressLine.textContent = text; progressLine.classList.remove("hidden"); } } - // one export after the other: the CAD program handles one document at a time + // one export after the other: the CAD program handles one document at a + // time. A failed export never stops the check-in (#342, #368): the file + // goes without its STEP and the result says why. + var exportFailures = []; var exported = toExport.reduce(function (chain, name) { return chain.then(function () { if (cancelled) throw stopped(); show("Exporting " + name + " to STEP with " + PROGRAM_LABEL[exportProgram(name, programs)] + " …"); - return exportStep(rev, name).then(function (step) { if (files.indexOf(step) < 0) files.push(step); }); + return exportStep(rev, name).then(function (step) { if (files.indexOf(step) < 0) files.push(step); }, + function (e) { if (cancelled) throw stopped(); exportFailures.push(name + ": " + errorText(e)); }); }); }, Promise.resolve()); exported.then(function () { @@ -531,7 +535,9 @@ export function checkinDialog(tab, park) { d.close(); toast((parking ? "Parked " + files.join(", ") + " on the server – " + rev.item_number + "/" + rev.code + " stays checked out to you" : "Checked in " + rev.item_number + "/" + rev.code + (files.length ? " with " + files.join(", ") : "")) + - (cancelled ? " – the server already had every file when you cancelled" : ""), cancelled ? "info" : null); + (cancelled ? " – the server already had every file when you cancelled" : "") + + (exportFailures.length ? ". No STEP export for " + exportFailures.join("; ") : ""), + cancelled || exportFailures.length ? "info" : null); reloadActive(); refreshWorklistCount(); }, function (err) { diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index e2bb27bc..ab6dfb0e 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -702,7 +702,7 @@ real files and belong to section 3 once such files are at hand. - [x] Linked designs as file references with quantities (#365); left: rewriting link paths after a rename (with #369) - [ ] BOM import from SolidCraft's BOM CSV and from the design (#366) - [ ] Design properties read, shown, searchable, mismatches with the item flagged (#367) -- [ ] Desktop: STEP export through `solidcraft-cli` at check-in, all OSes (#368) +- [x] Desktop: STEP export through `solidcraft-cli` at check-in, all OSes (#368); left: a rendered thumbnail (`solidcraft-cli snapshot`) for designs saved without one - [ ] Desktop: item number and revision written into the design properties (#369) - [x] Desktop: designs open in SolidCraft (lock file) shown, warning at check-in (#370) - [ ] (research first) 3D preview from the `.sc` file alone (#371) diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index 99c4405d..0f74fb1a 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -184,6 +184,12 @@ check-outs and reviews, and a **local working folder**: * on Windows with Inventor or Solid Edge installed, *STEP* (workspace) and the check-in option (off by default) create STEP exports for the 3D preview with that program; the Files tab shows the preview image stored in native files. +* on every system with SolidCraft installed, the same *STEP* button and + check-in option export SolidCraft designs (`.sc`) through SolidCraft's + command-line tool `solidcraft-cli` (set `SOLIDCRAFT_CLI` to its path if it + is not found); a design with a failing feature is not exported. An export + that fails or is not possible never stops the check-in – the file is + checked in without its STEP and the result names the reason. * with a *Preferred CAD program* set on your account page in the web UI, the Files tab of a revision collapses the native files of other CAD programs (see [Files](files.md#preferred-cad-program)); the app reads the setting at diff --git a/docs/src/guide/files.md b/docs/src/guide/files.md index e27a310d..a1d0e265 100755 --- a/docs/src/guide/files.md +++ b/docs/src/guide/files.md @@ -212,6 +212,8 @@ For the rest TeamCraft shows what other PLM systems show: – the *STEP* button in the workspace or the option at check-in, like the CAD add-ins of other PDM systems. It uses your licence (student licences included, within their terms); TeamCraft contains no Autodesk or Siemens software. + SolidCraft designs are exported on every system through SolidCraft's own + command-line tool (`solidcraft-cli`), when SolidCraft is installed. ## Full-text search diff --git a/docs/src/reference/interop.md b/docs/src/reference/interop.md index bd5112a8..9d501ed2 100755 --- a/docs/src/reference/interop.md +++ b/docs/src/reference/interop.md @@ -11,6 +11,7 @@ program: | SolidCraft design `.sc` (ZIP container with `container.json`, or JSON with `"format": "solidcraft/N"`) and the legacy `.solidcraft` | recognised as *SolidCraft design* (`.sc` is checked by content, so scripts with the same extension are not mistaken for designs); the picture SolidCraft embeds (`cache/thumbnail.png`) is the preview image when its key still names this document; an assembly's linked designs (`links`) are its file references, counted by their placements | | SolidCraft lock file `.~.lock` (JSON: computer, user, refresh time) | never uploaded; the desktop app shows a design that is open in SolidCraft and warns at check-in | | FieldCraft model `.fieldcraft` (ZIP: `fieldcraft.json`, `model.json`, `mesh.bin`, `journal.json`) | recognised as *FieldCraft analysis model* | +| `solidcraft-cli` on the user's computer | the desktop app exports `.sc` designs to STEP with it (*STEP* in the Workspace tab, *Create STEP exports … first* at check-in), on Windows, macOS and Linux; the server never runs it | | STEP, 3MF (incl. SolidCraft's face-tagged 3MF), STL, OBJ exports | 3D preview in the browser and the desktop app; STEP is searchable and scanned for references | | Abaqus input decks (`.inp`) written by FieldCraft | recognised as *Abaqus input file* | From 63f614eaefb6e140edd23c3e2ef84c4929333f43 Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:29:35 +0100 Subject: [PATCH 06/10] Desktop: module order (rustfmt) Co-Authored-By: Claude Opus 5.5 --- desktop/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 6e44e054..619cac9e 100755 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -13,8 +13,8 @@ mod api; mod autoallow; mod bomimport; mod cadexport; -mod cadlock; mod cadlaunch; +mod cadlock; mod commands; mod compat; mod crash; From 808bb2a3c2188a09fdbbcab9f42e0647803fe9fc Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:29:35 +0100 Subject: [PATCH 07/10] Desktop: module order (rustfmt) Co-Authored-By: Claude Opus 5.5 --- desktop/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 6e44e054..619cac9e 100755 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -13,8 +13,8 @@ mod api; mod autoallow; mod bomimport; mod cadexport; -mod cadlock; mod cadlaunch; +mod cadlock; mod commands; mod compat; mod crash; From fbf255a0e983041ddb8ee82f98c9b92e9097e121 Mon Sep 17 00:00:00 2001 From: fork Date: Sat, 21 Nov 2026 23:31:38 +0100 Subject: [PATCH 08/10] Desktop: write item number and revision into SolidCraft designs (#369) desktop/src/scprops.rs builds one document.metadata.set script (part_number, revision, description and TeamCraft's object with item and revision ids and the server under teamcraft.pdm) and runs 'solidcraft-cli run