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