standard-plugin-sdk 0.1.0

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Surfaces: typed views over the double-buffered shared buffer a UI plugin
//! paints and the viewer samples.
//!
//! A [`Surface<Cells>`] paints graphemes, colours and attributes per cell; a
//! [`Surface<Pixels>`] paints RGBA8 pixels. Both work the same way:
//!
//! - Create the surface once, by the id the manifest declares
//!   (`Surface::<Cells>::new("card")`). The SDK asks the host for its
//!   layout, allocates the region in the plugin's memory and attaches it.
//! - Draw with the model's methods and the [`crate::Shapes`] helpers. Every
//!   write records the rectangle it touched.
//! - [`Surface::commit`] publishes the painted slot with the merged dirty
//!   rectangles, bumps the sequence number, and switches slots. The next
//!   slot starts as a copy of what was just committed (copied lazily, and
//!   only the rectangles that changed), so drawing is always incremental.
//! - On a resize the SDK rebinds every surface of that id to a new region
//!   before the plugin sees [`crate::Event::Resize`]; the first commit at the
//!   new size is fully dirty, and the old region is freed only after it,
//!   as the host requires. Nothing is drawn while a surface has no size.
//!
//! The region layout (a 32-byte header of eight little-endian `u32` words
//! `seq, model, cols, rows, px-w, px-h, cell-px-w, cell-px-h`, then two
//! slots) is the contract in `wit/plugin.wit`.

mod cells;
mod dirty;
mod pixels;

use alloc::rc::{Rc, Weak};
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use core::marker::PhantomData;

pub use cells::Cell;
pub(crate) use cells::write_text_clipped;
use dirty::DirtyRects;
pub(crate) use pixels::Canvas;

use crate::error::{Error, Result};
use crate::geometry::{Geometry, Rect};
use crate::host;
use crate::local::instance_local;

/// Bytes before slot 0.
pub const HEADER_LEN: u32 = 32;
/// Bytes per cell in the cell model.
pub const CELL_LEN: u32 = 16;
/// Bytes per pixel in the graphics model.
pub const PIXEL_LEN: u32 = 4;

const HEADER_WORDS: usize = (HEADER_LEN / 4) as usize;

/// A surface's model, as the manifest declares it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Model {
    Cells,
    Pixels,
}

impl Model {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Cells => "cells",
            Self::Pixels => "pixels",
        }
    }

    fn word(self) -> u32 {
        match self {
            Self::Cells => 0,
            Self::Pixels => 1,
        }
    }

    /// Buffer words per unit (cell or pixel).
    fn unit_words(self) -> usize {
        match self {
            Self::Cells => (CELL_LEN / 4) as usize,
            Self::Pixels => 1,
        }
    }
}

/// How a region is laid out, as the host reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RegionLayout {
    pub len: u32,
    pub header_len: u32,
    pub slot_len: u32,
    pub model: Model,
    pub geometry: Geometry,
}

impl RegionLayout {
    /// The layout the host computes for a model and geometry.
    pub(crate) fn new(model: Model, geometry: Geometry) -> Self {
        let slot_len = match model {
            Model::Cells => geometry.cols * geometry.rows * CELL_LEN,
            Model::Pixels => geometry.px_w * geometry.px_h * PIXEL_LEN,
        };
        Self {
            len: HEADER_LEN + 2 * slot_len,
            header_len: HEADER_LEN,
            slot_len,
            model,
            geometry,
        }
    }

    /// Width and height in the model's units.
    fn extent(&self) -> (u32, u32) {
        match self.model {
            Model::Cells => (self.geometry.cols, self.geometry.rows),
            Model::Pixels => (self.geometry.px_w, self.geometry.px_h),
        }
    }

    fn slot_words(&self) -> usize {
        (self.slot_len / 4) as usize
    }
}

mod sealed {
    pub trait Sealed {}
}

