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::{
72    AgentPointer, AnySurface, AnySurfaceMut, Cell, Cells, Instances, Pixels, Scroll, Surface,
73    Viewport,
74};
75pub use ui_runtime::{Context, Event, Frame, Power, UiPlugin};
76
77/// Exports the annotated type, which implements [`UiPlugin`], as the
78/// component's `ui-plugin` world. Put it on the plugin's struct or enum, or
79/// on its `impl UiPlugin for ...` block; once per plugin crate.
80pub use standard_plugin_macros::ui;
81
82/// Exports the annotated type, which implements [`daemon::DaemonPlugin`],
83/// as the component's `daemon-plugin` world.
84pub use standard_plugin_macros::daemon;
85
86/// Floating-point maths for `no_std` plugins (`libm::sinf`, `sqrtf`, ...):
87/// `core` has no `f32::sin`.
88pub use libm;
89
90/// What most plugins import: `use standard_plugin::prelude::*;`.
91pub mod prelude {
92    pub use crate::daemon::DaemonPlugin;
93    pub use crate::{
94        AnySurface, Area, Attrs, Button, Cells, Colour, Context, Error, Event, Frame, Geometry,
95        Instances, Json, Key, KeyCode, Modifiers, Pixels, Pointer, PointerKind, Rect, Rgba, Scroll,
96        Shapes, Style, Surface, Target, ThemeSlot, UiPlugin,
97    };
98    pub use alloc::borrow::ToOwned;
99    pub use alloc::boxed::Box;
100    pub use alloc::format;
101    pub use alloc::string::{String, ToString};
102    pub use alloc::vec;
103    pub use alloc::vec::Vec;
104}
105
106/// The sources this SDK version is built from, for tools: the
107/// `standard-plugin` CLI checks components against [`sources::WIT`] and
108/// scaffolds new plugins from the examples, so both always match the SDK
109/// the new plugin depends on.
110pub mod sources {
111    /// The WIT package `standard:plugin@2.0.0` (`wit/plugin.wit`): the one
112    /// copy the SDK bindings, the viewer and daemon hosts and the CLI use.
113    pub const WIT: &str = include_str!("../wit/plugin.wit");
114
115    /// The compiled examples `standard-plugin new` starts from.
116    pub mod examples {
117        /// A cell-model sidebar card (`examples/clock_card.rs`).
118        pub const CLOCK_CARD: &str = include_str!("../examples/clock_card.rs");
119        /// A pane with a long list the viewer scrolls
120        /// (`examples/scroll_list.rs`).
121        pub const SCROLL_LIST: &str = include_str!("../examples/scroll_list.rs");
122        /// A daemon plugin (`examples/heartbeat_daemon.rs`).
123        pub const HEARTBEAT_DAEMON: &str = include_str!("../examples/heartbeat_daemon.rs");
124        /// The UI half of a companion pair (`examples/together_ui.rs`).
125        pub const TOGETHER_UI: &str = include_str!("../examples/together_ui.rs");
126        /// The companion daemon (`examples/together_companion.rs`).
127        pub const TOGETHER_COMPANION: &str = include_str!("../examples/together_companion.rs");
128    }
129
130    /// One guide of this SDK version: its name, the file stem in `docs/`
131    /// (`standard-plugin guide <name>`), and its Markdown text.
132    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
133    pub struct Guide {
134        pub name: &'static str,
135        pub text: &'static str,
136    }
137
138    impl Guide {
139        /// The text of its first heading, else its name.
140        #[must_use]
141        pub fn title(&self) -> &'static str {
142            self.text
143                .lines()
144                .next()
145                .and_then(|line| line.strip_prefix("# "))
146                .unwrap_or(self.name)
147        }
148    }
149
150    /// Every guide in this crate's `docs/` directory, in reading order,
151    /// the index first ([`crate::guide`] shows the same pages).
152    pub const GUIDES: &[Guide] = &[
153        Guide {
154            name: "README",
155            text: include_str!("../docs/README.md"),
156        },
157        Guide {
158            name: "getting-started",
159            text: include_str!("../docs/getting-started.md"),
160        },
161        Guide {
162            name: "agent-guide",
163            text: include_str!("../docs/agent-guide.md"),
164        },
165        Guide {
166            name: "manifest",
167            text: include_str!("../docs/manifest.md"),
168        },
169        Guide {
170            name: "grants",
171            text: include_str!("../docs/grants.md"),
172        },
173        Guide {
174            name: "rendering",
175            text: include_str!("../docs/rendering.md"),
176        },
177        Guide {
178            name: "input",
179            text: include_str!("../docs/input.md"),
180        },
181        Guide {
182            name: "handlers",
183            text: include_str!("../docs/handlers.md"),
184        },
185        Guide {
186            name: "previews",
187            text: include_str!("../docs/previews.md"),
188        },
189        Guide {
190            name: "working-together",
191            text: include_str!("../docs/working-together.md"),
192        },
193        Guide {
194            name: "daemon-plugins",
195            text: include_str!("../docs/daemon-plugins.md"),
196        },
197        Guide {
198            name: "testing",
199            text: include_str!("../docs/testing.md"),
200        },
201        Guide {
202            name: "publishing",
203            text: include_str!("../docs/publishing.md"),
204        },
205        Guide {
206            name: "abi",
207            text: include_str!("../docs/abi.md"),
208        },
209        Guide {
210            name: "other-languages",
211            text: include_str!("../docs/other-languages.md"),
212        },
213    ];
214}
215
216/// The guides, as pages of this documentation. The same Markdown files are
217/// this crate's `docs/` directory, where links between guides resolve, and
218/// `standard-plugin guide` prints them for the SDK version a plugin's
219/// `Cargo.lock` resolves.
220pub mod guide {
221    #[doc = include_str!("../docs/README.md")]
222    pub mod index {}
223    #[doc = include_str!("../docs/getting-started.md")]
224    pub mod getting_started {}
225    #[doc = include_str!("../docs/agent-guide.md")]
226    pub mod agent_guide {}
227    #[doc = include_str!("../docs/manifest.md")]
228    pub mod manifest {}
229    #[doc = include_str!("../docs/grants.md")]
230    pub mod grants {}
231    #[doc = include_str!("../docs/rendering.md")]
232    pub mod rendering {}
233    #[doc = include_str!("../docs/input.md")]
234    pub mod input {}
235    #[doc = include_str!("../docs/handlers.md")]
236    pub mod handlers {}
237    #[doc = include_str!("../docs/previews.md")]
238    pub mod previews {}
239    #[doc = include_str!("../docs/working-together.md")]
240    pub mod working_together {}
241    #[doc = include_str!("../docs/daemon-plugins.md")]
242    pub mod daemon_plugins {}
243    #[doc = include_str!("../docs/testing.md")]
244    pub mod testing {}
245    #[doc = include_str!("../docs/publishing.md")]
246    pub mod publishing {}
247    #[doc = include_str!("../docs/abi.md")]
248    pub mod abi {}
249    #[doc = include_str!("../docs/other-languages.md")]
250    pub mod other_languages {}
251}
252
253/// Used by the export macros; not part of the public API.
254#[doc(hidden)]
255pub mod __private {
256    pub use crate::bindings::{daemon as daemon_bindings, ui as ui_bindings};
257    pub use crate::daemon::runtime::DaemonRuntime;
258    pub use crate::ui_runtime::UiRuntime;
259    pub use alloc::string::String;
260}
261
262/// Exports a [`UiPlugin`] type; `#[standard_plugin::ui]` expands to this.
263#[doc(hidden)]
264#[macro_export]
265macro_rules! __export_ui {
266    ($plugin:ty) => {
267        const _: () = {
268            static RUNTIME: $crate::__private::UiRuntime<$plugin> =
269                $crate::__private::UiRuntime::new();
270
271            struct Export;
272
273            impl $crate::__private::ui_bindings::Guest for Export {
274                fn activate(config: $crate::__private::String) {
275                    RUNTIME.activate(config);
276                }
277
278                fn frame(
279                    now_ms: u64,
280                    interval_ms: u32,
281                    power: $crate::__private::ui_bindings::Power,
282                ) -> Option<u64> {
283                    RUNTIME.frame(now_ms, interval_ms, power.into())
284                }
285
286                fn event(event: $crate::__private::ui_bindings::Event) {
287                    RUNTIME.event(event.into());
288                }
289
290                fn deactivate() {
291                    RUNTIME.deactivate();
292                }
293            }
294
295    $crate::__export_ui_plugin_impl!(Export with_types_in $crate::__private::ui_bindings);
296        };
297    };
298}
299
300/// Exports a [`daemon::DaemonPlugin`] type; `#[standard_plugin::daemon]`
301/// expands to this.
302#[doc(hidden)]
303#[macro_export]
304macro_rules! __export_daemon {
305    ($plugin:ty) => {
306        const _: () = {
307            static RUNTIME: $crate::__private::DaemonRuntime<$plugin> =
308                $crate::__private::DaemonRuntime::new();
309
310            struct Export;
311
312            impl $crate::__private::daemon_bindings::Guest for Export {
313                fn activate(config: $crate::__private::String) {
314                    RUNTIME.activate(config);
315                }
316
317                fn event(event: $crate::__private::daemon_bindings::Event) {
318                    RUNTIME.event(event.into());
319                }
320
321                fn drive(now_ms: u64) -> Option<u64> {
322                    RUNTIME.drive(now_ms)
323                }
324
325                fn deactivate() {
326                    RUNTIME.deactivate();
327                }
328            }
329
330            impl $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::Guest
331                for Export
332            {
333                fn handle_event(
334                    event: $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::DaemonEvent,
335                ) {
336                    RUNTIME.event(event.into());
337                }
338            }
339
340            impl $crate::__private::daemon_bindings::exports::standard::plugin::companion::Guest
341                for Export
342            {
343                fn handle_call(
344                    method: $crate::__private::String,
345                    payload: $crate::__private::String,
346                    from: $crate::__private::daemon_bindings::exports::standard::plugin::companion::Caller,
347                ) -> Result<
348                    $crate::__private::String,
349                    $crate::__private::ui_bindings::standard::plugin::types::CallError,
350                > {
351                    RUNTIME
352                        .handle_call(&method, payload, from.into())
353                        .map_err(Into::into)
354                }
355            }
356
357            // Only a component exports. Natively, interface exports are
358            // `<interface>#<function>` symbols, and `#` starts a comment in
359            // the macOS linker's exported-symbols list.
360            #[cfg(target_family = "wasm")]
361            $crate::__export_daemon_plugin_impl!(
362                Export with_types_in $crate::__private::daemon_bindings
363            );
364
365            // A native build (tests, `cargo check`) still uses the plugin
366            // through the same entry points.
367            #[cfg(not(target_family = "wasm"))]
368            #[allow(dead_code)]
369            fn native_entry_points() {
370                use $crate::__private::daemon_bindings::Guest as _;
371                use $crate::__private::daemon_bindings::exports::standard::plugin::companion::Guest as _;
372                use $crate::__private::daemon_bindings::exports::standard::plugin::daemon_events::Guest as _;
373                let _ = (
374                    Export::activate,
375                    Export::event,
376                    Export::handle_event,
377                    Export::drive,
378                    Export::deactivate,
379                    Export::handle_call,
380                );
381            }
382        };
383    };
384}