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    /// Creates a pane through this driving viewer's normal action, including
127    /// on a remote project's machine. Needs `view.pane-create` and a gesture.
128    /// Returns its permanent id; wait for [`crate::view::PANE_CREATE_RESULT`]
129    /// before treating it as created. Never takes controller authority.
130    pub fn create_pane(
131        &self,
132        project: &str,
133        argv: &[String],
134        title: &str,
135    ) -> crate::Result<String> {
136        crate::host::create_pane(project, argv, title)
137    }
138
139    /// Opens an `https://` URL in the user's browser ([`crate::url::open`]):
140    /// while handling user input, or within a second after it.
141    pub fn open_url(&self, url: &str) -> crate::Result<()> {
142        crate::host::url_open(url)
143    }
144
145    /// Opens an instance of the declared `pane` or `window` surface
146    /// `surface`, named `<surface>@<key>`, and returns that name: a surface
147    /// of its own for events, [`Surface`](crate::Surface) and
148    /// [`Context::close`]. A `pane` instance with `after` opens right after
149    /// that pane without taking focus. It needs a user gesture, as
150    /// [`Context::open`], unless the plugin holds
151    /// `surface.open-unprompted` and names `after`.
152    pub fn open_instance(
153        &self,
154        surface: &str,
155        key: &str,
156        after: Option<&str>,
157    ) -> crate::Result<String> {
158        crate::host::surface_open_instance(surface, key, after)
159    }
160
161    /// Closes a surface [`Context::open`] opened.
162    pub fn close(&self, surface: &str) -> crate::Result<()> {
163        crate::host::surface_close(surface)
164    }
165
166    /// Asks for `surface` to be `cols` by `rows` cells (0: the viewer's
167    /// choice in that dimension) instead of the manifest's size. The
168    /// viewer clamps it where it places the surface and sends
169    /// [`Event::Resize`] when the size changes. A card grows to show more
170    /// rows; a popover fits its content.
171    pub fn request_size(&self, surface: &str, cols: u32, rows: u32) -> crate::Result<()> {
172        crate::host::surface_request_size(surface, cols, rows)
173    }
174
175    /// Sets a short label the viewer shows at the right end of `surface`'s
176    /// chrome title: a boxed card's top border, a pane's header, a column's
177    /// title row. `None` removes it. At most 48 characters with no control
178    /// characters.
179    pub fn set_label(&self, surface: &str, label: Option<&str>) -> crate::Result<()> {
180        crate::host::surface_set_label(surface, label)
181    }
182
183    /// Places the viewer's own text cursor at (`col`, `row`) of `surface`
184    /// while the surface takes keys (an open stage, popover or pane
185    /// overlay, or the surface a click or `open` gave input focus), so a
186    /// text field draws no cursor of its own; the cursor trail moves to it.
187    /// `None` removes it. Stays until set again.
188    pub fn set_caret(&self, surface: &str, caret: Option<(u32, u32)>) -> crate::Result<()> {
189        crate::host::surface_set_caret(surface, caret)
190    }
191
192    /// Shows an agent at work in `surface` the way the viewer shows its own
193    /// agent acting: an arrow with a name tag that glides to each place set
194    /// here (it jumps under reduced motion) and plays a press when
195    /// `pointer.press` is set. Report what the agent does, such as the
196    /// clicks it sends an embedded page; the viewer draws the pointer over
197    /// the surface, clipped to it. `None` removes it. `Invalid` for a place
198    /// outside the surface, `Unavailable` while the viewer has no cell
199    /// pixel size. Stays until set again.
200    pub fn set_agent_pointer(
201        &self,
202        surface: &str,
203        pointer: Option<crate::surface::AgentPointer>,
204    ) -> crate::Result<()> {
205        crate::host::surface_set_agent_pointer(surface, pointer)
206    }
207}
208
209/// Whether the viewer's machine is saving power.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
211pub enum Power {
212    #[default]
213    Mains,
214    SavePower,
215}
216
217impl From<wit::Power> for Power {
218    fn from(power: wit::Power) -> Self {
219        match power {
220            wit::Power::Mains => Self::Mains,
221            wit::Power::SavePower => Self::SavePower,
222        }
223    }
224}
225
226/// One frame callback.
227#[derive(Debug)]
228pub struct Frame {
229    now_ms: u64,
230    interval_ms: u32,
231    power: Power,
232    elapsed_ms: u64,
233    next: Cell<Option<u64>>,
234}
235
236impl Frame {
237    /// A frame at `now_ms` (for tests; the runtime makes the real ones).
238    pub fn new(now_ms: u64, interval_ms: u32, power: Power) -> Self {
239        Self {
240            now_ms,
241            interval_ms,
242            power,
243            elapsed_ms: 0,
244            next: Cell::new(None),
245        }
246    }
247
248    /// Milliseconds since the previous frame; zero on the first frame, and
249    /// on the first frame after the plugin's surfaces were all hidden (a
250    /// hidden period is not play time).
251    pub fn elapsed(&self) -> u64 {
252        self.elapsed_ms
253    }
254
255    /// The viewer's monotonic clock, in milliseconds.
256    pub fn now_ms(&self) -> u64 {
257        self.now_ms
258    }
259
260    /// The paced frame interval.
261    pub fn interval_ms(&self) -> u32 {
262        self.interval_ms
263    }
264
265    pub fn power(&self) -> Power {
266        self.power
267    }
268
269    /// Asks for the next paced frame (an animation).
270    pub fn request_frame(&self) {
271        self.wake_at(self.now_ms);
272    }
273
274    /// Asks for a frame at `at_ms` on the viewer's clock (a clock asks for
275    /// the next second). The earliest request wins.
276    pub fn wake_at(&self, at_ms: u64) {
277        let next = self.next.get().map_or(at_ms, |next| next.min(at_ms));
278        self.next.set(Some(next));
279    }
280
281    /// Asks for a frame `after_ms` from now.
282    pub fn wake_after(&self, after_ms: u64) {
283        self.wake_at(self.now_ms.saturating_add(after_ms));
284    }
285
286    /// When the plugin asked to be called next.
287    pub fn next_wake(&self) -> Option<u64> {
288        self.next.get()
289    }
290}
291
292/// What the host tells a plugin besides frames.
293#[derive(Clone, Debug, PartialEq, Eq)]
294#[non_exhaustive]
295pub enum Event {
296    /// A surface changed size. The SDK has rebound it; repaint it.
297    Resize { surface: String, geometry: Geometry },
298    /// A surface became visible or hidden.
299    Visibility { surface: String, visible: bool },
300    /// Graphics support, cell pixel size or frame rate changed
301    /// ([`capabilities`](mod@crate::capabilities)).
302    CapabilitiesChanged,
303    /// [`crate::view::is_driving`] changed.
304    Driving(bool),
305    /// A watched value changed ([`crate::values::Values::watch`]).
306    ValueChanged { key: String, value: Option<Json> },
307    /// A live message ([`crate::live::Live::subscribe`]).
308    Live { key: String, payload: Json },
309    /// A live key was withdrawn ([`crate::live::Live::delete`]).
310    LiveDeleted { key: String },
311    /// A plugin event ([`crate::events::Events::on`]).
312    Plugin { name: String, payload: Json },
313    /// The account changed ([`crate::account::watch`]).
314    AccountChanged,
315    /// A key on the surface with input focus.
316    Key(Key),
317    /// Text pasted into the surface with input focus.
318    Paste { surface: String, text: String },
319    /// The pointer over one of the plugin's surfaces.
320    Pointer(Pointer),
321    /// The viewer's theme or reduce-motion setting changed
322    /// ([`crate::view::theme`], [`crate::view::reduced_motion`]).
323    ThemeChanged,
324    /// A surface gained or lost input focus.
325    Focus { surface: String, focused: bool },
326    /// The user ran one of the manifest's commands, by id.
327    Command(String),
328    /// A [`Calls::call_async`](crate::calls::Calls::call_async) finished:
329    /// the companion's answer, or why there is none (a timeout is
330    /// [`Error::Unavailable`](crate::Error::Unavailable)).
331    CallResult {
332        id: crate::api::calls::CallId,
333        result: Result<Json>,
334    },
335    /// Daemon plugins: files under a [`watch`](crate::daemon::watch)
336    /// changed; every path that changed since the last delivery.
337    FileChanged { watch: u32, paths: Vec<String> },
338    /// Daemon plugins: a watch stopped delivering (the watcher's error).
339    WatchFailed { watch: u32, error: String },
340    /// Daemon plugins: output from a child's piped stream.
341    ProcessOutput {
342        pid: u32,
343        stderr: bool,
344        bytes: Vec<u8>,
345    },
346    /// Daemon plugins: a child exited (a signal is negated), after the
347    /// last of its output.
348    ProcessExited { pid: u32, status: i32 },
349    /// Daemon plugins: a pane on the daemon's machine changed
350    /// ([`panes::subscribe`](crate::daemon::panes::subscribe)).
351    PaneChanged {
352        kind: crate::daemon::PaneChangeKind,
353        pane: crate::api::account::Pane,
354    },
355    /// Daemon plugins: which of the plugin's UI surfaces the account's
356    /// viewers show changed ([`Context::interest`](crate::daemon::Context::interest)).
357    /// Start reading an outside source when [`any`](crate::daemon::Interest::any)
358    /// turns true and stop when it turns false.
359    Interest(crate::daemon::Interest),
360}
361
362impl From<wit::Event> for Event {
363    fn from(event: wit::Event) -> Self {
364        match event {
365            wit::Event::Resize((surface, g)) => Self::Resize {
366                surface,
367                geometry: Geometry {
368                    cols: g.cols,
369                    rows: g.rows,
370                    px_w: g.px_w,
371                    px_h: g.px_h,
372                    cell_px_w: g.cell_px_w,
373                    cell_px_h: g.cell_px_h,
374                },
375            },
376            wit::Event::Visibility((surface, visible)) => Self::Visibility { surface, visible },
377            wit::Event::CapabilitiesChanged => Self::CapabilitiesChanged,
378            wit::Event::Driving(driving) => Self::Driving(driving),
379            wit::Event::ValueChanged((key, value)) => Self::ValueChanged {
380                key,
381                value: value.map(Json),
382            },
383            wit::Event::Live((key, payload)) => Self::Live {
384                key,
385                payload: Json(payload),
386            },
387            wit::Event::LiveDeleted(key) => Self::LiveDeleted { key },
388            wit::Event::PluginEvent((name, payload)) => Self::Plugin {
389                name,
390                payload: Json(payload),
391            },
392            wit::Event::AccountChanged => Self::AccountChanged,
393            wit::Event::Key(key) => Self::Key(Key {
394                surface: key.surface,
395                code: KeyCode::parse(&key.code),
396                text: key.text,
397                modifiers: Modifiers(key.modifiers),
398                phase: match key.phase {
399                    wit::standard::plugin::event_types::KeyPhase::Press => KeyPhase::Press,
400                    wit::standard::plugin::event_types::KeyPhase::Repeat => KeyPhase::Repeat,
401                    wit::standard::plugin::event_types::KeyPhase::Release => KeyPhase::Release,
402                },
403            }),
404            wit::Event::Paste((surface, text)) => Self::Paste { surface, text },
405            wit::Event::Pointer(pointer) => Self::Pointer(Pointer {
406                surface: pointer.surface,
407                x: pointer.x,
408                y: pointer.y,
409                col: pointer.col,
410                row: pointer.row,
411                button: Button::from_wire(pointer.button),
412                kind: match pointer.kind {
413                    wit::standard::plugin::event_types::PointerKind::Down => PointerKind::Down,
414                    wit::standard::plugin::event_types::PointerKind::Up => PointerKind::Up,
415                    wit::standard::plugin::event_types::PointerKind::Move => PointerKind::Move,
416                    wit::standard::plugin::event_types::PointerKind::Drag => PointerKind::Drag,
417                    wit::standard::plugin::event_types::PointerKind::Wheel => PointerKind::Wheel,
418                    wit::standard::plugin::event_types::PointerKind::Enter => PointerKind::Enter,
419                    wit::standard::plugin::event_types::PointerKind::Leave => PointerKind::Leave,
420                },
421                modifiers: Modifiers(pointer.modifiers),
422            }),
423            wit::Event::ThemeChanged => Self::ThemeChanged,
424            wit::Event::Focus((surface, focused)) => Self::Focus { surface, focused },
425            wit::Event::Command(id) => Self::Command(id),
426            wit::Event::CallResult(answer) => Self::CallResult {
427                id: crate::api::calls::CallId(answer.id),
428                result: answer.outcome.map(Json).map_err(Into::into),
429            },
430        }
431    }
432}
433
434/// The instance's plugin and context, driven by the exports.
435#[doc(hidden)]
436pub struct UiRuntime<P> {
437    plugin: RefCell<Option<P>>,
438    cx: RefCell<Context>,
439    /// The previous frame's clock; `None` at the start and after every
440    /// surface was hidden.
441    last_frame_ms: Cell<Option<u64>>,
442    /// Surfaces the viewer shows now.
443    visible: RefCell<alloc::collections::BTreeSet<String>>,
444}
445
446// SAFETY: a component instance runs on one thread and the host calls one
447// export at a time; the exports are the only users of the static runtime.
448// On other targets the static is never reached (tests drive their own
449// runtime through `testing::Harness`).
450unsafe impl<P> Sync for UiRuntime<P> {}
451
452impl<P> Default for UiRuntime<P> {
453    fn default() -> Self {
454        Self::new()
455    }
456}
457
458impl<P> UiRuntime<P> {
459    pub const fn new() -> Self {
460        Self {
461            plugin: RefCell::new(None),
462            cx: RefCell::new(Context::new()),
463            last_frame_ms: Cell::new(None),
464            visible: RefCell::new(alloc::collections::BTreeSet::new()),
465        }
466    }
467}
468
469impl<P: UiPlugin> UiRuntime<P> {
470    pub fn activate(&self, config: String) {
471        let mut cx = self.cx.borrow_mut();
472        cx.config = config;
473        let plugin = P::activate(&mut cx);
474        *self.plugin.borrow_mut() = Some(plugin);
475    }
476
477    pub fn frame(&self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
478        let mut frame = Frame::new(now_ms, interval_ms, power);
479        frame.elapsed_ms = self
480            .last_frame_ms
481            .get()
482            .map_or(0, |last| now_ms.saturating_sub(last));
483        self.last_frame_ms.set(Some(now_ms));
484        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
485            plugin.frame(&frame);
486        }
487        frame.next_wake()
488    }
489
490    pub fn event(&self, event: Event) {
491        match &event {
492            Event::Resize { surface, .. } => crate::surface::rebind_surfaces(surface),
493            Event::Visibility { surface, visible } => {
494                let mut shown = self.visible.borrow_mut();
495                if *visible {
496                    shown.insert(surface.clone());
497                } else {
498                    shown.remove(surface);
499                    if shown.is_empty() {
500                        self.last_frame_ms.set(None);
501                    }
502                }
503            }
504            _ => {}
505        }
506        let mut cx = self.cx.borrow_mut();
507        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
508            plugin.event(event, &mut cx);
509        }
510    }
511
512    pub fn deactivate(&self) {
513        let plugin = self.plugin.borrow_mut().take();
514        if let Some(mut plugin) = plugin {
515            plugin.deactivate();
516        }
517    }
518
519    /// The plugin, for tests.
520    pub fn with_plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> Option<R> {
521        self.plugin.borrow_mut().as_mut().map(f)
522    }
523}