printCAD GitHub Download

Writing a workbench

A workbench is a crate that implements core_document::Workbench. The application never refers to a workbench by name. Everything a workbench shows, draws, picks, rebuilds or asks for goes through this trait and the workbench registry (DocumentService).

Workbench itself holds what a workbench is and its lifecycle (descriptor, configure, activation, frames, the state that moves with a tab). The rest is in one supertrait per concern, every method with a default:

Trait What it covers
BenchFeatures How owned features show in the tree and the view, picking, deleting, the edit session
BenchTools Tool buttons, input, what the workbench draws in the view while active
BenchPanels The task panel's state, the floating card, menu entries, its settings
BenchBuild Rebuild plans, mesh histories, derived working data
BenchParameters Numbers formulas set, the property panel's hints and swappable inputs
BenchOutput Reports, annotations, threads, bought bodies, print parts
BenchCommands Running the commands it registered

A workbench implements all of them, writing out only the methods it uses and leaving a group it does not need empty:

impl Workbench for MyWorkbench { /* descriptor, configure, ... */ }
impl BenchFeatures for MyWorkbench { /* feature_info, ... */ }
impl BenchTools for MyWorkbench {}
impl BenchPanels for MyWorkbench {}
impl BenchBuild for MyWorkbench {}
impl BenchParameters for MyWorkbench {}
impl BenchOutput for MyWorkbench {}
impl BenchCommands for MyWorkbench {}

The host calls every group through dyn Workbench. Code that calls a group's method on a concrete workbench type (a test) imports that trait.

Design (crates/workbenches/wb_design), the Sketcher (crates/workbenches/wb_sketch), Surface and Assembly are complete examples. This guide is for a built-in workbench; one installed as a package is written against the guest SDK instead (Workbench packages).

1. Create the crate

[package]
name = "wb_mine"

[features]
default = ["egui"]
egui = ["dep:egui", "dep:ui_kit", "dep:bench_panel"]

[dependencies]
core_document = { path = "../../core_document" }
kernel_api = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
egui = { workspace = true, optional = true }
ui_kit = { path = "../../ui_kit", optional = true }
bench_panel = { path = "../../bench_panel", optional = true }

The egui feature enables the bench's drawing side: what it draws itself with egui is bench_panel::BenchUi (ui_task_panel, ui_settings, ui_left_panel, ui_viewport_strip, each drawing nothing by default), implemented on the bench's own type beside its Workbench:

#[cfg(feature = "egui")]
impl bench_panel::BenchUi for MyWorkbench {
    fn ui_task_panel(
        &mut self,
        ui: &mut egui::Ui,
        ctx: &mut WorkbenchRuntimeContext,
        request: TaskRequest,
    ) -> TaskOutcome {
        // ...
    }
}

The workbenches crate gives every bench it lists its drawing side, so nothing else is needed. Panel code takes colours and sizes from ui_kit::tokens, never as literal values.

Add it to the workspace members and to the workbenches crate's dependencies, then register it in crates/workbenches/src/lib.rs:

listed!(
    SketchWorkbench,
    DesignWorkbench,
    SurfaceWorkbench,
    AssemblyWorkbench,
    MyWorkbench
);

Every bench in that list registers with its drawing side, so it must implement BenchUi, even if only as an empty impl.

The order matters. A new document opens in the first workbench that is not modal, and Preferences lists workbench pages in this order. The switcher and menus sort by label.

2. Describe the workbench

fn descriptor(&self) -> WorkbenchDescriptor {
    WorkbenchDescriptor::new("wb.mine", "Mine", "What it is for.")
        .icon("workbench-mine")
        .feature_kinds(["wb.mine"])
}

3. Add tools

configure runs once and registers the tools:

fn configure(&self, context: &mut WorkbenchContext) {
    context.register_tool(
        ToolDescriptor::new_action("mine.thing", "Thing", Some("shape")).icon("thing").row(1),
    );
}

4. Add keyboard shortcuts

A tool gets a default key with .shortcut. Pressing it while the workbench is active works like clicking the tool's button:

ToolDescriptor::new("mine.line", "Line", Some("draw")).shortcut("L")

For a key that is not a tool, register an action. Its key sends WorkbenchInputEvent::Action { id } to on_input:

context.register_action(
    ActionDescriptor::new("mine.flip", "Flip direction").shortcut("Shift+F"),
);

5. Add commands

A command is something a script can call by name, with named arguments. Keep each command's spec beside the function that runs it in a CommandTable, so its id is written once: the table registers the specs in configure, answers which ids are the bench's and runs them in run_command.

use std::sync::OnceLock;

