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
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:
- Match what the app sends with a wildcard arm.
Event,PanelEvent,MenuScope,PanelSlot,Button, and the kernel'sFaceSurfaceandProfileSegmentare#[non_exhaustive]: a new kind of event or curve comes in a patch release, and a_ =>arm leaves it to the default. A package built with an older SDK passes over an event it does not know. Bind a received variant's fields with..too (FaceSurface::Cone { axis, .. }): a patch release may add one, as it added a cone's half angle and a torus's radii. - Fill the contract's structs with
..Default::default().Registration,Tool,Command,Param,Parameter,FeatureInfo,Rebuild,Task,Polyline,Label,Mesh,MenuItemand the rest deriveDefault, so a field a patch release adds takes its default. (Clippy'sneedless_updatelint flags a literal that names every field; the examples allow it.)
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 = trueTool, 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:
geom.holes {body}lists the round holes in a body's solid (each{entry, direction, diameter, depth, through, drill_point_deg}).geom.face_edges {body, point}lists the edges round the face at a point (each{point, direction}halfway along it).geom.section {body, plane: {origin, normal, x_axis?}, face?}answers aSection: where the plane crosses the solid, or withface(a point) only the face there, as loops of curves end to end (closed round a solid's cut), each curve exact in the plane's 2D coordinates (along itsx_axisandy_axis, which the answer'splanegives), with points along it and the name of the face it crosses.geom.face_loops {body, point?, name?}answersFaceLoops: the face's name and its boundary loops, the outer one first, each edge with its points in loop order, its length, a round one'scircle, whether it is the seam a round face meets itself along, and the names of the two faces it runs between. A face is asked by its name (of several, the one nearestpoint) or atpoint.
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.
Section: a fold with its title in small capitals, an optionalcount, asummaryshown while it is closed,openat first or not, iconactionsat its right end (each aPanelEvent::Buttonwith the action's id) and itschildren.Item: a row with an icon in a tone (ormuted, or aproblem), the label, dimsecondarywords,tags(small chips: the elements a constraint ties), avalueat the end (mono unlessvalue_plain), glyphbadges,selected, ahint, and a right-clickmenu(an entry may carry ahintand beseparatedfrom the one above). An item may berelatedto what is in hand (a faint tint) orlitas that item itself, take avalue_toneand avalue_hint, aflag(a word after the value in its tone), be revealed (revealscrolls to it), have its name typed into whileediting(ItemTextat each change,doneas it is left), or put afield(aQuantity) at its end in place of the value. A tag or a badge may belit.Items: a list of items. A click isSelect, or withmultithe whole new selection asSelection(Ctrl adds). A double click isActivate, a menu entryContextMenu, a tagTag, and the pointer coming onto a row or leaving the listHover, so the bench can light the item in the view. A badge clicked isBadge, andHoverPartsays which item, tag and badge the pointer is on whenever that changes. A list that stops being drawn while the pointer was on it (its section closed) is told the pointer left.Filter: a search field over the lists that name it infilter, with a kind selector when it haskinds(the first passes every item, the others an item of thatkind). The app filters by label, secondary words and tags as the user types, with no call to the package; withby_benchit leaves the lists whole and sendsFilterinstead.Status: a state in a few words as a toned pill, the reason on hover.TaskHeaderputs asubtitleunder a task's title and astatuspill beside it, in the header the app draws above the task panel.- Layout:
Stack(one under another, close together whentight, or its ownspacingbetween them when given),Flow(side by side, wrapping unlessno_wrap, after alabelin the label column when it has one),Fill(in a flow, takes what the others leave),Fields(fields with a label column of their own,label_widthwide when given),Inline(a field with its label at its own width, no column),Settings(a titled, bordered group of rows as the Preferences pages draw them, each child's label at the left and its control at the right). PickChip: what is picked in the view as a compact chip; a click arms it (Pick), its cross clears it (Clear).Entry: a text field with aplaceholderwhile empty, told once typing ends, or at each change whenliveand thenTextLeftas it is left (escapedwhen by Escape, which drops what was typed); it may bemultiline,monoand of a givenwidth.Quantity: a number asNumbersays it, with its dragspeed, itswidth, aunitof its own (N·m),enabledor not,focusto take the keyboard once, and as astepper(its value between a down and an up button, each with its state and hint; a press is the value one down or up), orbare: the system's plain number drag, itsunitwritten after it as given.drag_minanddrag_max(from the next 0.1 patch) bound what a drag, the wheel or a stepper's buttons set, insideminandmax: they stop there, while a typed value may go past. Give a size that builds only up to a limit its limit asdrag_max, so only typing can ask for one that fails.Range: a slider frommintomax, its value written withdecimalsand asuffix(%), told asNumber.Check: a check box withtextbeside it, under alabelin the label column when it has one,enabledor not, with ahint.Select: a choice ofoptionswith itswidth,enabledor not, atextshown in place of the chosen option (a count, or a prompt for a list that only adds), optionsdisabledorseparatedby a line, a hint on hover for each, orsegmented: the options side by side.Grid: a two-column grid, each labelled field's label in the first column (as wide as the grid's longest label) and its control in the second; a widget with no label takes one cell. Rows sit close, or a little apart whenroomy; the controls sit a little further from the labels whenapart.Alert: a note asNotedraws it, a click on it aButtonevent of itsid.Card: a raised card under an icon and a title, holding widgets, with apaddingof its own when given.Caption: words in a tone,smallor the panel's size,monoor not,strong(semibold, in the primary text colour),medium(the medium face) andprimary(the primary text colour in place of the tone's), or anoverline(a small heading in small capitals).Plot: lines along a stripheightpoints tall, each series in a tone scaled to its own peak.Gap: room between widgets,small,medium,large, orsection(the room before a part under its own heading).Swatches: small squares of colour (sRGB), thechosenones ringed; a click isChoicewith the swatch's place; askeysthey are smaller, unringed and take no click, a legend's keys to what the view paints.Color: a colour button opening the system's picker, each change aColorevent with red, green and blue from 0 to 1.Gallery: square pictures each over its name, theselectedone ringed, a click aChoice; aPictureis RGBA pixels under akey, which the app keeps, so a key names one picture.RowButton: a frameless button the panel's width, one of a list of places (Button); thecurrentone is lit and takes no click.Selectable: words lit whileselected(Button), a few in aFlowchoosing one.Toggles(from 0.1.8): icon buttons in a row under alabel, eachonor not,disabledor not, itshinton hover, the way a text editor shows alignment; a click is aButtonevent of the button'sid, and the package lights one and puts out the others when they are a choice.panel::togglesbuilds one; a package using it needsmin_contract = "0.1.8".Cells: widgets in rows ofcolumnscells, each column as wide as its widest, rows close: a table of readings undermediumcaptions as column titles.Action: a small icon button on its own, itslabelon hover, aButtonevent of itsid(a cross at a row's end that takes the row out).- Buttons take three more styles:
plainandplain_small, the system's own unstyled button, andoutline, outlined in the accent, for taking what is picked in the view. Entrycan offer the document's names as a formula is typed (formulas) and belarge, in the panel's larger text size.
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:
- Preview. A press starts the gesture and each
Movechanges it; the package draws it in its frame (lines,labels) and writes nothing. - Acceptance. The release opens a card with the
values. The package keeps them as a draft, its preview following what is
typed, and writes them only on
CardClose { accept: true }. The host makes what that writes one undo step. - Cancellation. Cancel, Escape during the drag, a
tool change, a bench switch, a closed tab, a fault or an unload drop the
draft. Since nothing was written, the document and its undo history are
as before. A draft the package returns from
suspendcomes back with its tab. - Stale references. The package checks what it holds
when it writes: a feature removed while its card was open is refused by
host::call, and the package says so rather than write.
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.