printCAD GitHub Download

Workbench packages

A workbench package adds a workbench to printCAD without changing or rebuilding the app: tools, feature kinds with parametric solids, task panels, viewport drawing, commands for scripts and agents, and a Preferences page. A package is a WebAssembly component, so one file runs on every system printCAD runs on, and it runs sandboxed: it reaches its own folder and nothing else unless the user allows more.

A complete example sits under sdk/examples/gear: a spur gear workbench. sdk/examples/peg is a small one showing a tool's whole gesture (see Gestures). A larger one is the CAM package, PrintCAD-cam-wb, which works out pocket toolpaths from a sketch's outline in a job, draws them over the model and writes them as G-code. A repository to start a package from, with CI and releases on tags already set up, is PrintCAD-example-wb.

Installing one

Preferences › Workbench packages › Browse is the workbench store: the packages every store you keep lists, to search, read about (what each asks to reach beyond its own folder comes first) and install. A store is a registry's index; a new install keeps one, printCAD's own, and the Stores tab beside it adds others by their index's address or removes any, printCAD's included. A registry reviews each listing and checks that the package is what it says it is; it does not audit the code, so install what you trust, from stores you trust. A package installed from a store comes from its repository's latest release, checked against the list's checksum, and updates as any package from GitHub does; one a store takes off its list is marked, and whoever has it is told why. Anyone can run a store: the registry's README says how.

Installing does not need the store: the Installed page installs a .pcbench file (Install from a file…) or a package published on GitHub: type the repository's address (https://github.com/owner/repo, or owner/repo) to take its latest release, or a release's address (…/releases/tag/v1.2.0) to take that one. A package installed from GitHub remembers where it came from; Check for updates looks for a newer release (and does so at every start unless you turn that off), and Update to … installs it, keeping the package's data and what you allowed it. An update that holds a different package, or whose download does not match GitHub's checksum, is refused.

The page lists what is installed, whether each loaded, turns one off, removes it, and says what each may reach beyond its own folder:

Capability What it allows
save_dialog ask you where to save a file it made, or a folder for several (allowed unless you turn it off)
open_dialog ask you for a file to read, and read the one you pick (allowed unless you turn it off)
helper run native programs the package ships, outside the sandbox
network open network connections

An install, an update or a removal takes effect at once: the workbench appears in the workbench list (or leaves it), and features it owns in open documents rebuild with the version now running. Turning a package on or off, and what it may reach, take effect when you apply Preferences. Packages live in ~/.local/share/printcad/workbenches/<id>/, each with a data/ folder that is the only part of the disk it sees (as /data). The app compiles a package's component to native code the first time it loads it and keeps the result in ~/.cache/printcad/compiled-packages/, named by a hash of the component and of the runtime that compiled it, so later starts skip compiling; a changed component or a new runtime is compiled afresh. The folder is the app's own and is safe to delete; it keeps the 64 most recently used components, 512 MB at most.

A document made with a package keeps its features when opened without it: a notice says which package it needs, the tree marks them "Needs ", their bodies keep the shape they were saved with, and they cannot be deleted until the package is back. A feature records the package and version that last wrote it and, for a package installed from GitHub, its repository, so the feature's menu in the tree offers "Install ". A package reads each feature with the version that wrote it (Node::made_by), which is what lets it read data an older version saved.

Writing one

A package is a Rust crate built as a cdylib for wasm32-wasip2 against the SDK, printcad-bench-sdk on crates.io (its source is sdk/printcad-bench-sdk). Other languages that build WebAssembly components can implement crates/bench_api/wit/workbench.wit directly; the values it carries are the printcad-bench-api types as JSON.

# Cargo.toml
[lib]
crate-type = ["cdylib"]

[dependencies]
printcad-bench-sdk = "0.1"

To build against a printCAD checkout instead, say while trying a change to the SDK, patch the four crates to its folders:

[patch.crates-io]
printcad-bench-sdk = { path = "../printCAD/sdk/printcad-bench-sdk" }
printcad-bench-api = { path = "../printCAD/crates/bench_api" }
printcad-kernel-api = { path = "../printCAD/crates/kernel_api" }
printcad-panel-api = { path = "../printCAD/crates/panel_api" }
use printcad_bench_sdk::{Bench, api::*, bench, host};