/// The two surface models: [`Cells`] and [`Pixels`].
pub trait SurfaceModel: sealed::Sealed {
    const MODEL: Model;
}

/// The cell model: graphemes, colours and attributes per cell.
#[derive(Clone, Copy, Debug)]
pub enum Cells {}

/// The graphics model: RGBA8 pixels, the surface's cells times the cell
/// pixel size.
#[derive(Clone, Copy, Debug)]
pub enum Pixels {}

impl sealed::Sealed for Cells {}
impl sealed::Sealed for Pixels {}

impl SurfaceModel for Cells {
    const MODEL: Model = Model::Cells;
}

impl SurfaceModel for Pixels {
    const MODEL: Model = Model::Pixels;
}

/// What the last commit published (for tests and diagnostics).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommitInfo {
    /// The header sequence number the commit carried.
    pub seq: u32,
    /// The slot published, 0 or 1.
    pub slot: u8,
    /// The rectangles sent, in the model's units.
    pub dirty: Vec<Rect>,
    /// The first commit after a (re)bind: the whole surface.
    pub full: bool,
}

#[derive(Debug)]
enum Backend {
    /// Bound to the host's surface of the same id.
    Host,
    /// A buffer of the plugin's own, never sent to the host.
    Offscreen(Geometry),
}

#[derive(Debug)]
struct Binding {
    layout: RegionLayout,
    /// Header and both slots, as words (the host reads them as bytes).
    region: Vec<u32>,
    /// The slot being painted.
    back: u8,
}

#[derive(Debug)]
pub(crate) struct Inner {
    id: String,
    model: Model,
    backend: Backend,
    binding: Option<Binding>,
    /// The region a rebind replaced, freed after the next commit: the host
    /// samples it until then.
    retired: Option<Vec<u32>>,
    dirty: DirtyRects,
    /// Rectangles the back slot lacks from the last commit, copied in
    /// before the first write to it.
    sync: Vec<Rect>,
    /// The next commit is the first since a bind: fully dirty.
    full: bool,
    seq: u32,
    error: Option<Error>,
    last_commit: Option<CommitInfo>,
}

instance_local! {
    fn registry() -> Vec<Weak<RefCell<Inner>>> = Vec::new();
}

/// Rebinds every live surface named `id` after a resize.
pub(crate) fn rebind_surfaces(id: &str) {
    let surfaces: Vec<Rc<RefCell<Inner>>> = registry(|registry| {
        registry.retain(|weak| weak.strong_count() > 0);
        registry.iter().filter_map(Weak::upgrade).collect()
    });
    for surface in surfaces {
        let mut inner = surface.borrow_mut();
        if inner.id == id {
            inner.rebind();
        }
    }
}

fn as_bytes(words: &[u32]) -> &[u8] {
    // SAFETY: u32 has no padding and any byte pattern is a valid u8; the
    // length is the words' byte length.
    unsafe { core::slice::from_raw_parts(words.as_ptr().cast::<u8>(), words.len() * 4) }
}

fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] {
    // SAFETY: as `as_bytes`; the slice is borrowed mutably and exclusively.
    unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast::<u8>(), words.len() * 4) }
}

impl Inner {
    fn new(id: String, model: Model, backend: Backend) -> Self {
        Self {
            id,
            model,
            backend,
            binding: None,
            retired: None,
            dirty: DirtyRects::default(),
            sync: Vec::new(),
            full: false,
            seq: 0,
            error: None,
            last_commit: None,
        }
    }

    fn rebind(&mut self) {
        match self.bind() {
            Ok(_) => self.error = None,
            Err(error) => self.error = Some(error),
        }
    }

