Skip to main content

printcad_bench_sdk/
lib.rs

1//! Write a printCAD workbench as a WebAssembly component.
2//!
3//! Implement [`Bench`] on a type and name it with [`bench!`]; build the
4//! crate as a `cdylib` for `wasm32-wasip2`. The data the bench and the
5//! app exchange is [`api`] (the `printcad-bench-api` crate); what the app offers
6//! is [`host`]. `docs/PLUGINS.md` in the printCAD repository walks
7//! through a package.
8//!
9//! The SDK's 0.1.x speaks the contract `printcad:workbench@0.1`, and a
10//! patch release only adds: match the app's events with a wildcard arm
11//! and fill the contract's structs with `..Default::default()`, and a
12//! package keeps building on every later 0.1.x.
13//!
14//! ```ignore
15//! use printcad_bench_sdk::{Bench, api::*, bench};
16//!
17//! #[derive(Default)]
18//! struct Hello;
19//!
20//! impl Bench for Hello {
21//!     fn describe(&self) -> Registration {
22//!         Registration { label: "Hello".into(), ..Default::default() }
23//!     }
24//! }
25//!
26//! bench!(Hello);
27//! ```
28
29pub use bench_api as api;
30pub use serde_json::{self, Value, json};
31
32pub mod panel;
33
34use api::*;
35
36#[doc(hidden)]
37pub mod bindings {
38    wit_bindgen::generate!({
39        world: "workbench",
40        path: "wit",
41        pub_export_macro: true,
42        export_macro_name: "export_workbench",
43        default_bindings_module: "printcad_bench_sdk::bindings",
44    });
45}
46
47/// A workbench. Every method has a default, so a bench implements what it
48/// offers. One value of it lives in the bench's instance for as long as
49/// the app runs; a job runs in an instance of its own, through
50/// [`Bench::job`].
51pub trait Bench: Default + 'static {
52    /// What the bench is: label, icon, tools, actions, commands.
53    fn describe(&self) -> Registration;
54
55    /// How a feature of one of the package's kinds shows in the tree.
56    fn feature_info(&self, node: &Node) -> FeatureInfo {
57        FeatureInfo {
58            kind_label: node.kind.clone(),
59            builds_solid: true,
60            ..Default::default()
61        }
62    }
63
64    /// The numbers of a feature that formulas may set.
65    fn parameters(&self, _node: &Node) -> Vec<Parameter> {
66        Vec::new()
67    }
68
69    /// A feature's data made whole once formulas' values are in it.
70    fn settle(&self, node: &Node) -> Value {
71        node.data.clone()
72    }
73
74    /// Plans for the bodies whose features changed.
75    fn rebuild(&mut self, _request: RebuildRequest) -> Vec<Rebuild> {
76        Vec::new()
77    }
78
79    /// A command the bench registered. Edits go through [`host::call`].
80    fn run_command(&mut self, id: &str, _args: Value) -> Result<Value, String> {
81        Err(format!("no command `{id}`"))
82    }
83
84    /// Something the user did while the bench is active; `true` when it
85    /// was used.
86    fn input(&mut self, _input: &Input) -> bool {
87        false
88    }
89
90    /// Everything the bench shows. Asked after events, document and
91    /// selection changes, and after [`host::redraw`].
92    fn frame(&mut self, _pointer: &Pointer) -> Frame {
93        Frame::default()
94    }
95
96    /// A change to a widget of the task panel, the settings page, the
97    /// strip under the view or the floating card (`Frame::card`), whose
98    /// OK and Cancel come as `PanelEvent::CardClose`.
99    fn panel_event(&mut self, _slot: PanelSlot, _event: PanelEvent) {}
100
101    /// The task's OK (`true`) or Cancel; the undo step's name when it
102    /// closed keeping its edits.
103    fn task_close(&mut self, _accept: bool) -> Option<String> {
104        None
105    }
106
107    fn menu_items(&mut self, _scope: &MenuScope) -> Vec<MenuItem> {
108        Vec::new()
109    }
110
111    fn menu_command(&mut self, _id: &str, _scope: &MenuScope) -> bool {
112        false
113    }
114
115    /// Remove an owned feature itself; `false` leaves it to the app.
116    fn delete_feature(&mut self, _id: &str) -> bool {
117        false
118    }
119
120    /// The bench's Preferences page.
121    fn settings_panel(&mut self) -> Vec<Widget> {
122        Vec::new()
123    }
124
125    /// The bench's settings, for the app to keep.
126    fn settings(&self) -> Option<Value> {
127        None
128    }
129
130    fn apply_settings(&mut self, _settings: Value) {}
131
132    /// The editing state of the document on screen, kept with its tab.
133    fn suspend(&mut self) -> Option<Vec<u8>> {
134        None
135    }
136
137    fn resume(&mut self, _state: Option<Vec<u8>>) {}
138
139    /// Long work, started with [`host::start_job`], run in an instance of
140    /// its own away from the window. It reaches no document; it reports
141    /// with [`host::progress`] and stops when [`host::cancelled`].
142    fn job(_entry: &str, _input: &str) -> Result<String, String> {
143        Err("this bench has no jobs".into())
144    }
145}
146
147/// What the app offers a bench.
148pub mod host {
149    use super::bindings::printcad::workbench::host as raw;
150    use super::*;
151
152    pub fn info(message: &str) {
153        raw::log("info", message);
154    }
155
156    pub fn warn(message: &str) {
157        raw::log("warn", message);
158    }
159
160    pub fn error(message: &str) {
161        raw::log("error", message);
162    }
163
164    /// A feature, with its formulas' values in its data.
165    pub fn feature(id: &str) -> Option<Node> {
166        serde_json::from_str(&raw::feature(id)?).ok()
167    }
168
169    /// Every feature of the document, in history order.
170    pub fn features() -> Vec<Node> {
171        serde_json::from_str(&raw::features()).unwrap_or_default()
172    }
173
174    pub fn bodies() -> Vec<Body> {
175        serde_json::from_str(&raw::bodies()).unwrap_or_default()
176    }
177
178    /// A body's triangles in world space.
179    pub fn body_mesh(body: &str) -> Option<(Vec<[f32; 3]>, Vec<u32>)> {
180        let mesh = raw::body_mesh(body)?;
181        let positions = mesh.positions.as_chunks::<3>().0.to_vec();
182        Some((positions, mesh.indices))
183    }
184
185    /// A body's solid in the kernel's native format.
186    pub fn body_shape(body: &str) -> Option<Vec<u8>> {
187        raw::body_shape(body)
188    }
189
190    /// A feature's closed loops (a sketch's) placed in world space: the
191    /// plane, then the loops, holes inside their outlines. `None` when it
192    /// closes no area.
193    pub fn profile(feature: &str) -> Option<api::kernel_api::Profile> {
194        serde_json::from_str(&raw::profile(feature)?).ok()
195    }
196
197    /// Run a document command (`api::calls`).
198    pub fn call(command: &str, args: Value) -> Result<Value, String> {
199        let answer = raw::call(command, &args.to_string())?;
200        serde_json::from_str(&answer).map_err(|e| e.to_string())
201    }
202
203    pub fn request(request: Request) {
204        if let Ok(json) = serde_json::to_string(&request) {
205            raw::request(&json);
206        }
207    }
208
209    /// Ask for the frame again.
210    pub fn redraw() {
211        raw::redraw();
212    }
213
214    /// Add a feature of an owned kind; its id.
215    pub fn add_feature(
216        kind: &str,
217        name: &str,
218        body: Option<&str>,
219        data: Value,
220    ) -> Result<String, String> {
221        let answer = call(
222            calls::ADD_FEATURE,
223            json!({"kind": kind, "name": name, "body": body, "data": data}),
224        )?;
225        answer
226            .as_str()
227            .map(str::to_string)
228            .ok_or_else(|| "no id came back".into())
229    }
230
231    pub fn set_feature_data(id: &str, data: Value) -> Result<(), String> {
232        call(calls::SET_FEATURE_DATA, json!({"id": id, "data": data})).map(|_| ())
233    }
234
235    pub fn remove_feature(id: &str) -> Result<(), String> {
236        call(calls::REMOVE_FEATURE, json!({"id": id})).map(|_| ())
237    }
238
239    /// Remove a body that holds nothing of another package's and takes no
240    /// shape from an import, a link or a copy: the empty body a cancelled
241    /// part leaves (its removal undoes), or one of the package's own parts.
242    pub fn remove_body(id: &str) -> Result<(), String> {
243        call(calls::REMOVE_BODY, json!({"id": id})).map(|_| ())
244    }
245
246    /// A new body; its id.
247    pub fn create_body(name: Option<&str>) -> Result<String, String> {
248        let answer = call(calls::CREATE_BODY, json!({"name": name}))?;
249        answer
250            .as_str()
251            .map(str::to_string)
252            .ok_or_else(|| "no id came back".into())
253    }
254
255    /// Start [`Bench::job`] with `entry` and `input`; its number, which
256    /// `Event::JobFinished` names when it ends.
257    pub fn start_job(entry: &str, input: &str) -> Result<u64, String> {
258        call(calls::JOB_START, json!({"entry": entry, "input": input}))?
259            .as_u64()
260            .ok_or_else(|| "no job number came back".into())
261    }
262
263    pub fn cancel_job(job: u64) {
264        let _ = call(calls::JOB_CANCEL, json!({ "job": job }));
265    }
266
267    /// Inside a job: how far it is.
268    pub fn progress(done: u64, total: u64) {
269        raw::progress(done, total);
270    }
271
272    /// Inside a job: whether the user stopped it.
273    pub fn cancelled() -> bool {
274        raw::cancelled()
275    }
276
277    /// Inside a job, with the `helper` capability: run a native helper.
278    /// It reads `input` on its standard input and answers on its
279    /// standard output. A `progress <done> <total>` line on its
280    /// standard error moves the job's bar while it runs.
281    pub fn helper(name: &str, input: &[u8]) -> Result<Vec<u8>, String> {
282        raw::helper(name, input)
283    }
284
285    /// With the `helper` capability: start a native helper and keep it
286    /// running to talk to a line at a time; its handle. It ends when
287    /// closed, when the job that opened it ends, or with the package's
288    /// instance.
289    pub fn helper_open(name: &str) -> Result<u64, String> {
290        raw::helper_open(name)
291    }
292
293    /// Send a session's helper one line (no line break in it).
294    pub fn helper_send(handle: u64, line: &str) -> Result<(), String> {
295        raw::helper_send(handle, line)
296    }
297
298    /// The helper's next line: waiting up to `wait_ms` for it inside a
299    /// job, not at all outside one; `None` when none came. An error once
300    /// the helper has ended.
301    pub fn helper_receive(handle: u64, wait_ms: u32) -> Result<Option<String>, String> {
302        raw::helper_receive(handle, wait_ms)
303    }
304
305    pub fn helper_close(handle: u64) {
306        raw::helper_close(handle);
307    }
308
309    /// Keep a mesh for frames to draw by its handle (`Frame::kept`), with
310    /// a colour per position or none.
311    pub fn mesh_create(
312        positions: &[[f32; 3]],
313        indices: &[u32],
314        colors: &[[f32; 3]],
315    ) -> Result<u64, String> {
316        raw::mesh_create(positions.as_flattened(), indices, colors.as_flattened())
317    }
318
319    /// Replace a kept mesh's positions from `first` on, and their colours
320    /// when as many are given.
321    pub fn mesh_update(
322        handle: u64,
323        first: u32,
324        positions: &[[f32; 3]],
325        colors: &[[f32; 3]],
326    ) -> Result<(), String> {
327        raw::mesh_update(
328            handle,
329            first,
330            positions.as_flattened(),
331            colors.as_flattened(),
332        )
333    }
334
335    pub fn mesh_remove(handle: u64) {
336        raw::mesh_remove(handle);
337    }
338}
339
340/// A grid of heights kept as a mesh (simulated material, a terrain):
341/// `cols` × `rows` points `pitch` apart in x and y from `origin`, each
342/// raised by its height, two triangles a cell. Draw it with its
343/// [`handle`](Self::handle) in `Frame::kept`; [`update`](Self::update)
344/// sends only the rectangle that changed.
345pub struct HeightField {
346    handle: u64,
347    origin: [f32; 3],
348    cols: u32,
349    rows: u32,
350    pitch: f32,
351}
352
353impl HeightField {
354    /// A field of `heights`, row by row from `origin`, and a colour per
355    /// point or none.
356    pub fn new(
357        origin: [f32; 3],
358        cols: u32,
359        rows: u32,
360        pitch: f32,
361        heights: &[f32],
362        colors: &[[f32; 3]],
363    ) -> Result<Self, String> {
364        if cols < 2 || rows < 2 || heights.len() != (cols * rows) as usize {
365            return Err("a field has at least 2 × 2 points and a height for each".into());
366        }
367        let field = |handle| Self {
368            handle,
369            origin,
370            cols,
371            rows,
372            pitch,
373        };
374        let shape = field(0);
375        let positions: Vec<[f32; 3]> = (0..rows)
376            .flat_map(|r| (0..cols).map(move |c| (c, r)))
377            .zip(heights)
378            .map(|((c, r), h)| shape.point(c, r, *h))
379            .collect();
380        let mut indices = Vec::with_capacity(((cols - 1) * (rows - 1) * 6) as usize);
381        for r in 0..rows - 1 {
382            for c in 0..cols - 1 {
383                let at = r * cols + c;
384                indices.extend([at, at + 1, at + cols, at + 1, at + cols + 1, at + cols]);
385            }
386        }
387        host::mesh_create(&positions, &indices, colors).map(field)
388    }
389
390    pub fn handle(&self) -> u64 {
391        self.handle
392    }
393
394    fn point(&self, col: u32, row: u32, height: f32) -> [f32; 3] {
395        [
396            self.origin[0] + col as f32 * self.pitch,
397            self.origin[1] + row as f32 * self.pitch,
398            self.origin[2] + height,
399        ]
400    }
401
402    /// New heights (and colours, or none) for the `width` × `height`
403    /// points from `col`, `row`, row by row.
404    pub fn update(
405        &self,
406        col: u32,
407        row: u32,
408        width: u32,
409        height: u32,
410        heights: &[f32],
411        colors: &[[f32; 3]],
412    ) -> Result<(), String> {
413        if col + width > self.cols
414            || row + height > self.rows
415            || heights.len() != (width * height) as usize
416            || !(colors.is_empty() || colors.len() == heights.len())
417        {
418            return Err("the rectangle and its heights fit the field".into());
419        }
420        for r in 0..height {
421            let line = (r * width) as usize..((r + 1) * width) as usize;
422            let positions: Vec<[f32; 3]> = (0..width)
423                .zip(&heights[line.clone()])
424                .map(|(c, h)| self.point(col + c, row + r, *h))
425                .collect();
426            let colors = if colors.is_empty() {
427                &[][..]
428            } else {
429                &colors[line]
430            };
431            host::mesh_update(self.handle, (row + r) * self.cols + col, &positions, colors)?;
432        }
433        Ok(())
434    }
435}
436
437impl Drop for HeightField {
438    fn drop(&mut self) {
439        host::mesh_remove(self.handle);
440    }
441}
442
443#[doc(hidden)]
444pub mod adapter {
445    use std::any::Any;
446    use std::cell::RefCell;
447
448    use super::bindings::exports::printcad::workbench::bench::Guest;
449    use super::*;
450
451    thread_local! {
452        static BENCH: RefCell<Option<Box<dyn Any>>> = const { RefCell::new(None) };
453    }
454
455    fn with<B: Bench, R>(f: impl FnOnce(&mut B) -> R) -> R {
456        BENCH.with(|cell| {
457            let mut slot = cell.borrow_mut();
458            let bench = slot.get_or_insert_with(|| Box::new(B::default()));
459            f(bench.downcast_mut::<B>().expect("one bench per component"))
460        })
461    }
462
463    /// A value the app sent. A kind of event or menu this build of the SDK
464    /// does not know comes from a newer app within the same contract, and
465    /// passes the bench by unread.
466    fn read<T: serde::de::DeserializeOwned>(json: &str) -> Option<T> {
467        match serde_json::from_str(json) {
468            Ok(value) => Some(value),
469            Err(e) if e.to_string().starts_with("unknown variant") => None,
470            Err(e) => {
471                host::error(&format!("the app sent what this bench cannot read: {e}"));
472                None
473            }
474        }
475    }
476
477    fn write<T: serde::Serialize>(value: &T) -> String {
478        serde_json::to_string(value).unwrap_or_default()
479    }
480
481    /// The component's exports, forwarded to `B`.
482    pub struct Exports<B>(std::marker::PhantomData<B>);
483
484    impl<B: Bench> Guest for Exports<B> {
485        fn describe() -> String {
486            with::<B, _>(|b| write(&b.describe()))
487        }
488
489        fn feature_info(node: String) -> String {
490            match read::<Node>(&node) {
491                Some(node) => with::<B, _>(|b| write(&b.feature_info(&node))),
492                None => String::new(),
493            }
494        }
495
496        fn parameters(node: String) -> String {
497            match read::<Node>(&node) {
498                Some(node) => with::<B, _>(|b| write(&b.parameters(&node))),
499                None => "[]".into(),
500            }
501        }
502
503        fn settle(node: String) -> String {
504            match read::<Node>(&node) {
505                Some(node) => with::<B, _>(|b| write(&b.settle(&node))),
506                None => String::new(),
507            }
508        }
509
510        fn rebuild(request: String) -> String {
511            match read::<RebuildRequest>(&request) {
512                Some(request) => with::<B, _>(|b| write(&b.rebuild(request))),
513                None => "[]".into(),
514            }
515        }
516
517        fn run_command(id: String, args: String) -> Result<String, String> {
518            let args: Value = serde_json::from_str(&args).unwrap_or(Value::Null);
519            with::<B, _>(|b| b.run_command(&id, args)).map(|v| v.to_string())
520        }
521
522        fn input(input: String) -> bool {
523            match read::<Input>(&input) {
524                Some(input) => with::<B, _>(|b| b.input(&input)),
525                None => false,
526            }
527        }
528
529        fn frame(pointer: String) -> String {
530            let pointer = read::<Pointer>(&pointer).unwrap_or_default();
531            with::<B, _>(|b| write(&b.frame(&pointer)))
532        }
533
534        fn panel_event(slot: String, event: String) {
535            let slot = match slot.as_str() {
536                "settings" => PanelSlot::Settings,
537                "transport" => PanelSlot::Transport,
538                "card" => PanelSlot::Card,
539                _ => PanelSlot::Task,
540            };
541            if let Some(event) = read::<PanelEvent>(&event) {
542                with::<B, _>(|b| b.panel_event(slot, event));
543            }
544        }
545
546        fn task_close(accept: bool) -> Option<String> {
547            with::<B, _>(|b| b.task_close(accept))
548        }
549
550        fn menu_items(scope: String) -> String {
551            match read::<MenuScope>(&scope) {
552                Some(scope) => with::<B, _>(|b| write(&b.menu_items(&scope))),
553                None => "[]".into(),
554            }
555        }
556
557        fn menu_command(id: String, scope: String) -> bool {
558            match read::<MenuScope>(&scope) {
559                Some(scope) => with::<B, _>(|b| b.menu_command(&id, &scope)),
560                None => false,
561            }
562        }
563
564        fn delete_feature(id: String) -> bool {
565            with::<B, _>(|b| b.delete_feature(&id))
566        }
567
568        fn settings_panel() -> String {
569            with::<B, _>(|b| write(&b.settings_panel()))
570        }
571
572        fn settings() -> Option<String> {
573            with::<B, _>(|b| b.settings()).map(|v| v.to_string())
574        }
575
576        fn apply_settings(settings: String) {
577            if let Ok(value) = serde_json::from_str(&settings) {
578                with::<B, _>(|b| b.apply_settings(value));
579            }
580        }
581
582        fn suspend() -> Option<Vec<u8>> {
583            with::<B, _>(|b| b.suspend())
584        }
585
586        fn resume(state: Option<Vec<u8>>) {
587            with::<B, _>(|b| b.resume(state));
588        }
589
590        fn job_run(entry: String, input: String) -> Result<String, String> {
591            B::job(&entry, &input)
592        }
593    }
594}
595
596/// Make `$bench` (a [`Bench`]) the component's workbench.
597#[macro_export]
598macro_rules! bench {
599    ($bench:ty) => {
600        type __PrintcadBenchExports = $crate::adapter::Exports<$bench>;
601        $crate::bindings::export_workbench!(__PrintcadBenchExports with_types_in $crate::bindings);
602    };
603}