Skip to main content

standard_plugin/
lib.rs

1//! Write Standard Code plugins in Rust.
2//!
3//! Every plugin is a wasm component against the WIT package
4//! `standard:plugin@2.0.0`, built for `wasm32-wasip2`. This crate wraps the
5//! generated bindings in a safe API:
6//!
7//! - **UI plugins** ([`UiPlugin`], [`#[ui]`](macro@ui)) run in every viewer and paint
8//!   [`Surface`]s in the cell model ([`Cells`]) or the graphics model
9//!   ([`Pixels`]). They are side-effect free: effects that must happen once
10//!   go through [`claims`](mod@claims) or a companion daemon ([`calls`](mod@calls)), and
11//!   [`view::is_driving`] says whether the user is controlling this viewer.
12//! - **Daemon plugins** ([`daemon::DaemonPlugin`], [`#[daemon]`](macro@daemon))
13//!   run inside `standardd` with an async `run` loop on a small executor.
14//!
15//! The account interfaces ([`values`](mod@values), [`live`](mod@live), [`events`](mod@events), [`calls`](mod@calls),
16//! [`config`](mod@config), [`secrets`](mod@secrets), [`account`](mod@account)) are shared by both. Every call the
17//! plugin's manifest grants do not cover returns [`Error::GrantDenied`].
18//!
19//! A UI plugin is `#![no_std]` (the `std` library would import the WASI CLI
20//! world, which a viewer does not offer); `alloc` is available and this
21//! crate's default `runtime` feature supplies the allocator and panic
22//! handler. A UI plugin, in full:
23//!
24//! ```rust,ignore
25#![doc = include_str!("../examples/clock_card.rs")]
26//! ```
27//!
28//! More: the [`guide`] pages (the same Markdown files are this crate's
29//! `docs/` directory, and `standard-plugin guide` prints them), and the
30//! compiled examples in this crate's `examples/` directory. `testing` (on
31//! non-wasm targets) runs a plugin against an in-process host in ordinary
32//! `cargo test`.
33#![no_std]
34
35extern crate alloc;
36#[cfg(any(feature = "std", not(target_arch = "wasm32")))]
37extern crate std;
38
39#[cfg(target_endian = "big")]
40compile_error!("the shared surface buffer is little-endian");
41
42mod bindings;
43mod colour;
44mod error;
45mod geometry;
46mod host;
47mod input;
48mod local;
49#[cfg(all(target_arch = "wasm32", not(feature = "std")))]
50mod runtime;
51mod ui_runtime;
52
53pub mod api;
54pub mod daemon;
55pub mod draw;
56pub mod embed;
57pub mod links;
58pub mod surface;
59#[cfg(not(target_arch = "wasm32"))]
60pub mod testing;
61
62pub use api::{
63    Json, Target, account, calls, capabilities, claims, config, events, health, live, secrets, url,
64    values, view,
65};
66pub use colour::{Attrs, Colour, Rgba, Style, ThemeSlot, recede};
67pub use draw::{Area, Image, Shapes, font};
68pub use error::{Error, Result};
69pub use geometry::{Geometry, Rect};
70pub use input::{Button, Key, KeyCode, KeyPhase, Modifiers, Pointer, PointerKind};
71pub use surface::{AnySurface, AnySurfaceMut, Cell, Cells, Instances, Pixels, Surface};
72pub use ui_runtime::{Context, Event, Frame, Power, UiPlugin};
73
74/// Exports the annotated type, which implements [`UiPlugin`], as the
75/// component's `ui-plugin` world. Put it on the plugin's struct or enum, or
76/// on its `impl UiPlugin for ...` block; once per plugin crate.
77pub use standard_plugin_macros::ui;
78
79/// Exports the annotated type, which implements [`daemon::DaemonPlugin`],
80/// as the component's `daemon-plugin` world.
81pub use standard_plugin_macros::daemon;
82
83/// Floating-point maths for `no_std` plugins (`libm::sinf`, `sqrtf`, ...):
84/// `core` has no `f32::sin`.
85pub use libm;
86
87/// What most plugins import: `use standard_plugin::prelude::*;`.
88pub mod prelude {
89    pub use crate::daemon::DaemonPlugin;
90    pub use crate::{
91        AnySurface, Area, Attrs, Button, Cells, Colour, Context, Error, Event, Frame, Geometry,
92        Instances, Json, Key, KeyCode, Modifiers, Pixels, Pointer, PointerKind, Rect, Rgba, Shapes,
93        Style, Surface, Target, ThemeSlot, UiPlugin,
94    };
95    pub use alloc::borrow::ToOwned;
96    pub use alloc::boxed::Box;
97    pub use alloc::format;
98    pub use alloc::string::{String, ToString};
99    pub use alloc::vec;
100    pub use alloc::vec::Vec;
101}
102
103/// The sources this SDK version is built from, for tools: the
104/// `standard-plugin` CLI checks components against [`sources::WIT`] and
105/// scaffolds new plugins from the examples, so both always match the SDK
106/// the new plugin depends on.
107pub mod sources {
108    /// The WIT package `standard:plugin@2.0.0` (`wit/plugin.wit`): the one
109    /// copy the SDK bindings, the viewer and daemon hosts and the CLI use.
110    pub const WIT: &str = include_str!("../wit/plugin.wit");
111
112    /// The compiled examples `standard-plugin new` starts from.
113    pub mod examples {
114        /// A cell-model sidebar card (`examples/clock_card.rs`).
115        pub const CLOCK_CARD: &str = include_str!("../examples/clock_card.rs");
116        /// A daemon plugin (`examples/heartbeat_daemon.rs`).
117        pub const HEARTBEAT_DAEMON: &str = include_str!("../examples/heartbeat_daemon.rs");
118        /// The UI half of a companion pair (`examples/together_ui.rs`).
119        pub const TOGETHER_UI: &str = include_str!("../examples/together_ui.rs");
120        /// The companion daemon (`examples/together_companion.rs`).
121        pub const TOGETHER_COMPANION: &str = include_str!("../examples/together_companion.rs");
122    }
123
124    /// One guide of this SDK version: its name, the file stem in `docs/`
125    /// (`standard-plugin guide <name>`), and its Markdown text.
126    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
127    pub struct Guide {
128        pub name: &'static str,
129        pub text: &'static str,
130    }
131
132    impl Guide {
133        /// The text of its first heading, else its name.
134        #[must_use]
135        pub fn title(&self) -> &'static str {
136            self.text
137                .lines()
138                .next()
139                .and_then(|line| line.strip_prefix("# "))
140                .unwrap_or(self.name)
141        }
142    }
143
144    /// Every guide in this crate's `docs/` directory, in reading order,
145    /// the index first ([`crate::guide`] shows the same pages).
146    pub const GUIDES: &[Guide] = &[
147        Guide {
148            name: "README",
149            text: include_str!("../docs/README.md"),
150        },
151        Guide {
152            name: "getting-started",
153            text: include_str!("../docs/getting-started.md"),
154        },
155        Guide {
156            name: "agent-guide",
157            text: include_str!("../docs/agent-guide.md"),
158        },
159        Guide {
160            name: "manifest",
161            text: include_str!("../docs/manifest.md"),
162        },
163        Guide {
164            name: "grants",
165            text: include_str!("../docs/grants.md"),
166        },
167        Guide {
168            name: "rendering",
169            text: include_str!("../docs/rendering.md"),
170        },
171        Guide {
172            name: "input",
173            text: include_str!("../docs/input.md"),
174        },
175        Guide {
176            name: "handlers",
177            text: include_str!("../docs/handlers.md"),
178        },
179        Guide {
180            name: "previews",
181            text: include_str!("../docs/previews.md"),
182        },
183        Guide {
184            name: "working-together",
185            text: include_str!("../docs/working-together.md"),
186        },
187        Guide {
188            name: "daemon-plugins",
189            text: include_str!("../docs/daemon-plugins.md"),
190        },
191        Guide {
192            name: "testing",
193            text: include_str!("../docs/testing.md"),
194        },
195        Guide {
196            name: "publishing",
197            text: include_str!("../docs/publishing.md"),
198        },
199        Guide {
200            name: "abi",
201            text: include_str!("../docs/abi.md"),
202        },
203        Guide {
204            name: "other-languages",
205            text: include_str!("../docs/other-languages.md"),
206        },
207    ];
208}
209
210/// The guides, as pages of this documentation. The same Markdown files are
211/// this crate's `docs/` directory, where links between guides resolve, and
212/// `standard-plugin guide` prints them for the SDK version a plugin's
213/// `Cargo.lock` resolves.
214pub mod guide {
215    #[doc = include_str!("../docs/README.md")]
216    pub mod index {}
217    #[doc = include_str!("../docs/getting-started.md")]
218    pub mod getting_started {}
219    #[doc = include_str!("../docs/agent-guide.md")]
220    pub mod agent_guide {}
221    #[doc = include_str!("../docs/manifest.md")]
222    pub mod manifest {}
223    #[doc = include_str!("../docs/grants.md")]
224    pub mod grants {}
225    #[doc = include_str!("../docs/rendering.md")]
226    pub mod rendering {}
227    #[doc = include_str!("../docs/input.md")]
228    pub mod input {}
229    #[doc = include_str!("../docs/handlers.md")]
230    pub mod handlers {}
231    #[doc = include_str!("../docs/previews.md")]
232    pub mod previews {}
233    #[doc = include_str!("../docs/working-together.md")]
234    pub mod working_together {}
235    #[doc = include_str!("../docs/daemon-plugins.md")]
236    pub mod daemon_plugins {}
237    #[doc = include_str!("../docs/testing.md")]
238    pub mod testing {}
239    #[doc = include_str!("../docs/publishing.md")]
240    pub mod publishing {}
241    #[doc = include_str!("../docs/abi.md")]
242    pub mod abi {}
243    #[doc = include_str!("../docs/other-languages.md")]
244    pub mod other_languages {}
245}
246
247/// Used by the export macros; not part of the public API.
248#[doc(hidden)]
249pub mod __private {
250    pub use crate::bindings::{daemon as daemon_bindings, ui as ui_bindings};
251    pub use crate::daemon::runtime::DaemonRuntime;
252    pub use crate::ui_runtime::UiRuntime;
253    pub use alloc::string::String;
254}
255
256/// Exports a [`UiPlugin`] type; `#[standard_plugin::ui]` expands to this.
257#[doc(hidden)]
258#[macro_export]
259macro_rules! __export_ui {
260    ($plugin:ty) => {
261        const _: () = {
262            static RUNTIME: $crate::__private::UiRuntime<$plugin> =
263                $crate::__private::UiRuntime::new();
264
265            struct Export;
266
267            impl $crate::__private::ui_bindings::Guest for Export {
268                fn activate(config: $crate::__private::String) {
269                    RUNTIME.activate(config);
270                }
271
272                fn frame(
273                    now_ms: u64,
274                    interval_ms: u32,
275                    power: $crate::__private::ui_bindings::Power,
276                ) -> Option<u64> {
277                    RUNTIME.frame(now_ms, interval_ms, power.into())
278                }
279
280                fn event(event: $crate::__private::ui_bindings::Event) {
281                    RUNTIME.event(event.into());
282                }
283
284                fn deactivate() {
285                    RUNTIME.deactivate();
286                }
287            }
288
289    $crate::__export_ui_plugin_impl!(Export with_types_in $crate::__private::ui_bindings);
290        };
291    };
292}
293
294/// Exports a [`daemon::DaemonPlugin`] type; `#[standard_plugin::daemon]`
295/// expands to this.
296#[doc(hidden)]
297#[macro_export]
298macro_rules! __export_daemon {
299    ($plugin:ty) => {
300        const _: () = {
301            static RUNTIME: $crate::__private::DaemonRuntime<$plugin> =
302                $crate::__private::DaemonRuntime::new();
303
304            struct Export;
305
306            impl $crate::__private::daemon_bindings::Guest for Export {
307                fn activate(config: $crate::__private::String) {
308                    RUNTIME.activate(config);
309                }
310
311                fn event(event: $crate::__private::daemon_bindings::Event) {
312                    RUNTIME.event(event.into());
313                }
314
315                fn drive(now_ms: u64) -> Option<u64> {
316                    RUNTIME.drive(now_ms)
317                }
318
319                fn deactivate() {
320                    RUNTIME.deactivate();
321                }
322            }
323
324            impl $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::Guest
325                for Export
326            {
327                fn handle_event(
328                    event: $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::DaemonEvent,
329                ) {
330                    RUNTIME.event(event.into());
331                }
332            }
333
334            impl $crate::__private::daemon_bindings::exports::standard::plugin::companion::Guest
335                for Export
336            {
337                fn handle_call(
338                    method: $crate::__private::String,
339                    payload: $crate::__private::String,
340                    from: $crate::__private::daemon_bindings::exports::standard::plugin::companion::Caller,
341                ) -> Result<
342                    $crate::__private::String,
343                    $crate::__private::ui_bindings::standard::plugin::types::CallError,
344                > {
345                    RUNTIME
346                        .handle_call(&method, payload, from.into())
347                        .map_err(Into::into)
348                }
349            }
350
351            // Only a component exports. Natively, interface exports are
352            // `<interface>#<function>` symbols, and `#` starts a comment in
353            // the macOS linker's exported-symbols list.
354            #[cfg(target_family = "wasm")]
355            $crate::__export_daemon_plugin_impl!(
356                Export with_types_in $crate::__private::daemon_bindings
357            );
358
359            // A native build (tests, `cargo check`) still uses the plugin
360            // through the same entry points.
361            #[cfg(not(target_family = "wasm"))]
362            #[allow(dead_code)]
363            fn native_entry_points() {
364                use $crate::__private::daemon_bindings::Guest as _;
365                use $crate::__private::daemon_bindings::exports::standard::plugin::companion::Guest as _;
366                use $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::Guest as _;
367                let _ = (
368                    Export::activate,
369                    Export::event,
370                    Export::handle_event,
371                    Export::drive,
372                    Export::deactivate,
373                    Export::handle_call,
374                );
375            }
376        };
377    };
378}