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 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 pub fn open_url(&self, url: &str) -> crate::Result<()> {
142 crate::host::url_open(url)
143 }
144
145 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 pub fn close(&self, surface: &str) -> crate::Result<()> {
163 crate::host::surface_close(surface)
164 }
165
166 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 pub fn set_label(&self, surface: &str, label: Option<&str>) -> crate::Result<()> {
180 crate::host::surface_set_label(surface, label)
181 }
182
183 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#[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#[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 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 pub fn elapsed(&self) -> u64 {
236 self.elapsed_ms
237 }
238
239 pub fn now_ms(&self) -> u64 {
241 self.now_ms
242 }
243
244 pub fn interval_ms(&self) -> u32 {
246 self.interval_ms
247 }
248
249 pub fn power(&self) -> Power {
250 self.power
251 }
252
253 pub fn request_frame(&self) {
255 self.wake_at(self.now_ms);
256 }
257
258 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 pub fn wake_after(&self, after_ms: u64) {
267 self.wake_at(self.now_ms.saturating_add(after_ms));
268 }
269
270 pub fn next_wake(&self) -> Option<u64> {
272 self.next.get()
273 }
274}
275
276#[derive(Clone, Debug, PartialEq, Eq)]
278#[non_exhaustive]
279pub enum Event {
280 Resize { surface: String, geometry: Geometry },
282 Visibility { surface: String, visible: bool },
284 CapabilitiesChanged,
287 Driving(bool),
289 ValueChanged { key: String, value: Option<Json> },
291 Live { key: String, payload: Json },
293 LiveDeleted { key: String },
295 Plugin { name: String, payload: Json },
297 AccountChanged,
299 Key(Key),
301 Paste { surface: String, text: String },
303 Pointer(Pointer),
305 ThemeChanged,
308 Focus { surface: String, focused: bool },
310 Command(String),
312 CallResult {
316 id: crate::api::calls::CallId,
317 result: Result<Json>,
318 },
319 FileChanged { watch: u32, paths: Vec<String> },
322 WatchFailed { watch: u32, error: String },
324 ProcessOutput {
326 pid: u32,
327 stderr: bool,
328 bytes: Vec<u8>,
329 },
330 ProcessExited { pid: u32, status: i32 },
333 PaneChanged {
336 kind: crate::daemon::PaneChangeKind,
337 pane: crate::api::account::Pane,
338 },
339 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#[doc(hidden)]
420pub struct UiRuntime<P> {
421 plugin: RefCell<Option<P>>,
422 cx: RefCell<Context>,
423 last_frame_ms: Cell<Option<u64>>,
426 visible: RefCell<alloc::collections::BTreeSet<String>>,
428}
429
430unsafe 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 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}