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