fn commands() -> &'static CommandTable<MyWorkbench> {
    static TABLE: OnceLock<CommandTable<MyWorkbench>> = OnceLock::new();
    TABLE.get_or_init(|| {
        let mut t = CommandTable::default();
        t.add(
            CommandSpec::new("mine.slab", "Add a slab")
                .param("width", ParamKind::Number, "In millimetres")
                .optional("name", ParamKind::String, "Its name in the tree")
                .returns("the feature's id"),
            slab,
        );
        t
    })
}

fn slab(args: &CommandArgs, ctx: &mut WorkbenchRuntimeContext) -> CommandResult {
    let width = Args(args).number("width")?;
    let made: FeatureId = todo!("add a {width} mm slab to ctx.document");
    Ok(json!(made.0.to_string()))
}

// In `impl Workbench for MyWorkbench`:
fn configure(&self, context: &mut WorkbenchContext) {
    commands().register(context);
}

// In `impl BenchCommands for MyWorkbench`:
fn run_command(&mut self, id: &str, args: &CommandArgs, ctx: &mut WorkbenchRuntimeContext) -> CommandResult {
    commands().run_on(self, id, args, ctx)
}

A command that takes a file as path can also serve File › Import. Register the file kind beside it:

context.register_import(FileImport::new("Slab drawing", ["slab"], "mine.import"));

6. Store features

Define a type implementing WorkbenchFeature (see Document model) and add it with ctx.document.add_feature_in_body(feature, name, body).

For each kind it owns, the workbench answers these (in BenchFeatures, except property_hints, references and set_reference in BenchParameters, and not_printed, print_parts and cosmetic_threads in BenchOutput):

/// Icon and labels for the tree row.
fn feature_info(&self, node: &FeatureNode) -> FeatureInfo;

/// What to draw for the feature when it is visible and not being edited.
/// `node_revision(node)` gives a revision that changes with the data;
/// `region` (a `PassiveRegion`: a profile and an opacity) has the host
/// shade what the lines enclose.
fn passive_geometry(&self, doc: &Document, id: FeatureId, node: &FeatureNode)
    -> Option<PassiveGeometry>;

/// Distance in pixels from the cursor to the feature, if close enough.
fn pick_feature(&self, doc: &Document, id: FeatureId, node: &FeatureNode, pick: &ViewportPick)
    -> Option<f32>;

/// Remove the feature and fix up what depended on it.
/// The default just removes it.
fn delete_feature(&mut self, ctx: &mut WorkbenchRuntimeContext, id: FeatureId) -> bool;

/// Which data fields are lengths and which refer to other features,
/// for the property panel.
fn property_hints(&self) -> PropertyHints;

/// Bodies that are not made (bought parts): an export of every visible
/// body and the slicer leave them out. `bought_kinds` are the kinds every
/// bench declares bought.
fn not_printed(&self, doc: &Document, bought_kinds: &[WorkbenchId]) -> Vec<BodyId>;

/// The parts to print and how many of each, for the print layout. The
/// first bench that answers (the Assembly's parts list) is the one used.
fn print_parts(&self, doc: &Document, bought_kinds: &[WorkbenchId])
    -> Option<Vec<PrintPart>>;

/// Bores the feature threads without cutting the thread, with their
/// designation, for the view, the parts list and STEP.
fn cosmetic_threads(&self, doc: &Document, id: FeatureId, node: &FeatureNode)
    -> Vec<ThreadCallout>;

/// The curves and points the feature lays out, for an array of copies
/// along a path or at points.
fn feature_paths(&self, doc: &Document, id: FeatureId, node: &FeatureNode)
    -> Option<FeaturePaths>;

/// A problem that does not stop the feature building (a sketch whose
/// projected edges are gone), shown on its tree row. Asked whenever the
/// tree draws, so answer from what was last worked out.
fn feature_warning(&self, doc: &Document, kernel: Option<&dyn KernelQueries>, id: FeatureId)
    -> Option<String>;

/// Features of other bodies that act on `body` (a joint holding one
/// body to another); the tree lists each under `body` too, as a link.
fn linked_features(&self, doc: &Document, body: BodyId) -> Vec<FeatureId>;

/// Inputs the property panel lets the user swap (a profile sketch), and
/// how to swap one.
fn references(&self, doc: &Document, id: FeatureId, node: &FeatureNode)
    -> Vec<FeatureReference>;
fn set_reference(&mut self, ctx: &mut WorkbenchRuntimeContext, id: FeatureId,
    key: &str, to: ReferenceChoice) -> Result<(), String>;

A click on a feature in the tree only selects it: it becomes the active document object. A double click switches to its owner and calls edit_feature, which is where the workbench opens the feature's task; never open one on selection alone. editing_feature names the feature under edit (the tree badges it, and a feature that builds solid gets a preview); locks_view_to_plane keeps the camera square to the plane while editing_feature is Some. finish_editing ends the edit session when the user finishes it, or when undo takes away the feature under edit. shows_origin_planes draws the origin's planes whatever the view's setting, for the user to pick one; the plane under the cursor arrives as ctx.hovered_base_plane.

