1use 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
16pub trait UiPlugin: Sized + 'static {
24 fn activate(cx: &mut Context) -> Self;
27
28 fn frame(&mut self, frame: &Frame);
33
34 fn event(&mut self, event: Event, cx: &mut Context) {
37 let _ = (event, cx);
38 }
39
40 fn deactivate(&mut self) {}
42}
43
44#[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 pub fn config_json(&self) -> Json {
60 Json(self.config.clone())
61 }
62
63 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 pub fn request_frame(&self) {
104 crate::host::request_frame();
105 }
106
107 pub fn wake_at(&self, at_ms: u64) {
109 crate::host::wake_at(at_ms);
110 }
111
112 pub fn open(&self, surface: &str) -> crate::Result<()> {
116 crate::host::surface_open(surface)
117 }
118
119 pub fn focus_pane(&self, pane: &str) -> crate::Result<()> {
123 crate::host::focus_pane(pane)
124 }
125
126 pub fn open_url(&self, url: &str) -> crate::Result<()> {
129 crate::host::url_open(url)
130 }
131
132 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 pub fn close(&self, surface: &str) -> crate::Result<()> {
150 crate::host::surface_close(surface)
151 }
152
153 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 pub fn set_label(&self, surface: &str, label: Option<&str>) -> crate::Result<()> {
167 crate::host::surface_set_label(surface, label)
168 }
169
170 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#[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#[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 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 pub fn elapsed(&self) -> u64 {
223 self.elapsed_ms
224 }
225
226 pub fn now_ms(&self) -> u64 {
228 self.now_ms
229 }
230
231 pub fn interval_ms(&self) -> u32 {
233 self.interval_ms
234 }
235
236 pub fn power(&self) -> Power {
237 self.power
238 }
239
240 pub fn request_frame(&self) {
242 self.wake_at(self.now_ms);
243 }
244
245 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 pub fn wake_after(&self, after_ms: u64) {
254 self.wake_at(self.now_ms.saturating_add(after_ms));
255 }
256
257 pub fn next_wake(&self) -> Option<u64> {
259 self.next.get()
260 }
261}
262
263#[derive(Clone, Debug, PartialEq, Eq)]
265#[non_exhaustive]
266pub enum Event {
267 Resize { surface: String, geometry: Geometry },
269 Visibility { surface: String, visible: bool },
271 CapabilitiesChanged,
274 Driving(bool),
276 ValueChanged { key: String, value: Option<Json> },
278 Live { key: String, payload: Json },
280 LiveDeleted { key: String },
282 Plugin { name: String, payload: Json },
284 AccountChanged,
286 Key(Key),
288 Paste { surface: String, text: String },
290 Pointer(Pointer),
292 ThemeChanged,
295 Focus { surface: String, focused: bool },
297 Command(String),
299 CallResult {
303 id: crate::api::calls::CallId,
304 result: Result<Json>,
305 },
306 FileChanged { watch: u32, paths: Vec<String> },
309 WatchFailed { watch: u32, error: String },
311 ProcessOutput {
313 pid: u32,
314 stderr: bool,
315 bytes: Vec<u8>,
316 },
317 ProcessExited { pid: u32, status: i32 },
320 PaneChanged {
323 kind: crate::daemon::PaneChangeKind,
324 pane: crate::api::account::Pane,
325 },
326 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#[doc(hidden)]
407pub struct UiRuntime<P> {
408 plugin: RefCell<Option<P>>,
409 cx: RefCell<Context>,
410 last_frame_ms: Cell<Option<u64>>,
413 visible: RefCell<alloc::collections::BTreeSet<String>>,
415}
416
417unsafe 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 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}