    /// Asks for the current layout and, when the surface has a size, binds
    /// a new zeroed region carrying its header. `Ok(false)`: no size yet.
    fn bind(&mut self) -> Result<bool> {
        let layout = match &self.backend {
            Backend::Host => host::surface_layout(&self.id)?,
            Backend::Offscreen(geometry) => RegionLayout::new(self.model, *geometry),
        };
        if layout.model != self.model {
            return Err(Error::WrongModel {
                surface: self.id.clone(),
                expected: self.model,
                found: layout.model,
            });
        }
        if layout.geometry.is_empty() {
            return Ok(false);
        }
        let mut region = vec![0u32; (layout.len as usize).div_ceil(4)];
        let g = layout.geometry;
        region[..HEADER_WORDS].copy_from_slice(&[
            self.seq,
            layout.model.word(),
            g.cols,
            g.rows,
            g.px_w,
            g.px_h,
            g.cell_px_w,
            g.cell_px_h,
        ]);
        if let Backend::Host = self.backend {
            host::surface_attach(&self.id, &as_bytes(&region)[..layout.len as usize])?;
        }
        if let Some(previous) = self.binding.take() {
            // The host samples the region it had before the first resize
            // until the next commit; an intermediate one it never read
            // again once replaced.
            if self.retired.is_none() {
                self.retired = Some(previous.region);
            }
        }
        self.binding = Some(Binding {
            layout,
            region,
            back: 0,
        });
        self.full = true;
        self.dirty.clear();
        self.sync.clear();
        Ok(true)
    }

    fn ensure_bound(&mut self) -> Result<&mut Binding> {
        if self.binding.is_none() {
            if let Some(error) = self.error.clone() {
                return Err(error);
            }
            self.bind()?;
        }
        let id = &self.id;
        self.binding.as_mut().ok_or_else(|| Error::NotAttached {
            surface: id.clone(),
        })
    }

    fn extent(&self) -> (u32, u32) {
        self.binding
            .as_ref()
            .map_or((0, 0), |binding| binding.layout.extent())
    }

    /// Copies the pending rectangles from the front slot into the back.
    fn apply_sync(&mut self) {
        let Some(binding) = self.binding.as_mut() else {
            self.sync.clear();
            return;
        };
        if self.sync.is_empty() {
            return;
        }
        let (width, _) = binding.layout.extent();
        let unit = binding.layout.model.unit_words();
        let slot_words = binding.layout.slot_words();
        let front = HEADER_WORDS + usize::from(binding.back ^ 1) * slot_words;
        let back = HEADER_WORDS + usize::from(binding.back) * slot_words;
        for rect in self.sync.drain(..) {
            for y in rect.y..rect.bottom() {
                let start = (y as usize * width as usize + rect.x as usize) * unit;
                let len = rect.w as usize * unit;
                binding
                    .region
                    .copy_within(front + start..front + start + len, back + start);
            }
        }
    }

    /// The back slot as words, synced with the last commit, for a write
    /// that will record its own dirty rectangles. `None` while unbound.
    fn back(&mut self) -> Option<(&mut [u32], RegionLayout, &mut DirtyRects)> {
        self.apply_sync();
        let binding = self.binding.as_mut()?;
        let slot_words = binding.layout.slot_words();
        let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
        Some((
            &mut binding.region[start..start + slot_words],
            binding.layout,
            &mut self.dirty,
        ))
    }

    /// The back slot for a write that replaces all of it: the sync is
    /// skipped and the whole surface is dirty.
    fn back_discard(&mut self) -> Option<(&mut [u32], RegionLayout)> {
        self.sync.clear();
        let binding = self.binding.as_mut()?;
        let (width, height) = binding.layout.extent();
        self.dirty
            .add(Rect::new(0, 0, width, height), width, height);
        let slot_words = binding.layout.slot_words();
        let start = HEADER_WORDS + usize::from(binding.back) * slot_words;
        Some((
            &mut binding.region[start..start + slot_words],
            binding.layout,
        ))
    }

    fn mark_dirty(&mut self, rect: Rect) {
        self.apply_sync();
        let (width, height) = self.extent();
        self.dirty.add(rect, width, height);
    }

