standard-plugin-sdk 0.1.8

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
//! Graphics: pictures over cells of a [`Surface<Cells>`], as a progressive
//! enhancement of those cells. The plugin paints the cells for every viewer,
//! then draws the picture for a viewer with real graphics
//! ([`Surface::draw_graphic`]).

use alloc::collections::BTreeMap;

use super::{Cells, Pixels, Surface};
use crate::error::{Error, Result};
use crate::geometry::{Geometry, Rect};
use crate::host;

/// What the host holds of one graphic.
#[derive(Clone, Copy, Debug)]
struct Sent {
    place: Rect,
    size: (u32, u32),
    hash: u64,
    /// Drawn since the last [`Surface::clear`].
    drawn: bool,
}

/// What the host holds of a surface's graphics, so an unchanged image is
/// never sent again.
#[derive(Debug, Default)]
pub(super) struct SentGraphics {
    sent: BTreeMap<u32, Sent>,
    /// [`Surface::clear`] ran: the next commit removes what was not drawn
    /// again since.
    cleared: bool,
    /// Something changed since the last commit.
    changed: bool,
}

impl SentGraphics {
    /// The surface was cleared: its graphics go with the next commit, but
    /// for those drawn again before it.
    pub(super) fn clear(&mut self) {
        self.cleared = true;
        for graphic in self.sent.values_mut() {
            graphic.drawn = false;
        }
    }

    /// A new region: the host keeps the graphics that still fit it
    /// (`Place::still_fits`), and so does this.
    pub(super) fn rebound(&mut self, geometry: Geometry) {
        let cell = (geometry.cell_px_w, geometry.cell_px_h);
        self.sent.retain(|_, held| {
            let place = held.place;
            place.x + place.w <= geometry.cols
                && place.y + place.h <= geometry.rows
                && held.size == (place.w * cell.0, place.h * cell.1)
        });
    }

    pub(super) fn remove_undrawn(&mut self, id: &str) -> Result<()> {
        if !core::mem::take(&mut self.cleared) {
            return Ok(());
        }
        let undrawn: alloc::vec::Vec<u32> = self
            .sent
            .iter()
            .filter(|(_, graphic)| !graphic.drawn)
            .map(|(key, _)| *key)
            .collect();
        for key in undrawn {
            host::surface_remove_graphic(id, key)?;
            self.sent.remove(&key);
            self.changed = true;
        }
        Ok(())
    }

    pub(super) fn changed(&self) -> bool {
        self.changed
    }

    pub(super) fn published(&mut self) {
        self.changed = false;
    }
}

/// A hash of an image, a word at a time: only ever compared with the last
/// one of the same key, to avoid sending the same pixels again.
fn hash(bytes: &[u8]) -> u64 {
    const FACTOR: u64 = 0x9E37_79B9_7F4A_7C15;
    let mut hash = bytes.len() as u64;
    let (words, rest) = bytes.as_chunks::<8>();
    for word in words {
        hash = (hash.rotate_left(5) ^ u64::from_le_bytes(*word)).wrapping_mul(FACTOR);
    }
    for byte in rest {
        hash = (hash.rotate_left(5) ^ u64::from(*byte)).wrapping_mul(FACTOR);
    }
    hash
}

impl Surface<Cells> {
    /// Draws a picture over cells of this surface, as an enhancement of
    /// those cells: paint the cells first, for every viewer, then call this.
    ///
    /// `draw` gets a transparent [`Surface<Pixels>`] of `place`'s size at the
    /// viewer's cell pixel size, with every [`crate::Shapes`] helper, and runs
    /// only where the viewer shows real graphics. `Ok(false)` means it did
    /// not run: this viewer shows the cells. A viewer with graphics shows the
    /// picture, moves it with its rows while the surface scrolls, and blanks
    /// the glyphs under it.
    ///
    /// `key` is your number for the graphic. Drawing a key again replaces it
    /// with the next [`Surface::commit`]; identical pixels are not sent
    /// again, and only move when `place` moved. [`Surface::clear`] removes
    /// the graphics not drawn again before that commit. A resize keeps those
    /// that still fit the new size at the same cell pixel size, so a change
    /// of height needs no new image: see [`Surface::move_graphic`].
    ///
    /// Call it when the data changes, in `event` where you can: it costs a
    /// buffer of the image's size, and `frame` has a small budget. A surface
    /// holds at most 256 graphics and 64 MiB of images. A surface anchored as
    /// anything but a `pane`, `column`, `stage` or `window` answers
    /// [`Error::Invalid`].
    pub fn draw_graphic(
        &mut self,
        key: u32,
        place: Rect,
        draw: impl FnOnce(&mut Surface<Pixels>),
    ) -> Result<bool> {
        let Some(geometry) = self.geometry() else {
            return Ok(false);
        };
        let cell_px = (geometry.cell_px_w, geometry.cell_px_h);
        if !host::capabilities().graphics || cell_px.0 == 0 || cell_px.1 == 0 {
            return Ok(false);
        }
        let mut canvas = Surface::<Pixels>::offscreen(Geometry::cells(place.w, place.h, cell_px));
        draw(&mut canvas);
        let (width, height) = canvas.size();
        let pixels = canvas.pixels_untracked();
        let hash = hash(&pixels);
        let id = self.id();
        let mut inner = self.inner.borrow_mut();
        let held = inner.graphics.sent.get(&key).copied();
        let same = held.is_some_and(|held| held.hash == hash && held.size == (width, height));
        if !same || held.is_some_and(|held| held.place != place) {
            let image = (!same).then_some(&pixels[..]);
            match host::surface_set_graphic(&id, key, place, (width, height), image) {
                Err(Error::Unavailable(_)) => return Ok(false),
                sent => sent?,
            }
            inner.graphics.changed = true;
        }
        inner.graphics.sent.insert(
            key,
            Sent {
                place,
                size: (width, height),
                hash,
                drawn: true,
            },
        );
        Ok(true)
    }

    /// Moves a graphic to `place`, of the same size in cells, with the next
    /// [`Surface::commit`], with no drawing and no image sent. `Ok(false)`
    /// means this surface holds no such graphic: draw it. Use it when rows
    /// above a chart open or close, as the chart and its cells then move in
    /// one frame.
    pub fn move_graphic(&mut self, key: u32, place: Rect) -> Result<bool> {
        let id = self.id();
        let mut inner = self.inner.borrow_mut();
        let Some(held) = inner.graphics.sent.get(&key).copied() else {
            return Ok(false);
        };
        if (held.place.w, held.place.h) != (place.w, place.h) {
            return Ok(false);
        }
        if held.place != place {
            host::surface_set_graphic(&id, key, place, held.size, None)?;
            inner.graphics.changed = true;
        }
        inner.graphics.sent.insert(
            key,
            Sent {
                place,
                drawn: true,
                ..held
            },
        );
        Ok(true)
    }

    /// Removes a graphic with the next [`Surface::commit`]; the cells under
    /// it show again.
    pub fn remove_graphic(&mut self, key: u32) -> Result<()> {
        let id = self.id();
        let mut inner = self.inner.borrow_mut();
        if inner.graphics.sent.remove(&key).is_some() {
            host::surface_remove_graphic(&id, key)?;
            inner.graphics.changed = true;
        }
        Ok(())
    }
}