Skip to main content

compose_rust/
asset.rs

1//! Pictures: registering the bytes once and drawing them by id.
2//!
3//! An asset is not part of the tree. It is bytes that have to reach the Renderer before
4//! anything can draw them and have to outlive the frame that does, which is the opposite
5//! of a node: a node is re-sent whenever it changes and points at nothing after the call
6//! that carried it.
7//!
8//! So an asset is registered and forgotten, the way a message is posted and forgotten. It
9//! rides out on the batch the current call produces, and everything after that is the id.
10
11use crate::schema::AssetKind;
12use std::cell::{Cell, RefCell};
13
14/// One registration, waiting for the batch that carries it.
15pub(crate) struct PendingAsset {
16    pub(crate) asset_id: u32,
17    pub(crate) kind: AssetKind,
18    pub(crate) bytes: &'static [u8],
19}
20
21thread_local! {
22    /// What has been registered, so the same picture asked for twice is one registration.
23    ///
24    /// The kind is kept beside the bytes because a new Renderer has to be told all of this
25    /// again, and a registration is bytes, an id and what the bytes are.
26    static REGISTERED: RefCell<Vec<(&'static [u8], u32, AssetKind)>> =
27        const { RefCell::new(Vec::new()) };
28    static QUEUE: RefCell<Vec<PendingAsset>> = const { RefCell::new(Vec::new()) };
29    /// Ids the application let go of, waiting for the batch that tells the Renderer.
30    static RELEASES: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
31    /// The last id handed out. Counted here and not read off the registry's length,
32    /// because a released id leaves a hole and the next registration must not reuse it:
33    /// a stale `Paint` would then silently name a different brush.
34    static LAST_ID: Cell<u32> = const { Cell::new(0) };
35}
36
37/// The id [`asset`] returns for a registered picture, and what an `Image` or an icon
38/// names it by.
39pub type AssetId = u32;
40
41/// Registers one picture and returns the id an [`crate::Image`] draws it by.
42///
43/// ```ignore
44/// static HERO: &[u8] = include_bytes!("../assets/hero.svg");
45///
46/// rsx! { Image { asset_id: asset(AssetKind::Svg, HERO), height: 240.0 } }
47/// ```
48///
49/// Call it wherever the picture is drawn, including in a component body that runs every
50/// render. The second call with the same bytes returns the first call's id and queues
51/// nothing, so a screen that draws the same picture every frame registers it once.
52///
53/// The bytes are `'static` because a registration is carried by whichever batch the
54/// current call produces, which is not always the call this was made in, and because
55/// `include_bytes!` is what an application almost always has.
56pub fn asset(kind: AssetKind, bytes: &'static [u8]) -> u32 {
57    if let Some(id) = REGISTERED.with_borrow(|registered| registered_id(registered, bytes)) {
58        return id;
59    }
60    // Ids start at one. Zero is what a node with no asset property reads as, so handing it
61    // out would make "no picture" and "the first picture" the same value on the wire.
62    let asset_id = REGISTERED.with_borrow_mut(|registered| {
63        let asset_id = LAST_ID.get() + 1;
64        LAST_ID.set(asset_id);
65        registered.push((bytes, asset_id, kind));
66        asset_id
67    });
68    QUEUE.with_borrow_mut(|queue| {
69        queue.push(PendingAsset {
70            asset_id,
71            kind,
72            bytes,
73        });
74    });
75    asset_id
76}
77
78/// Registers bytes this process built rather than bytes it was compiled with.
79///
80/// A gradient is worked out at run time, so there is no `include_bytes!` to point at. The
81/// bytes are handed to the registry to keep for the life of the process, which is what
82/// `'static` means here and what a registration is anyway: an asset has to outlive every
83/// frame that draws it, and nothing ever un-registers by dropping.
84///
85/// The content comparison runs first, so building the same gradient on every render keeps
86/// one copy. Only a brush nobody has registered before is kept.
87pub fn register_owned(kind: AssetKind, bytes: Vec<u8>) -> u32 {
88    if let Some(id) = REGISTERED.with_borrow(|registered| {
89        registered
90            .iter()
91            .find(|(known, _, _)| *known == bytes.as_slice())
92            .map(|(_, id, _)| *id)
93    }) {
94        return id;
95    }
96    asset(kind, Box::leak(bytes.into_boxed_slice()))
97}
98
99/// The id these bytes were registered under, by address first and by content after.
100///
101/// Address first because that is the answer almost every time and it costs a comparison.
102/// Content after because the same picture really can arrive at two addresses: a `const`
103/// holding a reference is inlined at each use, and each use can get an allocation of its
104/// own, so a catalogue written as a `const` array hands out two pointers to one file and
105/// the shop registers the same cover twice under two ids. The full comparison only runs
106/// when the address misses, which is once per new picture and never in the steady state.
107fn registered_id(
108    registered: &[(&'static [u8], u32, AssetKind)],
109    bytes: &'static [u8],
110) -> Option<u32> {
111    registered
112        .iter()
113        .find(|(known, _, _)| std::ptr::eq(*known, bytes))
114        .or_else(|| registered.iter().find(|(known, _, _)| *known == bytes))
115        .map(|(_, id, _)| *id)
116}
117
118/// Lets go of bytes registered with [`register_owned`] (or [`asset`]), so the Renderer
119/// drops its copy.
120///
121/// A screen that builds its pictures at run time, a picture per colour an icon is drawn
122/// in for example, would otherwise grow the Renderer's cache for the life of the app.
123/// The bytes leave the registry, so registering the same bytes again gives a new id and
124/// sends them again. The release goes out on the next batch, as [`crate::release_brush`]
125/// sends one. Returns false, and sends nothing, for an id that is not registered as
126/// `kind` or was already released. Releasing a picture a node still draws is the caller's
127/// mistake, reported by the Renderer as a protocol error rather than a crash.
128pub fn release_owned(asset_id: u32, kind: AssetKind) -> bool {
129    release(asset_id, kind)
130}
131
132/// Hands every queued registration to `emit` and empties the queue.
133///
134/// The buffer is moved out and put back, so the steady state, where nothing new has been
135/// registered, touches an empty `Vec` and allocates nothing.
136pub(crate) fn drain(mut emit: impl FnMut(&PendingAsset)) {
137    let mut taken = QUEUE.with_borrow_mut(std::mem::take);
138    if taken.is_empty() {
139        return;
140    }
141    for pending in &taken {
142        emit(pending);
143    }
144    taken.clear();
145    QUEUE.with_borrow_mut(|queue| {
146        if queue.is_empty() {
147            *queue = taken;
148        }
149    });
150}
151
152/// Lets go of one registration and queues the release for the Renderer.
153///
154/// Returns whether anything was released: false for an id that was never registered or
155/// was already released. A registration still waiting for its batch is simply dropped,
156/// because the Renderer never heard of it and a release for it would be a protocol error.
157/// The id is not handed out again, so a copy of the old `Paint` stays a dangling name
158/// (reported as a protocol error) and never silently names a different asset.
159pub(crate) fn release(asset_id: u32, kind: AssetKind) -> bool {
160    let removed = REGISTERED.with_borrow_mut(|registered| {
161        let at = registered
162            .iter()
163            .position(|(_, id, known)| *id == asset_id && *known == kind)?;
164        registered.remove(at);
165        Some(())
166    });
167    if removed.is_none() {
168        return false;
169    }
170    let was_waiting = QUEUE.with_borrow_mut(|queue| {
171        let before = queue.len();
172        queue.retain(|pending| pending.asset_id != asset_id);
173        queue.len() != before
174    });
175    if !was_waiting {
176        RELEASES.with_borrow_mut(|releases| releases.push(asset_id));
177    }
178    true
179}
180
181/// Hands every queued release to `emit` and empties the queue.
182pub(crate) fn drain_releases(mut emit: impl FnMut(u32)) {
183    let mut taken = RELEASES.with_borrow_mut(std::mem::take);
184    if taken.is_empty() {
185        return;
186    }
187    for asset_id in &taken {
188        emit(*asset_id);
189    }
190    taken.clear();
191    RELEASES.with_borrow_mut(|releases| {
192        if releases.is_empty() {
193            *releases = taken;
194        }
195    });
196}
197
198/// What one thread has registered, for the thread the UI runs on to take over.
199///
200/// Bytes that live for the whole program, ids and kinds, so it can go to another thread.
201pub(crate) struct Registrations {
202    registered: Vec<(&'static [u8], u32, AssetKind)>,
203    last_id: u32,
204}
205
206/// What this thread has registered so far.
207///
208/// An application registers its window's icon and its theme's fonts while it builds what it
209/// launches with, which is before there is a UI, and the theme and the window then name
210/// them by id. Where the Host makes the UI thread, that was a different thread from the
211/// one the UI is about to run on, and a registry kept per thread would leave those ids
212/// naming nothing there, or naming whatever the UI registered first.
213pub(crate) fn registrations() -> Registrations {
214    Registrations {
215        registered: REGISTERED.with_borrow(Clone::clone),
216        last_id: LAST_ID.get(),
217    }
218}
219
220/// Makes another thread's registrations this thread's, ids unchanged, if this thread has
221/// registered nothing of its own. The Host that starts here then tells the Renderer all of
222/// them (`requeue_all`), and the next id handed out here follows the last one handed out
223/// there.
224pub(crate) fn adopt(registrations: Registrations) {
225    if LAST_ID.get() != 0 {
226        return;
227    }
228    LAST_ID.set(registrations.last_id);
229    REGISTERED.with_borrow_mut(|registered| *registered = registrations.registered);
230    requeue_all();
231}
232
233/// Forgets every registration and every id. Used between tests.
234#[doc(hidden)]
235pub fn reset_assets() {
236    REGISTERED.with_borrow_mut(Vec::clear);
237    QUEUE.with_borrow_mut(Vec::clear);
238    RELEASES.with_borrow_mut(Vec::clear);
239    LAST_ID.set(0);
240}
241
242/// Queues every registration again, for a Renderer that has not been told any of them.
243///
244/// What a new `Host` does instead of forgetting them. A new Host means a Renderer whose
245/// cache is empty, so an id handed out before it names nothing over there, and the cure
246/// for that is to say all of them again rather than to drop them.
247///
248/// Dropping them was wrong in a way that only shows on the screen. A theme names its fonts
249/// by id and a window names its icon by id, and both are built by the caller before the
250/// Host is made out of them: the ids travelled and the bytes they named had been thrown
251/// away, so the window wore no icon and the screen was set in the machine's own face while
252/// every batch looked correct.
253///
254/// Ids do not move. The same bytes keep the id they were given, which is what lets a theme
255/// built before this still name the right thing after it.
256pub(crate) fn requeue_all() {
257    let all: Vec<PendingAsset> = REGISTERED.with_borrow(|registered| {
258        registered
259            .iter()
260            .map(|(bytes, asset_id, kind)| PendingAsset {
261                asset_id: *asset_id,
262                kind: *kind,
263                bytes,
264            })
265            .collect()
266    });
267    // A new Renderer never held what was released, so telling it would be an error.
268    RELEASES.with_borrow_mut(Vec::clear);
269    if all.is_empty() {
270        return;
271    }
272    QUEUE.with_borrow_mut(|queue| {
273        // Anything already waiting is in `all` as well, because everything queued was
274        // registered. Replacing rather than appending is what keeps it sent once.
275        *queue = all;
276    });
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    /// Releasing a brush: a release reaches the Renderer once, a registration
284    /// that never left is dropped silently, and ids are never reused.
285    #[test]
286    fn fr23_released_brush_ids_are_sent_once_and_never_reused() {
287        reset_assets();
288        let kept = register_owned(AssetKind::Brush, vec![1, 2, 3]);
289        let sent = register_owned(AssetKind::Brush, vec![4, 5, 6]);
290        drain(|_| {});
291        let waiting = register_owned(AssetKind::Brush, vec![7, 8, 9]);
292
293        assert!(release(sent, AssetKind::Brush));
294        assert!(release(waiting, AssetKind::Brush));
295        assert!(
296            !release(sent, AssetKind::Brush),
297            "second release is a no-op"
298        );
299        assert!(!release(kept, AssetKind::Png), "wrong kind is not released");
300
301        let mut released = Vec::new();
302        drain_releases(|id| released.push(id));
303        assert_eq!(released, [sent], "only the registration the Renderer saw");
304        drain(|pending| panic!("nothing should be waiting, found {}", pending.asset_id));
305
306        let again = register_owned(AssetKind::Brush, vec![4, 5, 6]);
307        assert!(again > waiting, "a released id is not handed out again");
308        reset_assets();
309    }
310}