    fn commit(&mut self) -> Result<bool> {
        self.ensure_bound()?;
        let (width, height) = self.extent();
        let full = self.full;
        let rects = if full {
            self.dirty.clear();
            if width == 0 || height == 0 {
                Vec::new()
            } else {
                vec![Rect::new(0, 0, width, height)]
            }
        } else {
            self.dirty.take()
        };
        if rects.is_empty() {
            return Ok(false);
        }
        let seq = self.seq.wrapping_add(1);
        let Some(binding) = self.binding.as_mut() else {
            return Ok(false);
        };
        binding.region[0] = seq;
        let slot = binding.back;
        if let Backend::Host = self.backend
            && let Err(error) = host::surface_commit(&self.id, slot, &rects)
        {
            for rect in rects {
                self.dirty.add(rect, width, height);
            }
            return Err(error);
        }
        binding.back ^= 1;
        self.seq = seq;
        self.full = false;
        self.retired = None;
        self.sync = rects.clone();
        self.last_commit = Some(CommitInfo {
            seq,
            slot,
            dirty: rects,
            full,
        });
        Ok(true)
    }
}

/// A surface in model `M` ([`Cells`] or [`Pixels`]). See the module docs.
#[derive(Debug)]
pub struct Surface<M: SurfaceModel> {
    inner: Rc<RefCell<Inner>>,
    model: PhantomData<M>,
}

impl<M: SurfaceModel> Surface<M> {
    /// The manifest's surface `id`. Binds at once when the viewer has laid
    /// it out, else on its first [`crate::Event::Resize`].
    pub fn new(id: &str) -> Self {
        let inner = Rc::new(RefCell::new(Inner::new(id.into(), M::MODEL, Backend::Host)));
        registry(|registry| registry.push(Rc::downgrade(&inner)));
        inner.borrow_mut().rebind();
        Self {
            inner,
            model: PhantomData,
        }
    }

    /// A surface of the plugin's own that the host never sees: for tests,
    /// and to draw into a buffer before blitting it. Commits are recorded
    /// ([`Surface::last_commit`]) but go nowhere.
    pub fn offscreen(geometry: Geometry) -> Self {
        let mut inner = Inner::new("offscreen".into(), M::MODEL, Backend::Offscreen(geometry));
        inner.rebind();
        Self {
            inner: Rc::new(RefCell::new(inner)),
            model: PhantomData,
        }
    }

    /// Resizes an offscreen surface as a viewer resize would: a new
    /// zeroed region, the next commit fully dirty. No-op for a host
    /// surface (the host resizes those).
    pub fn resize_offscreen(&mut self, geometry: Geometry) {
        let mut inner = self.inner.borrow_mut();
        if let Backend::Offscreen(current) = &mut inner.backend {
            *current = geometry;
            inner.rebind();
        }
    }

    pub fn id(&self) -> String {
        self.inner.borrow().id.clone()
    }

    /// The current geometry; `None` until the viewer lays the surface out.
    pub fn geometry(&self) -> Option<Geometry> {
        let inner = self.inner.borrow();
        inner
            .binding
            .as_ref()
            .map(|binding| binding.layout.geometry)
    }

    /// Width and height in the model's units: cells, or pixels.
    pub fn size(&self) -> (u32, u32) {
        self.inner.borrow().extent()
    }

    /// Asks the viewer for `cols` by `rows` cells (0: its choice in that
    /// dimension) instead of the manifest's size; see
    /// [`Context::request_size`](crate::Context::request_size).
    pub fn request_size(&self, cols: u32, rows: u32) -> Result<()> {
        crate::host::surface_request_size(&self.id(), cols, rows)
    }

    /// Sets the short label the viewer shows at the right end of this
    /// surface's chrome title; see
    /// [`Context::set_label`](crate::Context::set_label).
    pub fn set_label(&self, label: Option<&str>) -> Result<()> {
        crate::host::surface_set_label(&self.id(), label)
    }