7. Take formulas

parameters and values_moved are in BenchParameters; settle and the derive steps in BenchBuild.

parameters lists an owned feature's numbers that formulas may set and read: a Parameter with a stable key, the name formulas call it, a JSON pointer into the feature's data, a Dim (length, angle, number), a scale for an angle kept in radians, and whether it is a count. The workbench builds, draws and edits from Document::feature_values, which has every formula's value in; its own data keeps plain numbers.

A feature type can state both lists where its fields are declared: #[derive(Walk)] (core_document::walk) gives each field a role, a number formulas set (#[walk(length("depth", "Depth"))]), a setting, or its own type's walk, where every FeatureId is a feature it reads. Walker::of(&feature) then answers its parameters and its dependencies, and a field added without a role does not compile. Design's features are written so (wb_design/src/feature/).

8. Build solids

A workbench whose features make a body's solid implements, in BenchBuild:

/// Bodies to rebuild now, each with a plan. Called every frame.
/// Clear the dirty flags of the planned features here, or the same job
/// comes back next frame.
fn rebuild_jobs(&self, doc: &mut Document) -> Vec<RebuildJob>;

/// The body's history changed: rebuild it from the start.
fn invalidate_body(&self, doc: &mut Document, body: BodyId);

/// Every solid is out of date (undo, redo, Recompute All).
fn invalidate_all(&self, doc: &mut Document);

A BuildPlan is a list of kernel_api::SolidOps (ops) with the feature that made each one (op_features); the application runs it on the kernel worker, and a kernel failure is shown on the feature whose op failed. A feature that cannot be planned stops the plan: put its BuildError in failed and the features after it in unbuilt, and the body shows the history before it. probes asks the solid questions part way through (where a face a sketch stands on is now); the answers come back through derive_on_solid. A job whose plan is Err(BuildError) puts the error on its feature and builds nothing; an empty plan drops the body's derived solid.

9. Add menu entries

In BenchPanels:

fn menu_items(&self, scope: &MenuScope, doc: &Document) -> Vec<MenuItem>;
fn on_command(&mut self, id: &str, scope: &MenuScope, ctx: &mut WorkbenchRuntimeContext) -> bool;

The scopes are the right-click menu on a body, a feature, body or component row in the tree, the Edit menu (edit.cut, edit.copy, edit.paste on the active workbench), and the start page. A start page item becomes a New card. Its command runs in a fresh document with one body. A MenuItem can be checked, drawn ticked: the choice that stands among its entries.

For something the bench draws itself (a node or handle of its own), it opens its own menu at the pointer, typically on a right click it sees in on_input:

ctx.request(HostRequest::OpenMenu {
    bench: WorkbenchId::from("mine"),
    tag: node.to_string(),
    items: vec![MenuItem::new("mine.corner", "Corner").checked(true)],
});

The pick comes back to that bench's on_command with MenuScope::Popup(tag), the tag saying what the menu was for; Escape or a click elsewhere closes it and says nothing. A right click that opens one opens no body menu as well.

10. Ask the host for things

