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
193/// Whether the viewer's machine is saving power.
194#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
195pub enum Power {
196    #[default]
197    Mains,
198    SavePower,
199}
200
201impl From<wit::Power> for Power {
202    fn from(power: wit::Power) -> Self {
203        match power {
204            wit::Power::Mains => Self::Mains,
205            wit::Power::SavePower => Self::SavePower,
206        }
207    }
208}
209
210/// One frame callback.
211#[derive(Debug)]
212pub struct Frame {
213    now_ms: u64,
214    interval_ms: u32,
215    power: Power,
216    elapsed_ms: u64,
217    next: Cell<Option<u64>>,
218}
219
220impl Frame {
221    /// A frame at `now_ms` (for tests; the runtime makes the real ones).
222    pub fn new(now_ms: u64, interval_ms: u32, power: Power) -> Self {
223        Self {
224            now_ms,
225            interval_ms,
226            power,
227            elapsed_ms: 0,
228            next: Cell::new(None),
229        }
230    }
231
232    /// Milliseconds since the previous frame; zero on the first frame, and
233    /// on the first frame after the plugin's surfaces were all hidden (a
234    /// hidden period is not play time).
235    pub fn elapsed(&self) -> u64 {
236        self.elapsed_ms
237    }
238
239    /// The viewer's monotonic clock, in milliseconds.
240    pub fn now_ms(&self) -> u64 {
241        self.now_ms
242    }
243
244    /// The paced frame interval.
245    pub fn interval_ms(&self) -> u32 {
246        self.interval_ms
247    }
248
249    pub fn power(&self) -> Power {
250        self.power
251    }
252
253    /// Asks for the next paced frame (an animation).
254    pub fn request_frame(&self) {
255        self.wake_at(self.now_ms);
256    }
257
258    /// Asks for a frame at `at_ms` on the viewer's clock (a clock asks for
259    /// the next second). The earliest request wins.
260    pub fn wake_at(&self, at_ms: u64) {
261        let next = self.next.get().map_or(at_ms, |next| next.min(at_ms));
262        self.next.set(Some(next));
263    }
264
265    /// Asks for a frame `after_ms` from now.
266    pub fn wake_after(&self, after_ms: u64) {
267        self.wake_at(self.now_ms.saturating_add(after_ms));
268    }
269
270    /// When the plugin asked to be called next.
271    pub fn next_wake(&self) -> Option<u64> {
272        self.next.get()
273    }
274}
275
276/// What the host tells a plugin besides frames.
277#[derive(Clone, Debug, PartialEq, Eq)]
278#[non_exhaustive]
279pub enum Event {
280    /// A surface changed size. The SDK has rebound it; repaint it.
281    Resize { surface: String, geometry: Geometry },
282    /// A surface became visible or hidden.
283    Visibility { surface: String, visible: bool },
284    /// Graphics support, cell pixel size or frame rate changed
285    /// ([`capabilities`](mod@crate::capabilities)).
286    CapabilitiesChanged,
287    /// [`crate::view::is_driving`] changed.
288    Driving(bool),
289    /// A watched value changed ([`crate::values::Values::watch`]).
290    ValueChanged { key: String, value: Option<Json> },
291    /// A live message ([`crate::live::Live::subscribe`]).
292    Live { key: String, payload: Json },
293    /// A live key was withdrawn ([`crate::live::Live::delete`]).
294    LiveDeleted { key: String },
295    /// A plugin event ([`crate::events::Events::on`]).
296    Plugin { name: String, payload: Json },
297    /// The account changed ([`crate::account::watch`]).
298    AccountChanged,
299    /// A key on the surface with input focus.
300    Key(Key),
301    /// Text pasted into the surface with input focus.
302    Paste { surface: String, text: String },
303    /// The pointer over one of the plugin's surfaces.
304    Pointer(Pointer),
305    /// The viewer's theme or reduce-motion setting changed
306    /// ([`crate::view::theme`], [`crate::view::reduced_motion`]).
307    ThemeChanged,
308    /// A surface gained or lost input focus.
309    Focus { surface: String, focused: bool },
310    /// The user ran one of the manifest's commands, by id.
311    Command(String),
312    /// A [`Calls::call_async`](crate::calls::Calls::call_async) finished:
313    /// the companion's answer, or why there is none (a timeout is
314    /// [`Error::Unavailable`](crate::Error::Unavailable)).
315    CallResult {
316        id: crate::api::calls::CallId,
317        result: Result<Json>,
318    },
319    /// Daemon plugins: files under a [`watch`](crate::daemon::watch)
320    /// changed; every path that changed since the last delivery.
321    FileChanged { watch: u32, paths: Vec<String> },
322    /// Daemon plugins: a watch stopped delivering (the watcher's error).
323    WatchFailed { watch: u32, error: String },
324    /// Daemon plugins: output from a child's piped stream.
325    ProcessOutput {
326        pid: u32,
327        stderr: bool,
328        bytes: Vec<u8>,
329    },
330    /// Daemon plugins: a child exited (a signal is negated), after the
331    /// last of its output.
332    ProcessExited { pid: u32, status: i32 },
333    /// Daemon plugins: a pane on the daemon's machine changed
334    /// ([`panes::subscribe`](crate::daemon::panes::subscribe)).
335    PaneChanged {
336        kind: crate::daemon::PaneChangeKind,
337        pane: crate::api::account::Pane,
338    },
339    /// Daemon plugins: which of the plugin's UI surfaces the account's
340    /// viewers show changed ([`Context::interest`](crate::daemon::Context::interest)).
341    /// Start reading an outside source when [`any`](crate::daemon::Interest::any)
342    /// turns true and stop when it turns false.
343    Interest(crate::daemon::Interest),
344}
345
346impl From<wit::Event> for Event {
347    fn from(event: wit::Event) -> Self {
348        match event {
349            wit::Event::Resize((surface, g)) => Self::Resize {
350                surface,
351                geometry: Geometry {
352                    cols: g.cols,
353                    rows: g.rows,
354                    px_w: g.px_w,
355                    px_h: g.px_h,
356                    cell_px_w: g.cell_px_w,
357                    cell_px_h: g.cell_px_h,
358                },
359            },
360            wit::Event::Visibility((surface, visible)) => Self::Visibility { surface, visible },
361            wit::Event::CapabilitiesChanged => Self::CapabilitiesChanged,
362            wit::Event::Driving(driving) => Self::Driving(driving),
363            wit::Event::ValueChanged((key, value)) => Self::ValueChanged {
364                key,
365                value: value.map(Json),
366            },
367            wit::Event::Live((key, payload)) => Self::Live {
368                key,
369                payload: Json(payload),
370            },
371            wit::Event::LiveDeleted(key) => Self::LiveDeleted { key },
372            wit::Event::PluginEvent((name, payload)) => Self::Plugin {
373                name,
374                payload: Json(payload),
375            },
376            wit::Event::AccountChanged => Self::AccountChanged,
377            wit::Event::Key(key) => Self::Key(Key {
378                surface: key.surface,
379                code: KeyCode::parse(&key.code),
380                text: key.text,
381                modifiers: Modifiers(key.modifiers),
382                phase: match key.phase {
383                    wit::standard::plugin::event_types::KeyPhase::Press => KeyPhase::Press,
384                    wit::standard::plugin::event_types::KeyPhase::Repeat => KeyPhase::Repeat,
385                    wit::standard::plugin::event_types::KeyPhase::Release => KeyPhase::Release,
386                },
387            }),
388            wit::Event::Paste((surface, text)) => Self::Paste { surface, text },
389            wit::Event::Pointer(pointer) => Self::Pointer(Pointer {
390                surface: pointer.surface,
391                x: pointer.x,
392                y: pointer.y,
393                col: pointer.col,
394                row: pointer.row,
395                button: Button::from_wire(pointer.button),
396                kind: match pointer.kind {
397                    wit::standard::plugin::event_types::PointerKind::Down => PointerKind::Down,
398                    wit::standard::plugin::event_types::PointerKind::Up => PointerKind::Up,
399                    wit::standard::plugin::event_types::PointerKind::Move => PointerKind::Move,
400                    wit::standard::plugin::event_types::PointerKind::Drag => PointerKind::Drag,
401                    wit::standard::plugin::event_types::PointerKind::Wheel => PointerKind::Wheel,
402                    wit::standard::plugin::event_types::PointerKind::Enter => PointerKind::Enter,
403                    wit::standard::plugin::event_types::PointerKind::Leave => PointerKind::Leave,
404                },
405                modifiers: Modifiers(pointer.modifiers),
406            }),
407            wit::Event::ThemeChanged => Self::ThemeChanged,
408            wit::Event::Focus((surface, focused)) => Self::Focus { surface, focused },
409            wit::Event::Command(id) => Self::Command(id),
410            wit::Event::CallResult(answer) => Self::CallResult {
411                id: crate::api::calls::CallId(answer.id),
412                result: answer.outcome.map(Json).map_err(Into::into),
413            },
414        }
415    }
416}
417
418/// The instance's plugin and context, driven by the exports.
419#[doc(hidden)]
420pub struct UiRuntime<P> {
421    plugin: RefCell<Option<P>>,
422    cx: RefCell<Context>,
423    /// The previous frame's clock; `None` at the start and after every
424    /// surface was hidden.
425    last_frame_ms: Cell<Option<u64>>,
426    /// Surfaces the viewer shows now.
427    visible: RefCell<alloc::collections::BTreeSet<String>>,
428}
429
430// SAFETY: a component instance runs on one thread and the host calls one
431// export at a time; the exports are the only users of the static runtime.
432// On other targets the static is never reached (tests drive their own
433// runtime through `testing::Harness`).
434unsafe impl<P> Sync for UiRuntime<P> {}
435
436impl<P> Default for UiRuntime<P> {
437    fn default() -> Self {
438        Self::new()
439    }
440}
441
442impl<P> UiRuntime<P> {
443    pub const fn new() -> Self {
444        Self {
445            plugin: RefCell::new(None),
446            cx: RefCell::new(Context::new()),
447            last_frame_ms: Cell::new(None),
448            visible: RefCell::new(alloc::collections::BTreeSet::new()),
449        }
450    }
451}
452
453impl<P: UiPlugin> UiRuntime<P> {
454    pub fn activate(&self, config: String) {
455        let mut cx = self.cx.borrow_mut();
456        cx.config = config;
457        let plugin = P::activate(&mut cx);
458        *self.plugin.borrow_mut() = Some(plugin);
459    }
460
461    pub fn frame(&self, now_ms: u64, interval_ms: u32, power: Power) -> Option<u64> {
462        let mut frame = Frame::new(now_ms, interval_ms, power);
463        frame.elapsed_ms = self
464            .last_frame_ms
465            .get()
466            .map_or(0, |last| now_ms.saturating_sub(last));
467        self.last_frame_ms.set(Some(now_ms));
468        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
469            plugin.frame(&frame);
470        }
471        frame.next_wake()
472    }
473
474    pub fn event(&self, event: Event) {
475        match &event {
476            Event::Resize { surface, .. } => crate::surface::rebind_surfaces(surface),
477            Event::Visibility { surface, visible } => {
478                let mut shown = self.visible.borrow_mut();
479                if *visible {
480                    shown.insert(surface.clone());
481                } else {
482                    shown.remove(surface);
483                    if shown.is_empty() {
484                        self.last_frame_ms.set(None);
485                    }
486                }
487            }
488            _ => {}
489        }
490        let mut cx = self.cx.borrow_mut();
491        if let Some(plugin) = self.plugin.borrow_mut().as_mut() {
492            plugin.event(event, &mut cx);
493        }
494    }
495
496    pub fn deactivate(&self) {
497        let plugin = self.plugin.borrow_mut().take();
498        if let Some(mut plugin) = plugin {
499            plugin.deactivate();
500        }
501    }
502
503    /// The plugin, for tests.
504    pub fn with_plugin<R>(&self, f: impl FnOnce(&mut P) -> R) -> Option<R> {
505        self.plugin.borrow_mut().as_mut().map(f)
506    }
507}