    /// Places the viewer's text cursor at (`col`, `row`) of this surface
    /// while it takes keys, or removes it; see
    /// [`Context::set_caret`](crate::Context::set_caret).
    pub fn set_caret(&self, caret: Option<(u32, u32)>) -> Result<()> {
        crate::host::surface_set_caret(&self.id(), caret)
    }

    pub fn is_attached(&self) -> bool {
        self.inner.borrow().binding.is_some()
    }

    /// Whether anything was drawn since the last commit (or the next commit
    /// is the first at a new size).
    pub fn is_dirty(&self) -> bool {
        let inner = self.inner.borrow();
        inner.binding.is_some() && (inner.full || !inner.dirty.is_empty())
    }

    /// Records a rectangle as changed, after writing through a raw slice.
    pub fn mark_dirty(&mut self, rect: Rect) {
        self.inner.borrow_mut().mark_dirty(rect);
    }

    /// Publishes what was drawn since the last commit and switches slots.
    /// `Ok(false)` when nothing changed (no host call, no frame). The
    /// first commit after a (re)bind covers the whole surface.
    pub fn commit(&mut self) -> Result<bool> {
        self.inner.borrow_mut().commit()
    }

    /// What the last commit published.
    pub fn last_commit(&self) -> Option<CommitInfo> {
        self.inner.borrow().last_commit.clone()
    }

    /// The rectangles the next commit would send (without the fully dirty
    /// first commit's).
    pub fn pending_dirty(&self) -> Vec<Rect> {
        self.inner.borrow().dirty.rects().to_vec()
    }

    /// Unbinds the surface from the host. Dropping the surface does this.
    pub fn detach(&mut self) -> Result<()> {
        let mut inner = self.inner.borrow_mut();
        if inner.binding.take().is_some()
            && let Backend::Host = inner.backend
        {
            inner.retired = None;
            return host::surface_detach(&inner.id);
        }
        Ok(())
    }
}

impl<M: SurfaceModel> Drop for Surface<M> {
    fn drop(&mut self) {
        // The host must stop reading the region before its memory is
        // freed.
        let _ = self.detach();
    }
}

/// A surface whose manifest lists both models (`"model": ["pixels",
/// "cells"]`): the viewer picks one per its capabilities and may switch
/// (graphics arriving or leaving), which the plugin sees as a
/// [`crate::Event::Resize`]. [`AnySurface::get`] hands out the surface in
/// the model the viewer uses now.
#[derive(Debug)]
pub struct AnySurface {
    id: String,
    surface: Option<AnySurfaceInner>,
}

#[derive(Debug)]
enum AnySurfaceInner {
    Cells(Surface<Cells>),
    Pixels(Surface<Pixels>),
}

