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