Skip to main content

standard_plugin/surface/
graphic.rs

1//! Graphics: pictures over cells of a [`Surface<Cells>`], as a progressive
2//! enhancement of those cells. The plugin paints the cells for every viewer,
3//! then draws the picture for a viewer with real graphics
4//! ([`Surface::draw_graphic`]).
5
6use alloc::collections::BTreeMap;
7
8use super::{Cells, Pixels, Surface};
9use crate::error::{Error, Result};
10use crate::geometry::{Geometry, Rect};
11use crate::host;
12
13/// What the host holds of one graphic.
14#[derive(Clone, Copy, Debug)]
15struct Sent {
16    place: Rect,
17    size: (u32, u32),
18    hash: u64,
19    /// Drawn since the last [`Surface::clear`].
20    drawn: bool,
21}
22
23/// What the host holds of a surface's graphics, so an unchanged image is
24/// never sent again.
25#[derive(Debug, Default)]
26pub(super) struct SentGraphics {
27    sent: BTreeMap<u32, Sent>,
28    /// [`Surface::clear`] ran: the next commit removes what was not drawn
29    /// again since.
30    cleared: bool,
31    /// Something changed since the last commit.
32    changed: bool,
33}
34
35impl SentGraphics {
36    /// The surface was cleared: its graphics go with the next commit, but
37    /// for those drawn again before it.
38    pub(super) fn clear(&mut self) {
39        self.cleared = true;
40        for graphic in self.sent.values_mut() {
41            graphic.drawn = false;
42        }
43    }
44
45    /// A new region: the host keeps the graphics that still fit it
46    /// (`Place::still_fits`), and so does this.
47    pub(super) fn rebound(&mut self, geometry: Geometry) {
48        let cell = (geometry.cell_px_w, geometry.cell_px_h);
49        self.sent.retain(|_, held| {
50            let place = held.place;
51            place.x + place.w <= geometry.cols
52                && place.y + place.h <= geometry.rows
53                && held.size == (place.w * cell.0, place.h * cell.1)
54        });
55    }
56
57    pub(super) fn remove_undrawn(&mut self, id: &str) -> Result<()> {
58        if !core::mem::take(&mut self.cleared) {
59            return Ok(());
60        }
61        let undrawn: alloc::vec::Vec<u32> = self
62            .sent
63            .iter()
64            .filter(|(_, graphic)| !graphic.drawn)
65            .map(|(key, _)| *key)
66            .collect();
67        for key in undrawn {
68            host::surface_remove_graphic(id, key)?;
69            self.sent.remove(&key);
70            self.changed = true;
71        }
72        Ok(())
73    }
74
75    pub(super) fn changed(&self) -> bool {
76        self.changed
77    }
78
79    pub(super) fn published(&mut self) {
80        self.changed = false;
81    }
82}
83
84/// A hash of an image, a word at a time: only ever compared with the last
85/// one of the same key, to avoid sending the same pixels again.
86fn hash(bytes: &[u8]) -> u64 {
87    const FACTOR: u64 = 0x9E37_79B9_7F4A_7C15;
88    let mut hash = bytes.len() as u64;
89    let (words, rest) = bytes.as_chunks::<8>();
90    for word in words {
91        hash = (hash.rotate_left(5) ^ u64::from_le_bytes(*word)).wrapping_mul(FACTOR);
92    }
93    for byte in rest {
94        hash = (hash.rotate_left(5) ^ u64::from(*byte)).wrapping_mul(FACTOR);
95    }
96    hash
97}
98
99impl Surface<Cells> {
100    /// Draws a picture over cells of this surface, as an enhancement of
101    /// those cells: paint the cells first, for every viewer, then call this.
102    ///
103    /// `draw` gets a transparent [`Surface<Pixels>`] of `place`'s size at the
104    /// viewer's cell pixel size, with every [`crate::Shapes`] helper, and runs
105    /// only where the viewer shows real graphics. `Ok(false)` means it did
106    /// not run: this viewer shows the cells. A viewer with graphics shows the
107    /// picture, moves it with its rows while the surface scrolls, and blanks
108    /// the glyphs under it.
109    ///
110    /// `key` is your number for the graphic. Drawing a key again replaces it
111    /// with the next [`Surface::commit`]; identical pixels are not sent
112    /// again, and only move when `place` moved. [`Surface::clear`] removes
113    /// the graphics not drawn again before that commit. A resize keeps those
114    /// that still fit the new size at the same cell pixel size, so a change
115    /// of height needs no new image: see [`Surface::move_graphic`].
116    ///
117    /// Call it when the data changes, in `event` where you can: it costs a
118    /// buffer of the image's size, and `frame` has a small budget. A surface
119    /// holds at most 256 graphics and 64 MiB of images. A surface anchored as
120    /// anything but a `pane`, `column`, `stage` or `window` answers
121    /// [`Error::Invalid`].
122    pub fn draw_graphic(
123        &mut self,
124        key: u32,
125        place: Rect,
126        draw: impl FnOnce(&mut Surface<Pixels>),
127    ) -> Result<bool> {
128        let Some(geometry) = self.geometry() else {
129            return Ok(false);
130        };
131        let cell_px = (geometry.cell_px_w, geometry.cell_px_h);
132        if !host::capabilities().graphics || cell_px.0 == 0 || cell_px.1 == 0 {
133            return Ok(false);
134        }
135        let mut canvas = Surface::<Pixels>::offscreen(Geometry::cells(place.w, place.h, cell_px));
136        draw(&mut canvas);
137        let (width, height) = canvas.size();
138        let pixels = canvas.pixels_untracked();
139        let hash = hash(&pixels);
140        let id = self.id();
141        let mut inner = self.inner.borrow_mut();
142        let held = inner.graphics.sent.get(&key).copied();
143        let same = held.is_some_and(|held| held.hash == hash && held.size == (width, height));
144        if !same || held.is_some_and(|held| held.place != place) {
145            let image = (!same).then_some(&pixels[..]);
146            match host::surface_set_graphic(&id, key, place, (width, height), image) {
147                Err(Error::Unavailable(_)) => return Ok(false),
148                sent => sent?,
149            }
150            inner.graphics.changed = true;
151        }
152        inner.graphics.sent.insert(
153            key,
154            Sent {
155                place,
156                size: (width, height),
157                hash,
158                drawn: true,
159            },
160        );
161        Ok(true)
162    }
163
164    /// Moves a graphic to `place`, of the same size in cells, with the next
165    /// [`Surface::commit`], with no drawing and no image sent. `Ok(false)`
166    /// means this surface holds no such graphic: draw it. Use it when rows
167    /// above a chart open or close, as the chart and its cells then move in
168    /// one frame.
169    pub fn move_graphic(&mut self, key: u32, place: Rect) -> Result<bool> {
170        let id = self.id();
171        let mut inner = self.inner.borrow_mut();
172        let Some(held) = inner.graphics.sent.get(&key).copied() else {
173            return Ok(false);
174        };
175        if (held.place.w, held.place.h) != (place.w, place.h) {
176            return Ok(false);
177        }
178        if held.place != place {
179            host::surface_set_graphic(&id, key, place, held.size, None)?;
180            inner.graphics.changed = true;
181        }
182        inner.graphics.sent.insert(
183            key,
184            Sent {
185                place,
186                drawn: true,
187                ..held
188            },
189        );
190        Ok(true)
191    }
192
193    /// Removes a graphic with the next [`Surface::commit`]; the cells under
194    /// it show again.
195    pub fn remove_graphic(&mut self, key: u32) -> Result<()> {
196        let id = self.id();
197        let mut inner = self.inner.borrow_mut();
198        if inner.graphics.sent.remove(&key).is_some() {
199            host::surface_remove_graphic(&id, key)?;
200            inner.graphics.changed = true;
201        }
202        Ok(())
203    }
204}