Every hook that acts gets a WorkbenchRuntimeContext: the document, the camera and viewport, hover and selection (selected_faces, selected_edges, selected_face_in(body) for a body's own frame), the active document object, the kernel's queries (kernel), the colours to draw in (sketch_palette), projection helpers, and logging (log_info and others).

Anything else goes through a request:

ctx.request(HostRequest::ActivateTool("mine.select".into()));
ctx.request(HostRequest::SelectBody(body));
ctx.request(HostRequest::SelectFeatures(vec![a, b]));
ctx.request(HostRequest::JournalLabel("Create thing".into()));
ctx.request(HostRequest::CloseToolGesture { bench: WorkbenchId::from("mine") });
ctx.request(HostRequest::UndoToolGesture { bench: WorkbenchId::from("mine"), entry });
ctx.request(HostRequest::StartOn { workbench: WorkbenchId::from("wb.sketch"), attach });
ctx.request(HostRequest::SwitchWorkbench(WorkbenchId::from("wb.design")));
ctx.request(HostRequest::OrientCamera(CameraOrientRequest { .. }));
ctx.request(HostRequest::FinishEditing);
ctx.request(HostRequest::SaveFile { name, kind, extension, contents });
ctx.request(HostRequest::RecordAnimation { name, frames, frame_ms });

SelectFeatures selects several tree rows as Ctrl-clicks would, the first the active document object. RecordAnimation asks where to save and writes the scene as the camera sees it, once per frame with the bodies at that frame's placements. CloseToolGesture closes the undo step now and UndoToolGesture takes back entry only while it is the newest step; the answer comes back at once through tool_history (ToolHistoryReply), and ctx.undo_entry is the newest step at every hook.

The host applies requests after the method returns, collected with everything else the hook left (HookOutcome). Requests from on_activate and on_deactivate that switch workbench are ignored, since those run during a switch. StartOn switches workbench and passes attach to the new one as ctx.attach_request.

11. Draw panels

task, floating_card, card_event and the settings methods are in BenchPanels; viewport and cancel_pointer_gesture in BenchTools; on_frame, suspend_session, resume_session and busy on Workbench.

Checklist

  1. descriptor with icon and feature_kinds, and a test that the icons exist.
  2. configure with the tools and their default keys, and is_tool_enabled where tools have preconditions.
  3. feature_info, plus passive_geometry, pick_feature, delete_feature, property_hints, references and set_reference as needed, and parameters for the numbers formulas may set.
  4. rebuild_jobs, invalidate_body and invalidate_all if it builds solids.
  5. on_input for the tools.
  6. edit_feature, editing_feature, task and ui_task_panel for editing, suspend_session/resume_session for per-tab state, has_settings and ui_settings for preferences.
  7. menu_items and on_command for menus and start cards.
  8. A CommandTable registered in configure and run in run_command for what scripts can do, and register_import for files it reads.
  9. Registration in crates/workbenches/src/lib.rs.

crates/app_shell/src/app/seam_lint.rs fails if a workbench crate, id or feature type appears in the application, and CI checks the same. The application builds parts from workbench features only through the facade (crates/workbenches, the calibration coupon) and, for its bench hooks, bench_fixtures (crates/workbenches/fixtures).

Adding to printCAD: the files each addition touches

Every addition ends with tests that measure what it made at its strongest boundary (a solid's volume, area and bounds; a sketch's closure; a placement), not the code's inner steps, and with fmt, clippy, node scripts/test-budget.mjs --changed and lint-comment-rot.mjs passing.

A Design feature

  1. wb_design/src/feature/: the DesignFeature variant and its new fields with #[serde(default)] (mod.rs), its icon and label (labels.rs), and its arms in the walks over features (access.rs: sketches and borrows it reads, refine, boolean_tolerance).
  2. wb_design/src/build.rs: the SolidOps it plans, in the body's frame.
  3. wb_design/src/params.rs and references.rs: the numbers formulas may set, and the inputs the property panel swaps.
  4. wb_design/src/editors.rs (or a file under editors/): its task panel; handles.rs if it drags in the view.
  5. wb_design/src/lib.rs: the tool (ToolDescriptor, icon, row, key); commands.rs: its design.* command, with notes and an example ending in asserts.
  6. A new kind of solid work: a SolidOp variant in kernel_api, built in kernel_ogeom/src/ops/ and dispatched in kernel_ogeom/src/chain.rs.
  7. Tests: the full stack in kernel_ogeom/tests/kernel/design_stack.rs or scripted_design.rs, measuring the solid.
  8. PRINTCAD_WRITE_DOCS=1 cargo test -p app_shell scripting_guide to bring the command reference in docs/SCRIPTING.md up to date, and a line in the bench's guide.

A command of the application's own

  1. Its CommandSpec in app_shell/src/app/scripts.rs (doc_commands or app_commands), with read_only and the agent access it needs.
  2. Its arm: document_command when it needs only the document (headless runs it too, listed in DOC_COMMANDS in headless.rs), otherwise the app's dispatch.
  3. An example; the generated reference as above.

A UI action

  1. One variant in app_ui/src/contract/commands.rs and one arm in app/commands.rs::fold_command. A change to settings alone needs no variant: push UiCommand::EditSettings(SettingsEdit::set(..)).
  2. A keymap entry in app_ui/src/keymap.rs when it takes a key, which also makes it a command.

A host request a bench may make

  1. The HostRequest variant in core_document/src/runtime.rs, with its place in rank.
  2. Its arm in app/workbench_host.rs::apply_hook_outcome.
  3. For packages: the bench_api::Request variant, its conversion in wb_wasm/src/convert.rs, and the capability it needs.

A field of the package contract

  1. bench_api: a field with #[serde(default)], or a new variant; never a new field on a variant a package builds (see docs/PLUGINS.md, Versions).
  2. A new host function: both WIT copies (crates/bench_api/wit and sdk/printcad-bench-sdk/wit, which a test holds equal), its arm in wb_wasm/src/guest.rs, and the SDK's host wrapper.
  3. The probe or rogue package under sdk/tests/ exercising it, and a test in wb_wasm/tests/packages.rs.

This page's source