#[derive(Default)]
struct Hello;

impl Bench for Hello {
    fn describe(&self) -> Registration {
        Registration {
            label: "Hello".into(),
            tools: vec![Tool {
                id: "acme.hello.wave".into(),
                label: "Wave".into(),
                behavior: ToolBehavior::Action,
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    fn input(&mut self, input: &Input) -> bool {
        if matches!(input.event, Event::ToolActivated) {
            host::info("Hello");
            return true;
        }
        false
    }
}

bench!(Hello);

Every method of Bench has a default; implement what the workbench offers.

Versions

The SDK and the crates under it are versioned by the contract they speak: 0.1.x is printcad:workbench@0.1, which the manifest's api names. A printCAD loads packages of its own contract and refuses others.

A patch release (0.1.1, 0.1.2) only adds, so a package written against an earlier 0.1.x keeps building after cargo update, if it keeps to two habits:

What a package builds as an enum variant with fields (Widget::Number, Request::SaveFile, SolidOp::Sweep, Plan::Ops) keeps its fields within a minor version: a new option comes as a new variant, or as a new struct that derives Default. A field added anywhere reads as its default when left out, so what an older package sends still reads.

A package that uses something a patch release added needs a printCAD of at least that release, and says so with min_contract in its manifest (min_contract = "0.1.4" for the panel blocks): a printCAD of an earlier release refuses to load it, naming the release it needs, rather than draw part of its panel. Left out, any printCAD of the api contract loads it. Releases before 0.1.4 do not read min_contract; a frame using a block they do not know fails to read whole there, so they draw none of it rather than half. A new minor version (0.2) is a new contract: a package moves to it by changing its dependency and its manifest's api, and a printCAD of 0.2 does not load packages of 0.1.

The SDK is published from the printCAD repository: a tag sdk-vX.Y.Z publishes printcad-kernel-api, printcad-panel-api, printcad-bench-api and printcad-bench-sdk, all at X.Y.Z. From 0.1.5 each crate asks for the same release of the crates beneath it, so cargo update -p printcad-bench-sdk brings the contract crates its code was written against. With 0.1.4, update all three together.

The manifest

bench.toml sits beside the component:

id = "acme.hello"            # lowercase, reverse-domain
name = "Hello"
version = "0.1.0"
api = "printcad:workbench@0.1"
min_contract = "0.1.4"       # optional: the earliest release it needs
description = "Says hello"
feature_kinds = ["acme.hello.note"]   # each starts with the id
memory_mb = 256              # default 1024, at most 4096

[capabilities]
save_dialog = true

Tool, action and command ids start with the package id too; others are left out with a warning.

Building and packing

cargo build --release --target wasm32-wasip2
mkdir -p pkg/icons
cp bench.toml pkg/
cp target/wasm32-wasip2/release/hello.wasm pkg/bench.wasm
cp icons/*.svg pkg/icons/
tar czf hello.pcbench -C pkg .

To publish, attach the .pcbench file to a GitHub release. The release's tag is its version for updates (v0.2.0 is newer than v0.1.0); the first .pcbench asset of the latest release is what users get. To have it in the store, add an entry to the workbench registry by pull request; its README says how. Releases after that reach the store by themselves.

Icons are 24×24 SVGs drawn in white (#fff) with a 1.5 px stroke; the app tints them. A tool or feature names one by its file name (gear for icons/gear.svg), or any icon of the app's own set.

What a bench does

Features. A bench owns the feature kinds its manifest lists. It makes and changes them only through host calls, each an ordinary edit: undone with Ctrl+Z, recorded, sent to peers. host::add_feature, set_feature_data, remove_feature, create_body, remove_body (a body with only the package's own features on it, never an imported, linked or copied one; a body removed with features still on it clears the undo history, as deleting one in the app does, so a cancelled part removes its feature first and then the empty body it made, which undoes), and host::call(api::calls::…) for the rest (renaming a feature, showing or hiding it, placing a body). Calls are allowed while the bench handles an event, a panel change, a menu entry or a command, and refused while it draws or plans. A feature's data is any JSON the bench likes.

Four calls only read, each answering where the body sits, and are answered when the other calls are:

The names are the kernel's: a face is named by the feature and the sketch element that made it and keeps its name through rebuilds, so a package keeps a face's or an edge's name rather than a point, and finds it again with geom.face_loops {name}. A pick carries them too (FaceRef::name, EdgeRef::faces). Imported solids name no faces.

Status and order. FeatureInfo::status shows how a feature's work stands as a badge beside its name in the tree: not run, running, done, warnings, failed or out of date, with a note for its tooltip. A running status naming its job shows that job's progress. The status is asked for again when the feature changes or the bench calls host::redraw. A feature of the bench's dragged in the tree reaches it as Event::FeatureMoved (dropped before or after target): used, the bench places it its own way, with calls::MOVE_FEATURE or in its own data, or leaves it where it was; passed over, the host moves it in its body's history. Either is one undo step.

Bought parts. Registration::bought_kinds names those of its kinds whose bodies are bought rather than made, such as catalog screws and bearings. The parts list marks such a body bought until the user clears the mark, and an export of everything and the slicer leave it out.

Radial menu. Registration::radial names up to eight of the package's tools or commands, clockwise from the top, for the menu a right press held still over the view opens while the bench is active. The user can choose others for it in Preferences › Input › Radial menu, which lists every bench, packages included; a package that names none offers its most used tools.

Parameters and formulas. parameters lists a feature's numbers: a key, a JSON pointer into its data, a dimension. Those numbers take formulas anywhere the app shows them, and the data a bench reads (host::feature, the nodes it is handed) already has the formulas' values in.

Solids. When a feature changes, the app asks rebuild for a plan per body: kernel operations (SolidOp: extrusions, revolutions, lofts, booleans, fillets and the rest), each naming the feature it is for. The kernel runs them natively; a failing op marks its feature.

A plan may also declare cosmetic threads (Rebuild::threads, each a CosmeticThread): a thread on a round face of the solid it builds, never modelled. The face keeps its size (a bore its tap drill, a shank its major diameter) and a helix of the thread's pitch is drawn just off it, inside a bore and outside a shank, from the face's end nearest the thread's point for its length (0 the whole face), in every bench. The helix is only drawn: no export carries it, and STL and 3MF get the face at its size. The face is found by its name while the solid has a face of that name, else at point (in the body's own frame, as the ops are). The thread draws while its feature shows. A thread given a designation ("M6"; optional) is named where the app names threads, as a hole's cosmetic thread is: a callout at the face's end under View › Annotations, the Assembly's parts list ("2 × M6 thread") and a STEP export's callouts. Putting it in the feature's kind_label as well ("Rod · M6 thread") is the package's choice.

Panels. A bench declares its task panel and Preferences page as widgets (Widget): headings, a header with an icon, text, read-only values, notes, numbers, sliders, choices, toggles, text fields, buttons (a small one for an action on its row), pick rows, lists, tables, sheets (a table whose cells may be links, text fields or check boxes, each change told by row and column), groups, rows of widgets side by side, a hint on any widget (Hinted, or HintedFigure with a small diagram under the words), progress, separators and diagrams. A table's columns marked editable take typing, each cell left coming back as PanelEvent::Cell (the CAM package's tool table is one). A number bound to a feature's parameter (bind) takes formulas like any field of the app's own. Changes come back as panel_event; Done and Cancel as task_close. After a Cancel the host takes back everything done while the task was open, so a package's own restore is not needed, and does no harm. A bench whose Preferences page declares no widgets gets no page. The Preferences page is asked for once and kept; a bench whose page changes on its own (a job brought what it shows) calls host::redraw, and the page is asked for again.

Every labelled field of a section (the panel's top level, a group, a section's children, a Fields block) puts its label in one column as wide as the section's longest label, from 96 to 160 px and never more than 45% of the panel, so each control starts at the same x. A longer label is cut, and whole on hover.

Panel blocks. From contract 0.1.4 a panel can also say what each part of it is, and the app draws it as its own panels draw theirs (the sketcher's lists, for one). A package gives no colours, fonts or sizes: a Tone (neutral, good, warning, bad, info, accent, muted) says what a mark means. Only an item's icon and a badge take a colour of their own (color, sRGB), for a list of geometry drawn in the view's colours. The SDK's panel module builds them.

panel::Form walks a panel once for both of its ends: built without an event it lists the widgets, built with the event the app sent it hands that event to the field it names, so the code that declares a field also says what a change to it does. Its binders (number, check, choose, index, text, button, action, toggles) give each widget an id from its name, set the value they bind when the event names it, and return the widget for the panel to place (form.put(bound) puts it next). It runs inside the package and sends ordinary widgets, so it needs no min_contract.

These events come only from these blocks, so a package that uses none never sees them. A package that uses the blocks names min_contract = "0.1.4" in its manifest.

Diagrams. Widget::Diagram is a schematic of what the panel edits, with its measures marked beside the parts they size. The bench draws it in a space of its own, [0, width] × [0, height] with y up, in whatever unit suits (a part's millimetres); the host fits that space to the panel's width, at most 220 px tall, and keeps strokes, arrowheads and text at their pixel size whatever the fit, so leave a margin for the labels. shapes are paths, circles and text; a path or circle has a DiagramStroke naming its role (outline, hidden dashed, axis long-dashed, thin, accent) rather than a colour, so they follow the theme; a filled path is shaded, which reads right only for a convex outline, so shade a part as several convex pieces. A Dimension measures from to to: its line stands offset away, to the left of the way from from to to (negative for the right), led out to the two points, with text on it. A Callout puts text at at with a leader to a dot at anchor. Either drawn with emphasis takes the accent colour: the bench sets it on the measure of the field last changed, since the host does not know which field is being edited. PrintCAD-hardware-lib-wb draws every part this way. A press on a diagram, each move of a drag begun on it, and where the drag ends come back as PanelEvent::DiagramPress in the diagram's own coordinates (dragging, released), so a diagram can be a timeline that seeks where it is pressed.

Drawing. frame answers everything the bench shows: the task, the panel, the viewport's hint, badge and footer, the status bar's items, lines, marks and labels in world space, and meshes, a mesh with a colour per vertex (colors, multiplying its color) where it wants one. A large mesh that changes in part (simulated material) is kept instead: host::mesh_create sends it once and answers a handle, the frame draws it by that handle (kept), and host::mesh_update replaces a run of its positions and colours; HeightField in the SDK keeps a grid of heights this way and updates the rectangle that changed. regions are flat outlines with holes, which the host fills (opacity) and hatches (hatch, the lines' spacing in mm, at hatch_angle). The app keeps it and asks again after an event, a document or selection change, or host::redraw, and moves the drawing with the view itself. A frame with animating set is asked for again every frame while its bench is on screen, for playback and anything else that moves on its own. Its transport widgets fill a strip under the view while the bench is active, in a row (a timeline, play and step buttons, a clock), their events coming with PanelSlot::Transport.

Floating cards. A frame's card (a FloatingCard, from 0.1.7) is a card over the view next to what it edits, for a quick edit of a value or two, such as a size typed right after a pick: anything with more to set is a task in the right panel. It has a title, widgets drawn with a task panel's controls but compact (labels only as wide as the widest, fields 96 points wide unless a widget gives a width, values against the right edge), and the point it sits by, in the world (at) or in viewport pixels (screen); the host draws it opaque over the bench's drawing, on the side of that point where it hides the least of the lines, marks and labels the bench draws, never on the point itself, and inside the view. focus names a text field (Entry) that has the keys as the card opens, its text selected, so the first key typed replaces it. The host adds OK (ok names it) and Cancel; Enter is OK, Escape is Cancel, and a click elsewhere in the view is OK. While refusal says why, OK is held back and the reason shows under the widgets as a warning. Its widgets' events, and then PanelEvent::CardClose {id, accept}, come with PanelSlot::Card; after it the bench leaves card out. Keep the edit in the package until OK: what OK writes is one undo step, and on Cancel the host takes back anything written while the card was open. A new id opens the card afresh. panel::floating_card builds one. A package using it needs min_contract = "0.1.7". A CardClose naming another id than the card the frame shows, or any card event while it shows none, never reaches the package.

A card with ok_only (from 0.1.8) has OK alone: Escape is OK too, and only a refused card is dropped, for what a step already made leaves to set. On any card, the edit finished or another tool or bench picked while it shows is OK, or its drop while refused.

A card with a hint (from 0.1.8) is a readout instead: the values a tool is drawing with, which the package types into through its own key events. The host writes the hint (Tab next · Enter places it) where OK and Cancel would be, leaves the keys and the pointer with the package, holds no undo step and sends no CardClose; it moves the card to the side of its point that hides the least as the point moves. Its fields are Quantity blocks with shown, the text the package has for the value (a number, or a formula with what it comes to), drawn in the field with the unit and not edited there, focus ringing the field the keys type into, and held, a lock after the field, shut while the value is held; a click on a lock comes as PanelEvent::Toggle with the field's id. One card shows at a time.

Profiles. host::profile(feature) answers a feature's closed loops (a sketch's) where they stand in the world: the plane, then the loops, holes inside their outlines, as lines, arcs, circles, ellipses and splines. The CAM package reads a pocket's outline this way.

Input. input gets clicks, key presses, tool activations and actions, with what is under the cursor and what is selected (Pointer: the ray, the point and body hit, the picked face and every face picked (faces, in the order picked), the picked edges (a circular one with its circle: centre, axis and radius), the active feature; faces and edges carry the kernel's names where the solid has them), and what the cursor is over whatever is selected: hover_face, hover_edge, and vertex, an end of the edge under it within a few pixels. A Move with a pick row armed is the cue to light what a click would take. A double click on a feature's tree row arrives as Event::EditFeature, the cue to open its task; selecting a feature alone never opens one.

Menus. menu_items adds entries to the viewport's body menu, the tree's feature and body rows, the start page's New cards and the Edit menu (MenuScope); a pick runs menu_command with the entry's id. For something the package draws itself, Request::OpenMenu { tag, items } (from 0.1.8) opens its own menu at the pointer, usually from input on a right click (Event::Release of Button::Right); the pick runs menu_command with MenuScope::Popup(tag), and Escape or a click elsewhere closes it unpicked. An entry with checked (from 0.1.8) draws ticked, the choice that stands. A package using either needs min_contract = "0.1.8".

Files. With save_dialog, Request::SaveFile asks where to save one file the bench made, and Request::SaveFiles asks for a folder and writes every file into it (plain names only: one program per operation). With open_dialog, Request::OpenFile { id, kinds, multiple } shows the open dialog with the kinds offered, and the files picked come back as Event::FileOpened with the same id, each its name and bytes, up to 64 MiB in all; a cancelled dialog answers with none. Request::CopyText { text } puts text on the system clipboard, needing no capability (contract 0.1.4).

Commands. Commands in describe appear to Lua scripts (pc.acme.hello.…), AI agents and recordings, and run in run_command.

Jobs. Long work runs as a job: host::start_job(entry, input) runs Bench::job in an instance of its own away from the window. It reports with host::progress, stops when host::cancelled, and a Progress widget naming the job shows how far it is. Its result comes back as Event::JobFinished, whichever bench is on screen, but only in the tab it was started in and while that tab holds the document it was started for (see Interruptions). The CAM package works out every toolpath this way and stops it when its task is cancelled. A job allowed helper may run a program from the package's helpers/<os>-<arch>/ folder with host::helper, for work that needs every core. The helper reads the input on its standard input and writes the result to its standard output. Each line progress <done> <total> it writes to its standard error moves the job's bar as host::progress does, while it runs. Its other error lines end a failure's message.

A helper can also be kept running and talked to a line at a time, for one that holds a run in memory and answers questions about it as they come: host::helper_open(name) starts it and answers a handle, helper_send writes a line to its standard input, and helper_receive(handle, wait_ms) answers its next line from its standard output, waiting inside a job and never outside one, so the window never waits on it. The bench as well as its jobs may open one, with the helper capability. A session ends at helper_close, when the job that opened it ends, or with the package's instance, and the helper is killed then.

Interruptions

What the host does to a package when the user's work is cut short. None of it needs a contract later than 0.1.

Interruption What the package sees
Tool change Event::ToolActivated, with the active tool in Input::tool.
Bench switch Event::Deactivated for the bench left, Event::Activated for the one entered.
Finish editing Event::Action { id: "finish-editing" }.
Window loses focus An Event::Release for each button the package was told was pressed and not released, where the pointer last was.
Tab switch suspend for the tab going off screen (its answer is kept with that tab), then resume with what the incoming tab kept, or none for a new tab. A press held over the switch is forgotten, not released.
Script command in a tab off screen resume with what that tab kept, the command, then suspend (kept with that tab again) and resume with the on-screen tab's state, so the command reads and changes that tab's state and a job it starts belongs to that tab. A press held on screen meanwhile is forgotten, as over a tab switch.
Tab closed Nothing. Its kept state is dropped, its running jobs are stopped and their results never told.
Job finishes Event::JobFinished in the tab it was started in, once that tab is on screen; held while it is off screen. If the tab has another document open in it by then, the job is stopped and never told.
Package turned off, updated or removed Event::Deactivated when it is the bench on screen. Its jobs are stopped, and what other tabs kept of it is dropped, so a later load never sees it.
Fault (overrun, trap, memory) The instance starts afresh with its state lost (Limits); jobs already running keep running and are told to the new instance.

Gestures

A tool that previews, asks for a value, and then applies or is dropped needs nothing beyond the events and the floating card. The Peg example (sdk/examples/peg) is that tool:

A tool that writes while the pointer moves (a drag of a value) is one undo step too: the host closes a step only when no button is held and no card is open. So the contract has no gesture acknowledgement and no undo step scoped to one gesture: what a package does within a gesture is already one step, and what it drops was never written. A tool that needs to take back one part of a longer gesture keeps that part as its draft until the gesture ends.

Testing a package

wb_wasm::testing::Harness drives a package the way the app does, with no window and the same result every run. It loads a package folder (bench.toml and bench.wasm), keeps tabs of empty documents, and gives every step a fixed view: an 800 × 600 viewport looking down on the ground plane at 10 pixels a millimetre, testing::pixel(x, y) the pixel over a point. Around each step it does what the app does to the undo history, so a test can check that OK is one step and Cancel leaves none.

Step Harness
Tool, pointer, keys tool, press, move_to, release, drag, key
What it shows frame (the package's Frame), card, logs
The card type_text, card_event, ok, cancel
Commands and jobs run, wait_for_jobs
History undo, can_undo, document, document_mut
Interruptions focus_lost, open_tab, switch_tab, close_tab, unload, reload
Anything else with, the bench and a context for the tab on screen

It lives in the printCAD repository, so a package's tests take it as a dev-dependency from there, and build the package for wasm32-wasip2 first:

[dev-dependencies]
wb_wasm = { git = "https://github.com/gilbertorconde/printCAD", default-features = false }
use wb_wasm::testing::{Harness, pixel};

let mut h = Harness::open(Path::new("pkg"), &Default::default())?;
h.tool(Some("acme.peg.place"));
h.drag(pixel(0.0, 0.0), pixel(6.0, 0.0), 3);
h.type_text("height", "5");
assert!(h.ok());
assert!(h.undo().is_some());

The Peg example's tests in crates/workbenches/wb_wasm/tests/packages.rs use it. A harness keeps compiled components for the test run; to keep them between runs too, name a folder of the build's, as those tests do: wb_wasm::set_compiled_cache(Path::new(env!("CARGO_TARGET_TMPDIR")).join("compiled-packages")).

Limits

A call the window waits on has 25 ms: frame, input, and the feature info, parameters and menu entries the tree and menus ask for. Any other call has 1 s, and so do two events: a double click that opens a feature's task (Event::EditFeature) and a finished job (Event::JobFinished). A job has no limit and stops when the user stops it. A call over its budget, a panic or memory past memory_mb stops the bench's instance, which starts afresh (its state lost); after three such failures in a session the bench is turned off until the app starts again.

This page's source