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 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#[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#[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 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 pub fn elapsed(&self) -> u64 {
252 self.elapsed_ms
253 }
254
255 pub fn now_ms(&self) -> u64 {
257 self.now_ms
258 }
259
260 pub fn interval_ms(&self) -> u32 {
262 self.interval_ms
263 }
264
265 pub fn power(&self) -> Power {
266 self.power
267 }
268
269 pub fn request_frame(&self) {
271 self.wake_at(self.now_ms);
272 }
273
274 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 pub fn wake_after(&self, after_ms: u64) {
283 self.wake_at(self.now_ms.saturating_add(after_ms));
284 }
285
286 pub fn next_wake(&self) -> Option<u64> {
288 self.next.get()
289 }
290}
291
292#[derive(Clone, Debug, PartialEq, Eq)]
294#[non_exhaustive]
295pub enum Event {
296 Resize { surface: String, geometry: Geometry },
298 Visibility { surface: String, visible: bool },
300 CapabilitiesChanged,
303 Driving(bool),
305 ValueChanged { key: String, value: Option<Json> },
307 Live { key: String, payload: Json },
309 LiveDeleted { key: String },
311 Plugin { name: String, payload: Json },
313 AccountChanged,
315 Key(Key),
317 Paste { surface: String, text: String },
319 Pointer(Pointer),
321 ThemeChanged,
324 Focus { surface: String, focused: bool },
326 Command(String),
328 CallResult {
332 id: crate::api::calls::CallId,
333 result: Result<Json>,
334 },
335 FileChanged { watch: u32, paths: Vec<String> },
338 WatchFailed { watch: u32, error: String },
340 ProcessOutput {
342 pid: u32,
343 stderr: bool,
344 bytes: Vec<u8>,
345 },
346 ProcessExited { pid: u32, status: i32 },
349 PaneChanged {
352 kind: crate::daemon::PaneChangeKind,
353 pane: crate::api::account::Pane,
354 },
355 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#[doc(hidden)]
436pub struct UiRuntime<P> {
437 plugin: RefCell<Option<P>>,
438 cx: RefCell<Context>,
439 last_frame_ms: Cell<Option<u64>>,
442 visible: RefCell<alloc::collections::BTreeSet<String>>,
444}
445
446unsafe 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 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}