/// [`AnySurface`] in the model the viewer uses now.
#[derive(Debug)]
pub enum AnySurfaceMut<'a> {
    Cells(&'a mut Surface<Cells>),
    Pixels(&'a mut Surface<Pixels>),
}

impl AnySurface {
    /// The manifest's surface `id`, in the model the viewer picked.
    pub fn new(id: &str) -> Self {
        let mut surface = Self {
            id: id.into(),
            surface: None,
        };
        surface.sync();
        surface
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// The model the surface paints in now.
    pub fn model(&self) -> Model {
        match self.surface {
            Some(AnySurfaceInner::Pixels(_)) => Model::Pixels,
            _ => Model::Cells,
        }
    }

    fn current_model(&self) -> Option<Model> {
        let inner = match self.surface.as_ref()? {
            AnySurfaceInner::Cells(surface) => &surface.inner,
            AnySurfaceInner::Pixels(surface) => &surface.inner,
        };
        let inner = inner.borrow();
        match &inner.error {
            Some(Error::WrongModel { found, .. }) => Some(*found),
            _ => Some(inner.model),
        }
    }

    /// Follows a model switch: `true` when the surface was recreated in the
    /// other model (it paints from scratch at its next commit).
    pub fn sync(&mut self) -> bool {
        let wanted = match self.current_model() {
            Some(model) => model,
            None => host::surface_layout(&self.id).map_or(Model::Cells, |layout| layout.model),
        };
        if self.surface.is_some() && Some(wanted) == self.surface.as_ref().map(|_| self.model()) {
            return false;
        }
        // The old surface detaches before the new one attaches under the
        // same id.
        self.surface = None;
        self.surface = Some(match wanted {
            Model::Cells => AnySurfaceInner::Cells(Surface::new(&self.id)),
            Model::Pixels => AnySurfaceInner::Pixels(Surface::new(&self.id)),
        });
        true
    }

    /// The surface in its current model, after following a switch.
    pub fn get(&mut self) -> AnySurfaceMut<'_> {
        self.sync();
        match self.surface.as_mut() {
            Some(AnySurfaceInner::Pixels(surface)) => AnySurfaceMut::Pixels(surface),
            Some(AnySurfaceInner::Cells(surface)) => AnySurfaceMut::Cells(surface),
            None => unreachable!("sync always leaves a surface"),
        }
    }
}

/// The instances of a `pane.footer` or `pane.header` surface (one per pane
/// the viewer shows, named `<surface>@<pane>`) or of a `machine.after`
/// surface (one per machine, `<surface>@<machine>`). Pass every event to
/// [`Instances::event`]; it creates an instance's surface when the viewer
/// first sizes it and drops it when the viewer removes it (a zero-size
/// resize), and says which pane or machine changed.
#[derive(Debug)]
pub struct Instances<M: SurfaceModel> {
    surface: String,
    panes: alloc::collections::BTreeMap<String, Surface<M>>,
}

/// The pane an instance id names, when `id` is an instance of `surface`.
pub fn instance_pane<'a>(surface: &str, id: &'a str) -> Option<&'a str> {
    id.strip_prefix(surface)?.strip_prefix('@')
}

impl<M: SurfaceModel> Instances<M> {
    /// The instances of the manifest's surface `surface`.
    pub fn new(surface: &str) -> Self {
        Self {
            surface: surface.into(),
            panes: alloc::collections::BTreeMap::new(),
        }
    }

    /// Follows the viewer: returns the pane whose instance the event is
    /// about (created, resized, shown, hidden or removed), if any.
    pub fn event(&mut self, event: &crate::Event) -> Option<String> {
        let (id, removed) = match event {
            crate::Event::Resize { surface, geometry } => (surface, geometry.is_empty()),
            crate::Event::Visibility { surface, .. } => (surface, false),
            _ => return None,
        };
        let pane = String::from(instance_pane(&self.surface, id)?);
        if removed {
            self.panes.remove(&pane);
        } else if !self.panes.contains_key(&pane) {
            self.panes.insert(pane.clone(), Surface::new(id));
        }
        Some(pane)
    }

    pub fn get_mut(&mut self, pane: &str) -> Option<&mut Surface<M>> {
        self.panes.get_mut(pane)
    }

    /// The instance of `owner` (a pane, machine or project id), created when
    /// the viewer has not shown it yet: a machine or project row at zero
    /// rows asks for rows through it
    /// ([`Surface::request_size`]).
    pub fn instance(&mut self, owner: &str) -> &mut Surface<M> {
        let surface = &self.surface;
        self.panes
            .entry(String::from(owner))
            .or_insert_with(|| Surface::new(&alloc::format!("{surface}@{owner}")))
    }

    /// Every live instance, by pane.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&str, &mut Surface<M>)> {
        self.panes
            .iter_mut()
            .map(|(pane, surface)| (pane.as_str(), surface))
    }

    pub fn len(&self) -> usize {
        self.panes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.panes.is_empty()
    }
}