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