Skip to main content

standard_plugin/
ui_runtime.rs

1//! UI plugins: the [`UiPlugin`] trait, what it is called with, and the
2//! runtime the `#[ui]` export forwards to.
3
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::cell::{Cell, RefCell};
7
8use serde::de::DeserializeOwned;
9
10use crate::api::{self, Json};
11use crate::bindings::ui as wit;
12use crate::error::Result;
13use crate::geometry::Geometry;
14pub use crate::input::{Button, Key, KeyCode, KeyPhase, Modifiers, Pointer, PointerKind};
15
16/// A UI plugin: one instance runs in every viewer on the account.
17///
18/// It paints its [`crate::Surface`]s and reads account state; it is
19/// side-effect free. Anything that must happen once (a write, a
20/// notification, a request) is either claimed first ([`claims`](mod@crate::claims)) or
21/// asked of a companion daemon ([`calls`](mod@crate::calls)); [`crate::view::is_driving`]
22/// says whether the user is controlling this viewer.
23pub trait UiPlugin: Sized + 'static {
24    /// Called once after instantiation. Create surfaces and read the
25    /// configuration here.
26    fn activate(cx: &mut Context) -> Self;
27
28    /// Called when a paced frame is due and one of the plugin's surfaces is
29    /// visible. Paint, commit, and say when the next frame is wanted
30    /// ([`Frame::request_frame`], [`Frame::wake_at`]); asking for nothing
31    /// waits for an event.
32    fn frame(&mut self, frame: &Frame);
33
34    /// Everything else the host tells the plugin. Surfaces are already
35    /// rebound when a [`Event::Resize`] arrives.
36    fn event(&mut self, event: Event, cx: &mut Context) {
37        let _ = (event, cx);
38    }
39
40    /// Called before the instance is dropped.
41    fn deactivate(&mut self) {}
42}
43
44/// What a plugin is called with besides a frame: its configuration, and
45/// handles to every interface.
46#[derive(Debug, Default)]
47pub struct Context {
48    config: String,
49}
50
51impl Context {
52    pub const fn new() -> Self {
53        Self {
54            config: String::new(),
55        }
56    }
57
58    /// The configuration document `activate` was called with.
59    pub fn config_json(&self) -> Json {
60        Json(self.config.clone())
61    }
62
63    /// The configuration, deserialized (an empty document is `null`).
64    pub fn config<T: DeserializeOwned>(&self) -> Result<T> {
65        if self.config.trim().is_empty() {
66            return Json(String::from("null")).parse();
67        }
68        Json(self.config.clone()).parse()
69    }
70
71    pub fn values(&self) -> api::values::Values {
72        api::values()
73    }
74
75    pub fn live(&self) -> api::live::Live {
76        api::live()
77    }
78
79    pub fn events(&self) -> api::events::Events {
80        api::events()
81    }
82
83    pub fn calls(&self) -> api::calls::Calls {
84        api::calls()
85    }
86
87    pub fn claims(&self) -> api::claims::Claims {
88        api::claims()
89    }
90
91    pub fn is_driving(&self) -> bool {
92        api::view::is_driving()
93    }
94
95    pub fn capabilities(&self) -> api::capabilities::Capabilities {
96        api::capabilities::get()
97    }
98
99    /// Asks for a frame on the next paced frame, from an event handler
100    /// (inside [`UiPlugin::frame`], use [`Frame::request_frame`]). A commit
101    /// in `event` is otherwise sampled on the next frame something else
102    /// causes.
103    pub fn request_frame(&self) {
104        crate::host::request_frame();
105    }
106
107    /// Asks for a frame at `at_ms` on the viewer's clock.
108    pub fn wake_at(&self, at_ms: u64) {
109        crate::host::wake_at(at_ms);
110    }
111
112    /// Opens a `stage` surface. Only while handling a user gesture: a key,
113    /// a paste, a pointer press on one of the plugin's surfaces, or one of
114    /// its commands.
115    pub fn open(&self, surface: &str) -> crate::Result<()> {
116        crate::host::surface_open(surface)
117    }
118
119    /// Shows a pane in this viewer's workspace and gives it focus, as a
120    /// click on its sidebar row does. Only while handling a user gesture,
121    /// as [`Context::open`]; a pane the viewer does not know is ignored.
122    pub fn focus_pane(&self, pane: &str) -> crate::Result<()> {
123        crate::host::focus_pane(pane)
124    }
125
126    /// Opens an `https://` URL in the user's browser ([`crate::url::open`]):
127    /// while handling user input, or within a second after it.
128    pub fn open_url(&self, url: &str) -> crate::Result<()> {
129        crate::host::url_open(url)
130    }
131
132    /// Opens an instance of the declared `pane` or `window` surface
133    /// `surface`, named `<surface>@<key>`, and returns that name: a surface
134    /// of its own for events, [`Surface`](crate::Surface) and
135    /// [`Context::close`]. A `pane` instance with `after` opens right after
136    /// that pane without taking focus. It needs a user gesture, as
137    /// [`Context::open`], unless the plugin holds
138    /// `surface.open-unprompted` and names `after`.
139    pub fn open_instance(
140        &self,
141        surface: &str,
142        key: &str,
143        after: Option<&str>,
144    ) -> crate::Result<String> {
145        crate::host::surface_open_instance(surface, key, after)
146    }
147
148    /// Closes a surface [`Context::open`] opened.
149    pub fn close(&self, surface: &str) -> crate::Result<()> {
150        crate::host::surface_close(surface)
151    }
152
153    /// Asks for `surface` to be `cols` by `rows` cells (0: the viewer's
154    /// choice in that dimension) instead of the manifest's size. The
155    /// viewer clamps it where it places the surface and sends
156    /// [`Event::Resize`] when the size changes. A card grows to show more
157    /// rows; a popover fits its content.
158    pub fn request_size(&self, surface: &str, cols: u32, rows: u32) -> crate::Result<()> {
159        crate::host::surface_request_size(surface, cols, rows)
160    }
161
162    /// Sets a short label the viewer shows at the right end of `surface`'s
163    /// chrome title: a boxed card's top border, a pane's header, a column's
164    /// title row. `None` removes it. At most 48 characters with no control
165    /// characters.
166    pub fn set_label(&self, surface: &str, label: Option<&str>) -> crate::Result<()> {
167        crate::host::surface_set_label(surface, label)
168    }
169
170    /// Places the viewer's own text cursor at (`col`, `row`) of `surface`
171    /// while the surface takes keys (an open stage, popover or pane
172    /// overlay, or the surface a click or `open` gave input focus), so a
173    /// text field draws no cursor of its own; the cursor trail moves to it.
174    /// `None` removes it. Stays until set again.
175    pub fn set_caret(&self, surface: &str, caret: Option<(u32, u32)>) -> crate::Result<()> {
176        crate::host::surface_set_caret(surface, caret)
177    }
178}
179
180/// Whether the viewer's machine is saving power.
181#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
182pub enum Power {
183    #[default]
184    Mains,
185    SavePower,
186}
187
188impl From<wit::Power> for Power {
189    fn from(power: wit::Power) -> Self {
190        match power {
191            wit::Power::Mains => Self::Mains,
192            wit::Power::SavePower => Self::SavePower,
193        }
194    }
195}
196
197/// One frame callback.
198#[derive(Debug)]
199pub struct Frame {
200    now_ms: u64,
201    interval_ms: u32,
202    power: Power,
203    elapsed_ms: u64,
204    next: Cell<Option<u64>>,
205}
206
207impl Frame {
208    /// A frame at `now_ms` (for tests; the runtime makes the real ones).
209    pub fn new(now_ms: u64, interval_ms: u32, power: Power) -> Self {
210        Self {
211            now_ms,
212            interval_ms,
213            power,
214            elapsed_ms: 0,
215            next: Cell::new(None),
216        }
217    }
218
219    /// Milliseconds since the previous frame; zero on the first frame, and
220    /// on the first frame after the plugin's surfaces were all hidden (a
221    /// hidden period is not play time).
222    pub fn elapsed(&self) -> u64 {
223        self.elapsed_ms
224    }
225
226    /// The viewer's monotonic clock, in milliseconds.
227    pub fn now_ms(&self) -> u64 {
228        self.now_ms
229    }
230
231    /// The paced frame interval.
232    pub fn interval_ms(&self) -> u32 {
233        self.interval_ms
234    }
235
236    pub fn power(&self) -> Power {
237        self.power
238    }
239
240    /// Asks for the next paced frame (an animation).
241    pub fn request_frame(&self) {
242        self.wake_at(self.now_ms);
243    }
244
245    /// Asks for a frame at `at_ms` on the viewer's clock (a clock asks for
246    /// the next second). The earliest request wins.
247    pub fn wake_at(&self, at_ms: u64) {
248        let next = self.next.get().map_or(at_ms, |next| next.min(at_ms));
249        self.next.set(Some(next));
250    }
251
252    /// Asks for a frame `after_ms` from now.
253    pub fn wake_after(&self, after_ms: u64) {
254        self.wake_at(self.now_ms.saturating_add(after_ms));
255    }
256
257    /// When the plugin asked to be called next.
258    pub fn next_wake(&self) -> Option<u64> {
259        self.next.get()
260    }
261}
262
263/// What the host tells a plugin besides frames.
264#[derive(Clone, Debug, PartialEq, Eq)]
265#[non_exhaustive]
266pub enum Event {
267    /// A surface changed size. The SDK has rebound it; repaint it.
268    Resize { surface: String, geometry: Geometry },
269    /// A surface became visible or hidden.
270    Visibility { surface: String, visible: bool },
271    /// Graphics support, cell pixel size or frame rate changed
272    /// ([`capabilities`](mod@crate::capabilities)).
273    CapabilitiesChanged,
274    /// [`crate::view::is_driving`] changed.
275    Driving(bool),
276    /// A watched value changed ([`crate::values::Values::watch`]).
277    ValueChanged { key: String, value: Option<Json> },
278    /// A live message ([`crate::live::Live::subscribe`]).
279    Live { key: String, payload: Json },
280    /// A live key was withdrawn ([`crate::live::Live::delete`]).
281    LiveDeleted { key: String },
282    /// A plugin event ([`crate::events::Events::on`]).
283    Plugin { name: String, payload: Json },
284    /// The account changed ([`crate::account::watch`]).
285    AccountChanged,
286    /// A key on the surface with input focus.
287    Key(Key),
288    /// Text pasted into the surface with input focus.
289    Paste { surface: String, text: String },
290    /// The pointer over one of the plugin's surfaces.
291    Pointer(Pointer),
292    /// The viewer's theme or reduce-motion setting changed
293    /// ([`crate::view::theme`], [`crate::view::reduced_motion`]).
294    ThemeChanged,
295    /// A surface gained or lost input focus.
296    Focus { surface: String, focused: bool },
297    /// The user ran one of the manifest's commands, by id.
298    Command(String),
299    /// A [`Calls::call_async`](crate::calls::Calls::call_async) finished:
300    /// the companion's answer, or why there is none (a timeout is
301    /// [`Error::Unavailable`](crate::Error::Unavailable)).
302    CallResult {
303        id: crate::api::calls::CallId,
304        result: Result<Json>,
305    },
306    /// Daemon plugins: files under a [`watch`](crate::daemon::watch)
307    /// changed; every path that changed since the last delivery.
308    FileChanged { watch: u32, paths: Vec<String> },
309    /// Daemon plugins: a watch stopped delivering (the watcher's error).
310    WatchFailed { watch: u32, error: String },
311    /// Daemon plugins: output from a child's piped stream.
312    ProcessOutput {
313        pid: u32,
314        stderr: bool,
315        bytes: Vec<u8>,
316    },
317    /// Daemon plugins: a child exited (a signal is negated), after the
318    /// last of its output.
319    ProcessExited { pid: u32, status: i32 },
320    /// Daemon plugins: a pane on the daemon's machine changed
321    /// ([`panes::subscribe`](crate::daemon::panes::subscribe)).
322    PaneChanged {
323        kind: crate::daemon::PaneChangeKind,
324        pane: crate::api::account::Pane,
325    },
326    /// Daemon plugins: which of the plugin's UI surfaces the account's
327    /// viewers show changed ([`Context::interest`](crate::daemon::Context::interest)).
328    /// Start reading an outside source when [`any`](crate::daemon::Interest::any)
329    /// turns true and stop when it turns false.
330    Interest(crate::daemon::Interest),
331}
332
333impl From<wit::Event> for Event {
334    fn from(event: wit::Event) -> Self {
335        match event {
336            wit::Event::Resize((surface, g)) => Self::Resize {
337                surface,
338                geometry: Geometry {
339                    cols: g.cols,
340                    rows: g.rows,
341                    px_w: g.px_w,
342                    px_h: g.px_h,
343                    cell_px_w: g.cell_px_w,
344                    cell_px_h: g.cell_px_h,
345                },
346            },
347            wit::Event::Visibility((surface, visible)) => Self::Visibility { surface, visible },
348            wit::Event::CapabilitiesChanged => Self::CapabilitiesChanged,
349            wit::Event::Driving(driving) => Self::Driving(driving),
350            wit::Event::ValueChanged((key, value)) => Self::ValueChanged {
351                key,
352                value: value.map(Json),
353            },
354            wit::Event::Live((key, payload)) => Self::Live {
355                key,
356                payload: Json(payload),
357            },
358            wit::Event::LiveDeleted(key) => Self::LiveDeleted { key },
359            wit::Event::PluginEvent((name, payload)) => Self::Plugin {
360                name,
361                payload: Json(payload),
362            },
363            wit::Event::AccountChanged => Self::AccountChanged,
364            wit::Event::Key(key) => Self::Key(Key {
365                surface: key.surface,
366                code: KeyCode::parse(&key.code),
367                text: key.text,
368                modifiers: Modifiers(key.modifiers),
369                phase: match key.phase {
370                    wit::standard::plugin::event_types::KeyPhase::Press => KeyPhase::Press,
371                    wit::standard::plugin::event_types::KeyPhase::Repeat => KeyPhase::Repeat,
372                    wit::standard::plugin::event_types::KeyPhase::Release => KeyPhase::Release,
373                },
374            }),
375            wit::Event::Paste((surface, text)) => Self::Paste { surface, text },
376            wit::Event::Pointer(pointer) => Self::Pointer(Pointer {
377                surface: pointer.surface,
378                x: pointer.x,
379                y: pointer.y,
380                col: pointer.col,
381                row: pointer.row,
382                button: Button::from_wire(pointer.button),
383                kind: match pointer.kind {
384                    wit::standard::plugin::event_types::PointerKind::Down => PointerKind::Down,
385                    wit::standard::plugin::event_types::PointerKind::Up => PointerKind::Up,
386                    wit::standard::plugin::event_types::PointerKind::Move => PointerKind::Move,
387                    wit::standard::plugin::event_types::PointerKind::Drag => PointerKind::Drag,
388                    wit::standard::plugin::event_types::PointerKind::Wheel => PointerKind::Wheel,
389                    wit::standard::plugin::event_types::PointerKind::Enter => PointerKind::Enter,
390                    wit::standard::plugin::event_types::PointerKind::Leave => PointerKind::Leave,
391                },
392                modifiers: Modifiers(pointer.modifiers),
393            }),
394            wit::Event::ThemeChanged => Self::ThemeChanged,
395            wit::Event::Focus((surface, focused)) => Self::Focus { surface, focused },
396            wit::Event::Command(id) => Self::Command(id),
397            wit::Event::CallResult(answer) => Self::CallResult {
398                id: crate::api::calls::CallId(answer.id),
399                result: answer.outcome.map(Json).map_err(Into::into),
400            },
401        }
402    }
403}
404
405/// The instance's plugin and context, driven by the exports.
406#[doc(hidden)]
407pub struct UiRuntime<P> {
408    plugin: RefCell<Option<P>>,
409    cx: RefCell<Context>,
410    /// The previous frame's clock; `None` at the start and after every
411    /// surface was hidden.
412    last_frame_ms: Cell<Option<u64>>,
413    /// Surfaces the viewer shows now.
414    visible: RefCell<alloc::collections::BTreeSet<String>>,
415}
416
417// SAFETY: a component instance runs on one thread and the host calls one
418// export at a time; the exports are the only users of the static runtime.
419// On other targets the static is never reached (tests drive their own
420// runtime through `testing::Harness`).
421unsafe impl<P> Sync for UiRuntime<P> {}
422
423impl<P> Default for UiRuntime<P> {
424    fn default() -> Self {
425        Self::new()
426    }
427}
428
429impl<P> UiRuntime<P> {
430    pub const fn new() -> Self {
431        Self {
432            plugin: RefCell::new(None),
433            cx: RefCell::new(Context::new()),
434            last_frame_ms: Cell::new(None),
435            visible: RefCell::new(alloc::collections::BTreeSet::new()),
436        }
437    }
438}
439
440impl<P: UiPlugin> UiRuntime<P> {
441    pub fn activate(&self, config: String) {
442        let mut cx = self.cx.borrow_mut();
443        cx.config = config;
444        let plugin = P::activate(&mut cx);
445        *self.plugin.borrow_mut() = Some(plugin);
446    }
447
448    pub fn frame(&self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
449        let mut frame = Frame::new(now_ms, interval_ms, power);
450        frame.elapsed_ms = self
451            .last_frame_ms
452            .get()
453            .map_or(0, |last| now_ms.saturating_sub(last));
454        self.last_frame_ms.set(Some(now_ms));
455        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
456            plugin.frame(&frame);
457        }
458        frame.next_wake()
459    }
460
461    pub fn event(&self, event: Event) {
462        match &event {
463            Event::Resize { surface, .. } => crate::surface::rebind_surfaces(surface),
464            Event::Visibility { surface, visible } => {
465                let mut shown = self.visible.borrow_mut();
466                if *visible {
467                    shown.insert(surface.clone());
468                } else {
469                    shown.remove(surface);
470                    if shown.is_empty() {
471                        self.last_frame_ms.set(None);
472                    }
473                }
474            }
475            _ => {}
476        }
477        let mut cx = self.cx.borrow_mut();
478        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
479            plugin.event(event, &mut cx);
480        }
481    }
482
483    pub fn deactivate(&self) {
484        let plugin = self.plugin.borrow_mut().take();
485        if let Some(mut plugin) = plugin {
486            plugin.deactivate();
487        }
488    }
489
490    /// The plugin, for tests.
491    pub fn with_plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> Option<R> {
492        self.plugin.borrow_mut().as_mut().map(f)
493    }
494}