Skip to main content

standard_plugin/surface/
mod.rs

1//! Surfaces: typed views over the double-buffered shared buffer a UI plugin
2//! paints and the viewer samples.
3//!
4//! A [`Surface<Cells>`] paints graphemes, colours and attributes per cell; a
5//! [`Surface<Pixels>`] paints RGBA8 pixels. Both work the same way:
6//!
7//! - Create the surface once, by the id the manifest declares
8//!   (`Surface::<Cells>::new("card")`). The SDK asks the host for its
9//!   layout, allocates the region in the plugin's memory and attaches it.
10//! - Draw with the model's methods and the [`crate::Shapes`] helpers. Every
11//!   write records the rectangle it touched.
12//! - [`Surface::commit`] publishes the painted slot with the merged dirty
13//!   rectangles, bumps the sequence number, and switches slots. The next
14//!   slot starts as a copy of what was just committed (copied lazily, and
15//!   only the rectangles that changed), so drawing is always incremental.
16//! - On a resize the SDK rebinds every surface of that id to a new region
17//!   before the plugin sees [`crate::Event::Resize`]; the first commit at the
18//!   new size is fully dirty, and the old region is freed only after it,
19//!   as the host requires. Nothing is drawn while a surface has no size.
20//!
21//! The region layout (a 32-byte header of eight little-endian `u32` words
22//! `seq, model, cols, rows, px-w, px-h, cell-px-w, cell-px-h`, then two
23//! slots) is the contract in `wit/plugin.wit`.
24
25mod cells;
26mod dirty;
27mod graphic;
28mod pixels;
29
30use alloc::rc::{Rc, Weak};
31use alloc::string::String;
32use alloc::vec;
33use alloc::vec::Vec;
34use core::cell::RefCell;
35use core::marker::PhantomData;
36
37pub use cells::Cell;
38pub(crate) use cells::write_text_clipped;
39use dirty::DirtyRects;
40use graphic::SentGraphics;
41pub(crate) use pixels::Canvas;
42
43use crate::error::{Error, Result};
44use crate::geometry::{Geometry, Rect};
45use crate::host;
46use crate::local::instance_local;
47
48/// Bytes before slot 0.
49pub const HEADER_LEN: u32 = 32;
50/// Bytes per cell in the cell model.
51pub const CELL_LEN: u32 = 16;
52/// Bytes per pixel in the graphics model.
53pub const PIXEL_LEN: u32 = 4;
54
55const HEADER_WORDS: usize = (HEADER_LEN / 4) as usize;
56
57/// A surface's model, as the manifest declares it.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
59pub enum Model {
60    Cells,
61    Pixels,
62}
63
64impl Model {
65    pub fn as_str(self) -> &'static str {
66        match self {
67            Self::Cells => "cells",
68            Self::Pixels => "pixels",
69        }
70    }
71
72    fn word(self) -> u32 {
73        match self {
74            Self::Cells => 0,
75            Self::Pixels => 1,
76        }
77    }
78
79    /// Buffer words per unit (cell or pixel).
80    fn unit_words(self) -> usize {
81        match self {
82            Self::Cells => (CELL_LEN / 4) as usize,
83            Self::Pixels => 1,
84        }
85    }
86}
87
88/// How a region is laid out, as the host reports it.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub(crate) struct RegionLayout {
91    pub len: u32,
92    pub header_len: u32,
93    pub slot_len: u32,
94    pub model: Model,
95    pub geometry: Geometry,
96}
97
98impl RegionLayout {
99    /// The layout the host computes for a model and geometry.
100    pub(crate) fn new(model: Model, geometry: Geometry) -> Self {
101        let slot_len = match model {
102            Model::Cells => geometry.cols * geometry.rows * CELL_LEN,
103            Model::Pixels => geometry.px_w * geometry.px_h * PIXEL_LEN,
104        };
105        Self {
106            len: HEADER_LEN + 2 * slot_len,
107            header_len: HEADER_LEN,
108            slot_len,
109            model,
110            geometry,
111        }
112    }
113
114    /// Width and height in the model's units.
115    fn extent(&self) -> (u32, u32) {
116        match self.model {
117            Model::Cells => (self.geometry.cols, self.geometry.rows),
118            Model::Pixels => (self.geometry.px_w, self.geometry.px_h),
119        }
120    }
121
122    fn slot_words(&self) -> usize {
123        (self.slot_len / 4) as usize
124    }
125}
126
127mod sealed {
128    pub trait Sealed {}
129}
130
131/// The two surface models: [`Cells`] and [`Pixels`].
132pub trait SurfaceModel: sealed::Sealed {
133    const MODEL: Model;
134}
135
136/// The cell model: graphemes, colours and attributes per cell.
137#[derive(Clone, Copy, Debug)]
138pub enum Cells {}
139
140/// The graphics model: RGBA8 pixels, the surface's cells times the cell
141/// pixel size.
142#[derive(Clone, Copy, Debug)]
143pub enum Pixels {}
144
145impl sealed::Sealed for Cells {}
146impl sealed::Sealed for Pixels {}
147
148impl SurfaceModel for Cells {
149    const MODEL: Model = Model::Cells;
150}
151
152impl SurfaceModel for Pixels {
153    const MODEL: Model = Model::Pixels;
154}
155
156/// What the last commit published (for tests and diagnostics).
157/// An agent's pointer over a surface (`set_agent_pointer`): its tip in
158/// device pixels from the surface's top left, the surface's own pixels for
159/// a pixels surface and the viewer's cell pixel size for a cells surface.
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161pub struct AgentPointer {
162    pub x_px: u32,
163    pub y_px: u32,
164    /// A press (a click) plays at the tip as it gets there.
165    pub press: bool,
166}
167
168/// A cells surface taller than where it shows (`set_scroll`): the viewer
169/// scrolls the rows between the fixed ones with its own motion.
170#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
171pub struct Scroll {
172    /// The rows the plugin paints (at most [`Scroll::MAX_ROWS`]): the
173    /// surface's height while it is at least as tall as where it shows.
174    pub rows: u32,
175    /// Rows at the top that stay in place: a title or a toolbar.
176    pub fixed_top: u32,
177    /// Rows at the bottom that stay in place, at the bottom of where the
178    /// surface shows: a status line or key hints.
179    pub fixed_bottom: u32,
180}
181
182impl Scroll {
183    /// The most rows a scrolling surface paints.
184    pub const MAX_ROWS: u32 = 4096;
185
186    /// `rows` rows that all scroll.
187    pub const fn rows(rows: u32) -> Self {
188        Self {
189            rows,
190            fixed_top: 0,
191            fixed_bottom: 0,
192        }
193    }
194
195    /// The same rows with `top` rows fixed above and `bottom` rows fixed
196    /// below the scrolling ones.
197    pub const fn fixed(self, top: u32, bottom: u32) -> Self {
198        Self {
199            fixed_top: top,
200            fixed_bottom: bottom,
201            ..self
202        }
203    }
204}
205
206/// The scrolling rows of a scrolling surface that show now (`viewport`).
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
208pub struct Viewport {
209    /// The first scrolling row in view, in the surface's rows.
210    pub top: u32,
211    /// How many scrolling rows show at once.
212    pub rows: u32,
213}
214
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct CommitInfo {
217    /// The header sequence number the commit carried.
218    pub seq: u32,
219    /// The slot published, 0 or 1.
220    pub slot: u8,
221    /// The rectangles sent, in the model's units.
222    pub dirty: Vec<Rect>,
223    /// The first commit after a (re)bind: the whole surface.
224    pub full: bool,
225}
226
227#[derive(Debug)]
228enum Backend {
229    /// Bound to the host's surface of the same id.
230    Host,
231    /// A buffer of the plugin's own, never sent to the host.
232    Offscreen(Geometry),
233}
234
235#[derive(Debug)]
236struct Binding {
237    layout: RegionLayout,
238    /// Header and both slots, as words (the host reads them as bytes).
239    region: Vec<u32>,
240    /// The slot being painted.
241    back: u8,
242}
243
244#[derive(Debug)]
245pub(crate) struct Inner {
246    id: String,
247    model: Model,
248    backend: Backend,
249    binding: Option<Binding>,
250    /// The region a rebind replaced, freed after the next commit: the host
251    /// samples it until then.
252    retired: Option<Vec<u32>>,
253    dirty: DirtyRects,
254    /// Rectangles the back slot lacks from the last commit, copied in
255    /// before the first write to it.
256    sync: Vec<Rect>,
257    /// The next commit is the first since a bind: fully dirty.
258    full: bool,
259    seq: u32,
260    error: Option<Error>,
261    last_commit: Option<CommitInfo>,
262    /// An embedded program shows instead (`bind_embed`): nothing draws here, so
263    /// the surface holds no region, at any size.
264    embedded: bool,
265    /// What the host holds of this cells surface's graphics.
266    graphics: SentGraphics,
267}
268
269instance_local! {
270    fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
271}
272
273/// Rebinds every live surface named `id` after a resize.
274pub(crate) fn rebind_surfaces(id: &str) {
275    let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
276        registry.retain(|weak| weak.strong_count() > 0);
277        registry.iter().filter_map(Weak::upgrade).collect()
278    });
279    for surface in surfaces {
280        let mut inner = surface.borrow_mut();
281        if inner.id == id {
282            inner.rebind();
283        }
284    }
285}
286
287fn as_bytes(words: &[u32]) -> &[u8] {
288    // SAFETY: u32 has no padding and any byte pattern is a valid u8; the
289    // length is the words' byte length.
290    unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
291}
292
293fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
294    // SAFETY: as `as_bytes`; the slice is borrowed mutably and exclusively.
295    unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
296}
297
298impl Inner {
299    fn new(id: String, model: Model, backend: Backend) -> Self {
300        Self {
301            id,
302            model,
303            backend,
304            binding: None,
305            retired: None,
306            dirty: DirtyRects::default(),
307            sync: Vec::new(),
308            full: false,
309            seq: 0,
310            error: None,
311            last_commit: None,
312            embedded: false,
313            graphics: SentGraphics::default(),
314        }
315    }
316
317    fn rebind(&mut self) {
318        match self.bind() {
319            Ok(_) => self.error = None,
320            Err(error) => self.error = Some(error),
321        }
322    }
323
324    /// Asks for the current layout and, when the surface has a size, binds
325    /// a new zeroed region carrying its header. `Ok(false)`: no size yet.
326    fn bind(&mut self) -> Result<bool> {
327        if self.embedded {
328            // The host lets go of the region before its memory goes.
329            if self.binding.take().is_some() && matches!(self.backend, Backend::Host) {
330                host::surface_detach(&self.id)?;
331            }
332            self.retired = None;
333            return Ok(false);
334        }
335        let layout = match &self.backend {
336            Backend::Host => host::surface_layout(&self.id)?,
337            Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
338        };
339        if layout.model != self.model {
340            return Err(Error::WrongModel {
341                surface: self.id.clone(),
342                expected: self.model,
343                found: layout.model,
344            });
345        }
346        if layout.geometry.is_empty() {
347            return Ok(false);
348        }
349        let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
350        let g = layout.geometry;
351        region[..HEADER_WORDS].copy_from_slice(&[
352            self.seq,
353            layout.model.word(),
354            g.cols,
355            g.rows,
356            g.px_w,
357            g.px_h,
358            g.cell_px_w,
359            g.cell_px_h,
360        ]);
361        if let Backend::Host = self.backend {
362            host::surface_attach(&self.id, &as_bytes(&region)[..layout.len as usize])?;
363        }
364        if let Some(previous) = self.binding.take() {
365            // The host samples the region it had before the first resize
366            // until the next commit; an intermediate one it never read
367            // again once replaced.
368            if self.retired.is_none() {
369                self.retired = Some(previous.region);
370            }
371        }
372        self.binding = Some(Binding {
373            layout,
374            region,
375            back: 0,
376        });
377        self.full = true;
378        self.dirty.clear();
379        self.sync.clear();
380        // The host keeps the graphics that still fit the new region.
381        self.graphics.rebound(layout.geometry);
382        Ok(true)
383    }
384
385    fn ensure_bound(&mut self) -> Result<&mut Binding> {
386        if self.binding.is_none() {
387            if let Some(error) = self.error.clone() {
388                return Err(error);
389            }
390            self.bind()?;
391        }
392        let id = &self.id;
393        self.binding.as_mut().ok_or_else(|| Error::NotAttached {
394            surface: id.clone(),
395        })
396    }
397
398    fn extent(&self) -> (u32, u32) {
399        self.binding
400            .as_ref()
401            .map_or((0, 0), |binding| binding.layout.extent())
402    }
403
404    /// Copies the pending rectangles from the front slot into the back.
405    fn apply_sync(&mut self) {
406        let Some(binding) = self.binding.as_mut() else {
407            self.sync.clear();
408            return;
409        };
410        if self.sync.is_empty() {
411            return;
412        }
413        let (width, _) = binding.layout.extent();
414        let unit = binding.layout.model.unit_words();
415        let slot_words = binding.layout.slot_words();
416        let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
417        let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
418        for rect in self.sync.drain(..) {
419            for y in rect.y..rect.bottom() {
420                let start = (y as usize * width as usize + rect.x as usize) * unit;
421                let len = rect.w as usize * unit;
422                binding
423                    .region
424                    .copy_within(front + start..front + start + len, back + start);
425            }
426        }
427    }
428
429    /// The back slot as words, synced with the last commit, for a write
430    /// that will record its own dirty rectangles. `None` while unbound.
431    fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
432        self.apply_sync();
433        let binding = self.binding.as_mut()?;
434        let slot_words = binding.layout.slot_words();
435        let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
436        Some((
437            &mut binding.region[start..start + slot_words],
438            binding.layout,
439            &mut self.dirty,
440        ))
441    }
442
443    /// The back slot for a write that replaces all of it: the sync is
444    /// skipped and the whole surface is dirty.
445    fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
446        self.sync.clear();
447        let binding = self.binding.as_mut()?;
448        let (width, height) = binding.layout.extent();
449        self.dirty
450            .add(Rect::new(0, 0, width, height), width, height);
451        let slot_words = binding.layout.slot_words();
452        let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
453        Some((
454            &mut binding.region[start..start + slot_words],
455            binding.layout,
456        ))
457    }
458
459    fn mark_dirty(&mut self, rect: Rect) {
460        self.apply_sync();
461        let (width, height) = self.extent();
462        self.dirty.add(rect, width, height);
463    }
464
465    fn commit(&mut self) -> Result<bool> {
466        self.ensure_bound()?;
467        let (width, height) = self.extent();
468        let full = self.full;
469        let rects = if full {
470            self.dirty.clear();
471            if width == 0 || height == 0 {
472                Vec::new()
473            } else {
474                vec![Rect::new(0, 0, width, height)]
475            }
476        } else {
477            self.dirty.take()
478        };
479        if let Backend::Host = self.backend {
480            self.graphics.remove_undrawn(&self.id)?;
481        }
482        if rects.is_empty() {
483            return self.commit_graphics();
484        }
485        let seq = self.seq.wrapping_add(1);
486        let Some(binding) = self.binding.as_mut() else {
487            return Ok(false);
488        };
489        binding.region[0] = seq;
490        let slot = binding.back;
491        if let Backend::Host = self.backend
492            && let Err(error) = host::surface_commit(&self.id, slot, &rects)
493        {
494            for rect in rects {
495                self.dirty.add(rect, width, height);
496            }
497            return Err(error);
498        }
499        binding.back ^= 1;
500        self.graphics.published();
501        self.seq = seq;
502        self.full = false;
503        self.retired = None;
504        self.sync = rects.clone();
505        self.last_commit = Some(CommitInfo {
506            seq,
507            slot,
508            dirty: rects,
509            full,
510        });
511        Ok(true)
512    }
513
514    /// A commit that changes no cell: it publishes only the graphics. The
515    /// slots stay as they are.
516    fn commit_graphics(&mut self) -> Result<bool> {
517        let Some(binding) = self.binding.as_ref() else {
518            return Ok(false);
519        };
520        if !self.graphics.changed() || !matches!(self.backend, Backend::Host) {
521            return Ok(false);
522        }
523        host::surface_commit(&self.id, binding.back, &[])?;
524        self.graphics.published();
525        Ok(true)
526    }
527}
528
529/// A surface in model `M` ([`Cells`] or [`Pixels`]). See the module docs.
530#[derive(Debug)]
531pub struct Surface<M: SurfaceModel> {
532    inner: Rc<RefCell<Inner>>,
533    model: PhantomData<M>,
534}
535
536impl<M: SurfaceModel> Surface<M> {
537    /// The manifest's surface `id`. Binds at once when the viewer has laid
538    /// it out, else on its first [`crate::Event::Resize`].
539    pub fn new(id: &str) -> Self {
540        let surface = Self::new_unbound(id);
541        surface.inner.borrow_mut().rebind();
542        surface
543    }
544
545    fn new_unbound(id: &str) -> Self {
546        let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
547        registry(|registry| registry.push(Rc::downgrade(&inner)));
548        Self {
549            inner,
550            model: PhantomData,
551        }
552    }
553
554    /// A surface of the plugin's own that the host never sees: for tests,
555    /// and to draw into a buffer before blitting it. Commits are recorded
556    /// ([`Surface::last_commit`]) but go nowhere.
557    pub fn offscreen(geometry: Geometry) -> Self {
558        let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
559        inner.rebind();
560        Self {
561            inner: Rc::new(RefCell::new(inner)),
562            model: PhantomData,
563        }
564    }
565
566    /// Resizes an offscreen surface as a viewer resize would: a new
567    /// zeroed region, the next commit fully dirty. No-op for a host
568    /// surface (the host resizes those).
569    pub fn resize_offscreen(&mut self, geometry: Geometry) {
570        let mut inner = self.inner.borrow_mut();
571        if let Backend::Offscreen(current) = &mut inner.backend {
572            *current = geometry;
573            inner.rebind();
574        }
575    }
576
577    pub fn id(&self) -> String {
578        self.inner.borrow().id.clone()
579    }
580
581    /// The current geometry; `None` until the viewer lays the surface out.
582    pub fn geometry(&self) -> Option<Geometry> {
583        let inner = self.inner.borrow();
584        inner
585            .binding
586            .as_ref()
587            .map(|binding| binding.layout.geometry)
588    }
589
590    /// Width and height in the model's units: cells, or pixels.
591    pub fn size(&self) -> (u32, u32) {
592        self.inner.borrow().extent()
593    }
594
595    /// Asks the viewer for `cols` by `rows` cells (0: its choice in that
596    /// dimension) instead of the manifest's size; see
597    /// [`Context::request_size`](crate::Context::request_size).
598    pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
599        crate::host::surface_request_size(&self.id(), cols, rows)
600    }
601
602    /// [`Surface::request_size`] in device pixels: the viewer asks for the
603    /// whole cells that hold them. `Unavailable` while the viewer has no
604    /// cell pixel size.
605    pub fn request_size_px(&self, width: u32, height: u32) -> Result<()> {
606        crate::host::surface_request_size_px(&self.id(), width, height)
607    }
608
609    /// Sets the short label the viewer shows at the right end of this
610    /// surface's chrome title; see
611    /// [`Context::set_label`](crate::Context::set_label).
612    pub fn set_label(&self, label: Option<&str>) -> Result<()> {
613        crate::host::surface_set_label(&self.id(), label)
614    }
615
616    /// Copies selected text to the viewer clipboard during a user gesture.
617    /// Text is limited to 64 KiB; this grants no clipboard read access.
618    pub fn copy_text(&self, text: &str) -> Result<()> {
619        crate::host::surface_copy_text(&self.id(), text)
620    }
621
622    /// Places the viewer's text cursor at (`col`, `row`) of this surface
623    /// while it takes keys, or removes it; see
624    /// [`Context::set_caret`](crate::Context::set_caret).
625    pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
626        crate::host::surface_set_caret(&self.id(), caret)
627    }
628
629    /// Paints this cells surface `scroll.rows` rows tall, for the viewer to
630    /// scroll, or returns it to the size it shows at; see
631    /// [`Context::set_scroll`](crate::Context::set_scroll).
632    pub fn set_scroll(&self, scroll: Option<Scroll>) -> Result<()> {
633        crate::host::surface_set_scroll(&self.id(), scroll)
634    }
635
636    /// Brings rows `first..=last` of this scrolling surface into view; see
637    /// [`Context::reveal`](crate::Context::reveal).
638    pub fn reveal(&self, first: u32, last: u32) -> Result<()> {
639        crate::host::surface_reveal(&self.id(), first, last)
640    }
641
642    /// The scrolling rows that show now; see
643    /// [`Context::viewport`](crate::Context::viewport).
644    pub fn viewport(&self) -> Result<Option<Viewport>> {
645        crate::host::surface_viewport(&self.id())
646    }
647
648    /// Shows an agent's pointer over this surface, or removes it; see
649    /// [`Context::set_agent_pointer`](crate::Context::set_agent_pointer).
650    pub fn set_agent_pointer(&self, pointer: Option<AgentPointer>) -> Result<()> {
651        crate::host::surface_set_agent_pointer(&self.id(), pointer)
652    }
653
654    pub fn is_attached(&self) -> bool {
655        self.inner.borrow().binding.is_some()
656    }
657
658    /// Whether anything was drawn since the last commit (or the next commit
659    /// is the first at a new size).
660    pub fn is_dirty(&self) -> bool {
661        let inner = self.inner.borrow();
662        inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
663    }
664
665    /// Records a rectangle as changed, after writing through a raw slice.
666    pub fn mark_dirty(&mut self, rect: Rect) {
667        self.inner.borrow_mut().mark_dirty(rect);
668    }
669
670    /// Publishes what was drawn since the last commit and switches slots.
671    /// `Ok(false)` when nothing changed (no host call, no frame). The
672    /// first commit after a (re)bind covers the whole surface.
673    pub fn commit(&mut self) -> Result<bool> {
674        self.inner.borrow_mut().commit()
675    }
676
677    /// What the last commit published.
678    pub fn last_commit(&self) -> Option<CommitInfo> {
679        self.inner.borrow().last_commit.clone()
680    }
681
682    /// The rectangles the next commit would send (without the fully dirty
683    /// first commit's).
684    pub fn pending_dirty(&self) -> Vec<Rect> {
685        self.inner.borrow().dirty.rects().to_vec()
686    }
687
688    /// Unbinds the surface from the host. Dropping the surface does this.
689    pub fn detach(&mut self) -> Result<()> {
690        let mut inner = self.inner.borrow_mut();
691        inner.graphics = SentGraphics::default();
692        if inner.binding.take().is_some()
693            && let Backend::Host = inner.backend
694        {
695            inner.retired = None;
696            return host::surface_detach(&inner.id);
697        }
698        Ok(())
699    }
700}
701
702impl<M: SurfaceModel> Drop for Surface<M> {
703    fn drop(&mut self) {
704        // The host must stop reading the region before its memory is
705        // freed.
706        let _ = self.detach();
707    }
708}
709
710/// A surface whose manifest lists both models (`"model": ["pixels",
711/// "cells"]`): the viewer picks one per its capabilities and may switch
712/// (graphics arriving or leaving), which the plugin sees as a
713/// [`crate::Event::Resize`]. [`AnySurface::get`] hands out the surface in
714/// the model the viewer uses now.
715#[derive(Debug)]
716pub struct AnySurface {
717    id: String,
718    surface: Option<AnySurfaceInner>,
719}
720
721#[derive(Debug)]
722enum AnySurfaceInner {
723    Cells(Surface<Cells>),
724    Pixels(Surface<Pixels>),
725}
726
727/// [`AnySurface`] in the model the viewer uses now.
728#[derive(Debug)]
729pub enum AnySurfaceMut<'a> {
730    Cells(&'a mut Surface<Cells>),
731    Pixels(&'a mut Surface<Pixels>),
732}
733
734impl AnySurface {
735    /// The manifest's surface `id`, in the model the viewer picked.
736    pub fn new(id: &str) -> Self {
737        let mut surface = Self {
738            id: id.into(),
739            surface: None,
740        };
741        surface.sync();
742        surface
743    }
744
745    pub fn id(&self) -> &str {
746        &self.id
747    }
748
749    /// The model the surface paints in now.
750    pub fn model(&self) -> Model {
751        match self.surface {
752            Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
753            _ => Model::Cells,
754        }
755    }
756
757    fn current_model(&self) -> Option<Model> {
758        let inner = match self.surface.as_ref()? {
759            AnySurfaceInner::Cells(surface) => &surface.inner,
760            AnySurfaceInner::Pixels(surface) => &surface.inner,
761        };
762        let inner = inner.borrow();
763        match &inner.error {
764            Some(Error::WrongModel { found, .. }) => Some(*found),
765            _ => Some(inner.model),
766        }
767    }
768
769    /// Follows a model switch: `true` when the surface was recreated in the
770    /// other model (it paints from scratch at its next commit).
771    pub fn sync(&mut self) -> bool {
772        let wanted = match self.current_model() {
773            Some(model) => model,
774            None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
775        };
776        if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
777            return false;
778        }
779        // The old surface detaches before the new one attaches under the
780        // same id.
781        self.surface = None;
782        self.surface = Some(match wanted {
783            Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
784            Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
785        });
786        true
787    }
788
789    /// The surface in its current model, after following a switch.
790    pub fn get(&mut self) -> AnySurfaceMut<'_> {
791        self.sync();
792        match self.surface.as_mut() {
793            Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
794            Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
795            None => unreachable!("sync always leaves a surface"),
796        }
797    }
798}
799
800/// The instances of a `pane.footer` or `pane.header` surface (one per pane
801/// the viewer shows, named `<surface>@<pane>`) or of a `machine.after`
802/// surface (one per machine, `<surface>@<machine>`). Pass every event to
803/// [`Instances::event`]; it creates an instance's surface when the viewer
804/// first sizes it and drops it when the viewer removes it (a zero-size
805/// resize), and says which pane or machine changed.
806#[derive(Debug)]
807pub struct Instances<M: SurfaceModel> {
808    surface: String,
809    panes: alloc::collections::BTreeMap<String, Surface<M>>,
810}
811
812/// The pane an instance id names, when `id` is an instance of `surface`.
813pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
814    id.strip_prefix(surface)?.strip_prefix('@')
815}
816
817impl<M: SurfaceModel> Instances<M> {
818    /// The instances of the manifest's surface `surface`.
819    pub fn new(surface: &str) -> Self {
820        Self {
821            surface: surface.into(),
822            panes: alloc::collections::BTreeMap::new(),
823        }
824    }
825
826    /// Follows the viewer: returns the pane whose instance the event is
827    /// about (created, resized, shown, hidden or removed), if any.
828    pub fn event(&mut self, event: &crate::Event) -> Option<String> {
829        let (id, removed) = match event {
830            crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
831            crate::Event::Visibility { surface, .. } => (surface, false),
832            _ => return None,
833        };
834        let pane = String::from(instance_pane(&self.surface, id)?);
835        if removed {
836            self.panes.remove(&pane);
837        } else if !self.panes.contains_key(&pane) {
838            self.panes.insert(pane.clone(), Surface::new(id));
839        }
840        Some(pane)
841    }
842
843    pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
844        self.panes.get_mut(pane)
845    }
846
847    /// The instance of `owner` (a pane, machine or project id), created when
848    /// the viewer has not shown it yet: a machine or project row at zero
849    /// rows asks for rows through it
850    /// ([`Surface::request_size`]).
851    pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
852        let surface = &self.surface;
853        self.panes
854            .entry(String::from(owner))
855            .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
856    }
857
858    /// Every live instance, by pane.
859    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
860        self.panes
861            .iter_mut()
862            .map(|(pane, surface)| (pane.as_str(), surface))
863    }
864
865    pub fn len(&self) -> usize {
866        self.panes.len()
867    }
868
869    pub fn is_empty(&self) -> bool {
870        self.panes.is_empty()
871    }
872}
873
874impl Surface<Pixels> {
875    /// A bound surface's buffers go: an embedded program fills a large
876    /// window, and its region would only hold memory nothing draws into.
877    fn embed_bound(&self, bound: bool) {
878        let mut inner = self.inner.borrow_mut();
879        inner.embedded = bound;
880        inner.rebind();
881    }
882
883    /// A pixels surface that only ever hosts an embedded program: it holds
884    /// no buffer at any size, from the start, so a large window costs the
885    /// plugin no memory before [`Surface::bind_embed`]; drawing here shows
886    /// nothing.
887    pub fn for_embed(id: &str) -> Self {
888        let surface = Self::new_unbound(id);
889        surface.inner.borrow_mut().embedded = true;
890        surface
891    }
892
893    /// Hosts an embedded pixel app in this pixels surface (a native viewer
894    /// only): the viewer opens a private socket and terminal and tells the
895    /// plugin their paths with [`EmbedEvent::Ready`]. Start the program
896    /// with `PIXEL_EMBED` and `PIXEL_TTY` set to them (from the companion,
897    /// with `daemon::process`); the viewer then shows its frames and hands
898    /// it this surface's size, colours, focus, keys, pointer and pastes.
899    /// The surface holds no buffer while it is bound.
900    ///
901    /// [`EmbedEvent::Ready`]: crate::embed::EmbedEvent::Ready
902    pub fn bind_embed(&self) -> Result<()> {
903        crate::host::surface_bind_embed(&self.id(), true)?;
904        self.embed_bound(true);
905        Ok(())
906    }
907
908    /// Ends the embedded program's connection and shows this surface's own
909    /// buffer again.
910    pub fn unbind_embed(&self) -> Result<()> {
911        crate::host::surface_bind_embed(&self.id(), false)?;
912        self.embed_bound(false);
913        Ok(())
914    }
915}