Skip to main content

kui_core/
resources.rs

1//! Long-lived, host-registered resources: fonts, images, sounds and
2//! fragment shaders, behind typed handles.
3//!
4//! A handle ([`FontId`], [`ImageId`], [`SoundId`], [`FragmentId`]) is a
5//! slotmap key with generational use-after-free protection. It converts
6//! to and from `u64` (`to_ffi` / `from_ffi`) so it crosses a scripting
7//! boundary as a plain integer with the generation check intact. The
8//! registry is the session's, so a resource registered through one window
9//! draws and plays in every window of the session.
10//!
11//! Registering through a [`Core`](crate::Core):
12//!
13//! ```rust,no_run
14//! use kui_core::{Core, NodeSpec, Size, TextStyle};
15//!
16//! let mut core = Core::new();
17//! // A font: raw TTF/OTF bytes; `None` when the data holds no usable face.
18//! let font = core.add_font_data(std::fs::read("Inter.ttf").unwrap()).unwrap();
19//! // An image: RGBA, `width * height * 4` bytes.
20//! let logo = core.resources.add_image(2, 2, vec![255; 16]);
21//! // A sound: encoded file bytes the runner's audio backend decodes.
22//! let ding = core.add_sound(std::fs::read("ding.ogg").unwrap());
23//!
24//! let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
25//! ui.text("Hello", TextStyle::new(14.0).font(font));
26//! ui.image(logo, NodeSpec::row().size(64.0, 64.0));
27//! ui.finish();
28//! core.play(ding, Default::default());
29//! ```
30//!
31//! Removing a resource (`remove_image`, `remove_font`, `remove_sound`,
32//! `remove_fragment` on `Core`) makes its handle a miss: the image draws
33//! nothing, the font shapes as sans, the sound is silent.
34//!
35//! **A handle is unique to the process, not to its session.** Every
36//! `Session` has its own registry, but the keys come from one process-wide
37//! mint per kind, which also records the session that owns each. So an
38//! `ImageId` from one session, looked up in another, is a detectable miss
39//! rather than an alias for that session's first image: it behaves as a
40//! removed handle does, plus a `foreign-resource` warning the next
41//! `Core::take_warnings` reports. The mint is touched on registration,
42//! removal and the miss path only; a live lookup never locks it.
43
44use std::cell::RefCell;
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
47
48use slotmap::{Key as _, SlotMap, SparseSecondaryMap, new_key_type};
49
50use crate::spec::FontFamily;
51
52new_key_type! {
53    pub struct ImageId;
54    pub struct PainterId;
55    /// A registered font (`Core::add_font_data` / `add_system_font`), used
56    /// through `TextStyle::font`.
57    pub struct FontId;
58    /// A registered sound (`Core::add_sound`): encoded file bytes the
59    /// driver's audio backend decodes. Played through `Core::play`, an
60    /// `audio` node, or `NodeSpec::click_sound` / `hover_sound`.
61    pub struct SoundId;
62    /// A registered WGSL fragment function (`Core::add_fragment`), drawn
63    /// by a `fragment` node.
64    pub struct FragmentId;
65}
66
67impl FragmentId {
68    /// The handle as a plain integer for C/Lua/JS (generation check intact).
69    pub fn to_ffi(self) -> u64 {
70        self.data().as_ffi()
71    }
72
73    pub fn from_ffi(raw: u64) -> Self {
74        Self::from(slotmap::KeyData::from_ffi(raw))
75    }
76}
77
78impl SoundId {
79    /// The handle as a plain integer for C/Lua/JS (generation check intact).
80    pub fn to_ffi(self) -> u64 {
81        self.data().as_ffi()
82    }
83
84    pub fn from_ffi(raw: u64) -> Self {
85        Self::from(slotmap::KeyData::from_ffi(raw))
86    }
87}
88
89impl FontId {
90    /// The handle as a plain integer for C/Lua/JS (generation check intact).
91    pub fn to_ffi(self) -> u64 {
92        self.data().as_ffi()
93    }
94
95    pub fn from_ffi(raw: u64) -> Self {
96        Self::from(slotmap::KeyData::from_ffi(raw))
97    }
98}
99
100impl ImageId {
101    /// The handle as a plain integer for C/Lua (generation check intact).
102    pub fn to_ffi(self) -> u64 {
103        self.data().as_ffi()
104    }
105
106    pub fn from_ffi(raw: u64) -> Self {
107        Self::from(slotmap::KeyData::from_ffi(raw))
108    }
109}
110
111/// Which `Session` a registry — and so every handle it minted — belongs
112/// to. Process-wide unique, from a counter; never serialized, so the
113/// number means nothing across runs and is only ever compared or printed.
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
115pub struct SessionId(pub u64);
116
117impl SessionId {
118    /// The next unused id. Starts at 1 so a zeroed struct is never a
119    /// session.
120    pub(crate) fn next() -> Self {
121        static NEXT: AtomicU64 = AtomicU64::new(1);
122        Self(NEXT.fetch_add(1, Ordering::Relaxed))
123    }
124}
125
126/// The kind of resource a handle names, for the warning that reports a
127/// foreign one.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum ResourceKind {
130    Image,
131    Font,
132    Sound,
133    Fragment,
134}
135
136impl ResourceKind {
137    pub fn name(self) -> &'static str {
138        match self {
139            Self::Image => "image",
140            Self::Font => "font",
141            Self::Sound => "sound",
142            Self::Fragment => "fragment",
143        }
144    }
145
146    /// What a handle of this kind does when it does not resolve.
147    fn fallback(self) -> &'static str {
148        match self {
149            Self::Image => "draws nothing",
150            Self::Font => "shapes as sans-serif",
151            Self::Sound => "plays nothing",
152            Self::Fragment => "draws nothing",
153        }
154    }
155}
156
157/// A handle from another session that this registry was asked to resolve:
158/// what `diag::foreign_resource` turns into a warning.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub struct Foreign {
161    pub kind: ResourceKind,
162    /// The handle as `to_ffi` shows it — what a host would have logged.
163    pub raw: u64,
164    /// The session the handle is live in.
165    pub owner: SessionId,
166    /// The session that was asked.
167    pub here: SessionId,
168}
169
170impl Foreign {
171    /// The one-line explanation: which handle, whose it is, what it did
172    /// instead, and the fix.
173    pub fn message(&self) -> String {
174        let Foreign {
175            kind,
176            raw,
177            owner,
178            here,
179        } = *self;
180        let what = kind.name();
181        let did = kind.fallback();
182        format!(
183            "{what} handle {raw:#x} belongs to session #{} and was used in session #{}: a \
184             handle is only valid in the session that registered it, so this one is treated \
185             as removed and {did} — register the {what} through a core of this session, or \
186             build both cores against one `Session` (`Core::new_in`)",
187            owner.0, here.0
188        )
189    }
190}
191
192/// Foreign hits a registry keeps before it stops recording: a `Core`
193/// drains them on every `take_warnings`, and the diagnostics' own dedup
194/// means one line per handle, so a handful is plenty.
195const MAX_FOREIGN: usize = 64;
196
197/// The process's one allocator of handles, per kind, with the session each
198/// live handle belongs to. A session's registry never mints a key itself:
199/// it takes one from here and stores its entry under it, which is what
200/// keeps two sessions from ever holding the same bits for different
201/// things.
202#[derive(Default)]
203struct Mint {
204    images: SlotMap<ImageId, SessionId>,
205    fonts: SlotMap<FontId, SessionId>,
206    sounds: SlotMap<SoundId, SessionId>,
207    fragments: SlotMap<FragmentId, SessionId>,
208}
209
210static MINT: LazyLock<Mutex<Mint>> = LazyLock::new(Mutex::default);
211
212/// The mint, past a poisoned lock: the maps hold plain ids and session
213/// numbers, so a panic mid-insert on another thread leaves nothing to
214/// distrust.
215fn mint() -> MutexGuard<'static, Mint> {
216    MINT.lock().unwrap_or_else(|e| e.into_inner())
217}
218
219/// An image handle for pixels the core itself owns — a path's mask drawn
220/// from a texture of its own — unique across sessions as a registered
221/// image's is, so a backend's texture cache never confuses the two.
222pub(crate) fn mint_image(session: SessionId) -> ImageId {
223    mint().images.insert(session)
224}
225
226/// Returns a handle [`mint_image`] made.
227pub(crate) fn unmint_image(id: ImageId) {
228    mint().images.remove(id);
229}
230
231/// An RGBA image registered by the host (rendering lands in a later pass).
232pub struct ImageEntry {
233    pub width: u32,
234    pub height: u32,
235    /// Shared rather than owned so a frame's display list can hand a
236    /// backend the pixels of a texture-backed image without copying them
237    /// (`DisplayList::texture_pixels`): an update replaces the `Arc`, and
238    /// a backend mid-upload keeps the old one alive until it is done.
239    pub rgba: std::sync::Arc<Vec<u8>>,
240    /// Moves on every [`Resources::update_image`]; a backend re-uploads a
241    /// texture-backed image when the revision it uploaded is behind.
242    pub rev: u32,
243    /// Where the pixels live on the GPU.
244    pub backing: ImageBacking,
245    /// The buffer the last [`Resources::update_image_with`] replaced, kept
246    /// for the next one to write into once no display list holds it.
247    /// An update between frames finds `rgba` still shared
248    /// with the last frame's `texture_pixels`, so without it every update
249    /// was a fresh `w × h × 4` allocation and the previous one freed —
250    /// 590 µs of page faults and 170 µs of release at 1080p on Windows,
251    /// three times the copy itself. Two buffers per streamed image, and a
252    /// stream stops allocating from its fourth update. Kept only for an
253    /// image updated before, at the same size, and dropped by
254    /// [`Resources::release_spares`] once [`SPARE_FRAMES`] frames pass
255    /// with no update: an image updated once, or a stream that stopped,
256    /// holds one buffer again.
257    pub(crate) spare: Option<std::sync::Arc<Vec<u8>>>,
258    /// [`Resources::frames`] when `spare` was last set.
259    spare_at: u64,
260}
261
262/// How many frames an image's spare buffer outlives its last update.
263/// Long enough for a stream slower than the display — a
264/// 30 fps video beside a 120 Hz animation updates every fourth frame —
265/// and short enough that one that stopped gives its buffer back.
266pub const SPARE_FRAMES: u64 = 30;
267
268/// Where a registered image's pixels are kept for drawing.
269/// The core
270/// decides on the two facts that matter — whether the image fits an atlas
271/// page, and whether its pixels were ever replaced — and the app never
272/// chooses.
273#[derive(Clone, Copy, Debug, PartialEq, Eq)]
274pub enum ImageBacking {
275    /// Blitted into the glyph atlas at first draw and drawn as
276    /// [`crate::display::QuadKind::Image`]: icons, thumbnails, anything
277    /// that fits and never changes.
278    Atlas,
279    /// A texture of its own, drawn as [`crate::display::QuadKind::Texture`]
280    /// through an entry in `DisplayList::textures`: an image that does not
281    /// fit a `MAX_ATLAS_SIZE` page, or one that has been updated in place.
282    /// Once here, an image stays here.
283    Texture,
284}
285
286/// How an `image` node meets the pixels it shows: its two per-node rows.
287/// Carried on the node's content rather than
288/// on `NodeSpec`, so a box pays nothing for a row only an image reads.
289#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
290pub struct ImageOpts {
291    pub sampling: Sampling,
292    pub fit: ImageFit,
293}
294
295/// The `sampling` row: how a backend reads texels between pixel centres.
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
297pub enum Sampling {
298    /// Bilinear — a photo, a rendered frame (the default).
299    #[default]
300    Linear,
301    /// Nearest texel — pixel art, an emulator, a data grid that must stay
302    /// square under zoom.
303    Nearest,
304}
305
306impl Sampling {
307    /// Every mode, in the order the `sampling` row names them.
308    pub const ALL: [Sampling; 2] = [Sampling::Linear, Sampling::Nearest];
309
310    pub fn name(self) -> &'static str {
311        match self {
312            Sampling::Linear => "linear",
313            Sampling::Nearest => "nearest",
314        }
315    }
316}
317
318/// The `fit` row: how the pixels meet the node's box. The box itself —
319/// its layout, its hit region, its access rect — is the same in every
320/// mode; only what is painted inside it moves.
321#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
322pub enum ImageFit {
323    /// The pixels stretch to the box (the default, and what every image
324    /// did before the row existed).
325    #[default]
326    Fill,
327    /// The largest rect of the image's aspect that fits the box, centred;
328    /// the rest of the box shows what is behind it.
329    Contain,
330    /// The box is filled and the pixels that do not fit are cropped,
331    /// centred.
332    Cover,
333}
334
335impl ImageFit {
336    /// Every mode, in the order the `fit` row names them.
337    pub const ALL: [ImageFit; 3] = [ImageFit::Fill, ImageFit::Contain, ImageFit::Cover];
338
339    pub fn name(self) -> &'static str {
340        match self {
341            ImageFit::Fill => "fill",
342            ImageFit::Contain => "contain",
343            ImageFit::Cover => "cover",
344        }
345    }
346}
347
348/// A registered font: the family name shaping resolves it by, the faces
349/// it loaded into the font database (empty for installed fonts), and the
350/// weights the family is asked at for regular and bold.
351pub struct FontEntry {
352    pub family: String,
353    pub faces: Vec<cosmic_text::fontdb::ID>,
354    pub(crate) weights: crate::weights::Weights,
355}
356
357/// One family of the font database — installed or loaded — as its faces
358/// describe it, from what the database read off each face's tables when
359/// it was scanned: nothing is loaded or shaped to answer.
360/// What [`Core::system_fonts`](crate::Core::system_fonts) lists, one per
361/// family.
362#[derive(Clone, Debug, PartialEq, Eq)]
363pub struct SystemFont {
364    /// The family name [`Core::add_system_font`](crate::Core::add_system_font)
365    /// takes.
366    pub family: String,
367    /// Every face of the family says it is fixed-pitch (the `post` table's
368    /// `isFixedPitch`): a monospaced family. Measuring glyph widths instead
369    /// loads and shapes every file, and calls a symbol font whose glyphs
370    /// happen to share an advance monospaced.
371    pub monospaced: bool,
372    /// The weights its faces come in, on the CSS scale (400 regular, 700
373    /// bold) as each face's `OS/2` table says it — sorted, each once. A
374    /// variable font's face reads as its default instance.
375    pub weights: Vec<u16>,
376    /// It has an italic or an oblique face.
377    pub italic: bool,
378}
379
380/// A registered sound: the encoded file (wav/ogg/mp3/flac, whatever the
381/// driver's backend decodes), shared so the backend can hold it without a
382/// copy. The core never decodes — headless drivers have no use for PCM.
383pub struct SoundEntry {
384    pub bytes: Arc<[u8]>,
385}
386
387/// A registered fragment: the app's WGSL as it was given, which is what a
388/// backend compiles (around the core's prelude and epilogue — see
389/// `crate::fragment`) and what a C host reads back to compile itself.
390pub struct FragmentEntry {
391    /// The app's source, without the prelude or the epilogue.
392    pub source: Arc<str>,
393}
394
395/// One session's registry. The maps are secondary to the process-wide
396/// the process-wide mint (see the module doc), so a lookup that misses is a handle this
397/// session never registered or has since removed — never somebody else's
398/// entry.
399pub struct Resources {
400    session: SessionId,
401    pub(crate) images: SparseSecondaryMap<ImageId, ImageEntry>,
402    pub(crate) fonts: SparseSecondaryMap<FontId, FontEntry>,
403    pub(crate) sounds: SparseSecondaryMap<SoundId, SoundEntry>,
404    pub(crate) fragments: SparseSecondaryMap<FragmentId, FragmentEntry>,
405    /// The families asked before the platform's fallback lists
406    /// (`Core::set_fallback_fonts`), in order: what the font system was
407    /// built with, kept for the one built again over a new scan.
408    pub(crate) fallback: Vec<String>,
409    /// Handles of other sessions this registry was asked for since the
410    /// last drain, each once. A `RefCell` because the resolves that find
411    /// them (`family_of` under a shaping closure, `image` under the
412    /// emitter's shared borrow) hold the registry by `&`.
413    foreign: RefCell<Vec<Foreign>>,
414    /// Frames begun by any window of the session, for aging spares.
415    frames: u64,
416    /// The images holding a spare buffer, swept each frame.
417    spared: Vec<ImageId>,
418}
419
420impl Resources {
421    /// The registry for session `session`; keys come from the process's
422    /// mint.
423    pub fn new(session: SessionId) -> Self {
424        Self {
425            session,
426            images: SparseSecondaryMap::new(),
427            fonts: SparseSecondaryMap::new(),
428            sounds: SparseSecondaryMap::new(),
429            fragments: SparseSecondaryMap::new(),
430            fallback: Vec::new(),
431            foreign: RefCell::new(Vec::new()),
432            frames: 0,
433            spared: Vec::new(),
434        }
435    }
436
437    /// The session this registry belongs to.
438    pub fn session(&self) -> SessionId {
439        self.session
440    }
441
442    /// The foreign handles resolved since the last call (see
443    /// [`Foreign`]); `Core::take_warnings` turns each into one line.
444    pub(crate) fn take_foreign(&self) -> Vec<Foreign> {
445        std::mem::take(&mut *self.foreign.borrow_mut())
446    }
447
448    /// A lookup missed: the mint says whether the handle is live in some
449    /// other session (recorded, once) or in none (removed — silent, the
450    /// documented behaviour). Only the miss path pays for the lock.
451    fn note_miss(&self, kind: ResourceKind, raw: u64) {
452        let owner = {
453            let m = mint();
454            match kind {
455                ResourceKind::Image => m.images.get(ImageId::from_ffi(raw)).copied(),
456                ResourceKind::Font => m.fonts.get(FontId::from_ffi(raw)).copied(),
457                ResourceKind::Sound => m.sounds.get(SoundId::from_ffi(raw)).copied(),
458                ResourceKind::Fragment => m.fragments.get(FragmentId::from_ffi(raw)).copied(),
459            }
460        };
461        let Some(owner) = owner else {
462            return;
463        };
464        if owner == self.session {
465            return;
466        }
467        let mut foreign = self.foreign.borrow_mut();
468        if foreign.len() >= MAX_FOREIGN || foreign.iter().any(|f| f.kind == kind && f.raw == raw) {
469            return;
470        }
471        foreign.push(Foreign {
472            kind,
473            raw,
474            owner,
475            here: self.session,
476        });
477    }
478
479    pub(crate) fn add_font(
480        &mut self,
481        family: String,
482        faces: Vec<cosmic_text::fontdb::ID>,
483    ) -> FontId {
484        let id = mint().fonts.insert(self.session);
485        self.fonts.insert(
486            id,
487            FontEntry {
488                family,
489                faces,
490                weights: crate::weights::Weights::CSS,
491            },
492        );
493        id
494    }
495
496    /// Reads again the weights of the registered families `families` holds
497    /// from what `db` has of them now: after a family is
498    /// registered, and after faces of it come into the database or leave.
499    /// Whether the weights of a font other than `fresh` — the one just
500    /// registered, which nothing has shaped in yet — changed: text shaped
501    /// in it was shaped at the old ones.
502    pub(crate) fn reweigh(
503        &mut self,
504        db: &cosmic_text::fontdb::Database,
505        families: &rustc_hash::FxHashSet<String>,
506        fresh: Option<FontId>,
507    ) -> bool {
508        let mut changed = false;
509        for (id, entry) in self.fonts.iter_mut() {
510            if families.contains(&entry.family) {
511                let weights = crate::weights::Weights::of(db, &entry.family);
512                changed |= Some(id) != fresh && weights != entry.weights;
513                entry.weights = weights;
514            }
515        }
516        changed
517    }
518
519    pub(crate) fn remove_font(&mut self, id: FontId) -> Option<FontEntry> {
520        let entry = self.fonts.remove(id);
521        match entry {
522            Some(_) => {
523                mint().fonts.remove(id);
524            }
525            None => self.note_miss(ResourceKind::Font, id.to_ffi()),
526        }
527        entry
528    }
529
530    /// The registered family name, if the handle is live here.
531    pub fn font_family(&self, id: FontId) -> Option<&str> {
532        let entry = self.fonts.get(id);
533        if entry.is_none() {
534            self.note_miss(ResourceKind::Font, id.to_ffi());
535        }
536        entry.map(|f| f.family.as_str())
537    }
538
539    /// The cosmic-text family a style's `FontFamily` shapes with; an unknown
540    /// or removed custom font falls back to sans-serif.
541    pub(crate) fn family_of(&self, f: FontFamily) -> cosmic_text::Family<'_> {
542        match f {
543            FontFamily::Sans => cosmic_text::Family::SansSerif,
544            FontFamily::Serif => cosmic_text::Family::Serif,
545            FontFamily::Mono => cosmic_text::Family::Monospace,
546            FontFamily::Custom(id) => match self.font_family(id) {
547                Some(name) => cosmic_text::Family::Name(name),
548                None => cosmic_text::Family::SansSerif,
549            },
550        }
551    }
552
553    /// The weights a style's `FontFamily` is asked at: a
554    /// registered family's own, the CSS ones for a generic family and for
555    /// an unknown or removed custom font (which shapes as sans-serif).
556    pub(crate) fn weights_of(&self, f: FontFamily) -> crate::weights::Weights {
557        match f {
558            FontFamily::Custom(id) => self
559                .fonts
560                .get(id)
561                .map_or(crate::weights::Weights::CSS, |entry| entry.weights),
562            _ => crate::weights::Weights::CSS,
563        }
564    }
565
566    pub fn add_image(&mut self, width: u32, height: u32, rgba: Vec<u8>) -> ImageId {
567        debug_assert_eq!(rgba.len(), (width * height * 4) as usize);
568        let id = mint().images.insert(self.session);
569        self.images.insert(
570            id,
571            ImageEntry {
572                width,
573                height,
574                rgba: std::sync::Arc::new(rgba),
575                rev: 0,
576                spare: None,
577                spare_at: 0,
578                // Past a page it has nowhere to go but its own texture;
579                // before ADR 0025 it was dropped at emission, silently.
580                backing: if width > crate::atlas::MAX_ATLAS_SIZE
581                    || height > crate::atlas::MAX_ATLAS_SIZE
582                {
583                    ImageBacking::Texture
584                } else {
585                    ImageBacking::Atlas
586                },
587            },
588        );
589        id
590    }
591
592    /// Replaces an image's pixels in place: the
593    /// handle is unchanged, so every node declaring it shows the new
594    /// pixels next frame with no view change; the dimensions may change.
595    /// From the first update on the image is texture-backed for life.
596    /// Returns whether the pixels were taken: false for a foreign or
597    /// removed handle (noted as a miss), and for a buffer that is not
598    /// `width × height × 4` bytes, which changes nothing rather than
599    /// handing a backend a short upload it would refuse with a validation
600    /// error — the doors that take bytes from an app check the length
601    /// first and say so; this is the guard behind them.
602    pub fn update_image(&mut self, id: ImageId, width: u32, height: u32, rgba: Vec<u8>) -> bool {
603        if rgba.len() != width as usize * height as usize * 4 {
604            return false;
605        }
606        let Some(entry) = self.images.get_mut(id) else {
607            self.note_miss(ResourceKind::Image, id.to_ffi());
608            return false;
609        };
610        entry.width = width;
611        entry.height = height;
612        entry.rgba = std::sync::Arc::new(rgba);
613        entry.spare = None;
614        entry.rev = entry.rev.wrapping_add(1);
615        entry.backing = ImageBacking::Texture;
616        true
617    }
618
619    /// [`Self::update_image`] into a buffer the core recycles: `fill` is
620    /// handed `width × height × 4` bytes to write the new pixels into, and
621    /// is not called for a foreign or removed handle (noted as a miss),
622    /// or for a size whose byte count overflows. The bytes it is handed
623    /// hold an earlier frame's pixels, not zeros, so `fill` writes every
624    /// one. The buffer is the image's own when no display list still
625    /// holds it, else the one the previous update replaced, else a new
626    /// one — so a stream updated every frame, between frames or inside
627    /// them, allocates at most three times and then never again. The replaced
628    /// buffer is kept only for an image updated before
629    /// at the same size, and let go [`SPARE_FRAMES`] frames after the
630    /// last update. What every door that copies an app's bytes goes
631    /// through.
632    pub fn update_image_with(
633        &mut self,
634        id: ImageId,
635        width: u32,
636        height: u32,
637        fill: impl FnOnce(&mut [u8]),
638    ) -> bool {
639        use std::sync::Arc;
640        let Some(len) = (width as usize)
641            .checked_mul(height as usize)
642            .and_then(|n| n.checked_mul(4))
643        else {
644            return false;
645        };
646        let Some(entry) = self.images.get_mut(id) else {
647            self.note_miss(ResourceKind::Image, id.to_ffi());
648            return false;
649        };
650        if Arc::get_mut(&mut entry.rgba).is_none() {
651            // The last frame's display list (or a backend mid-upload)
652            // still reads the current buffer: write into the spare if
653            // nothing reads that any more, else into a new one. `vec!`
654            // rather than a resize, so a fresh buffer's zeros are the
655            // allocator's and not a pass over it.
656            let had = entry.spare.is_some();
657            // Unique by both counts: a `Weak` a host took of pixels it
658            // was handed makes `get_mut` refuse the buffer as well.
659            let next = match entry.spare.take() {
660                Some(spare) if Arc::strong_count(&spare) == 1 && Arc::weak_count(&spare) == 0 => {
661                    spare
662                }
663                _ => Arc::new(vec![0; len]),
664            };
665            let replaced = std::mem::replace(&mut entry.rgba, next);
666            // The replaced buffer is worth keeping for a stream: an image
667            // updated before (not the pixels it was added with) whose size
668            // holds. A one-off update, or a resize, keeps nothing.
669            if entry.rev > 0 && replaced.len() == len {
670                entry.spare = Some(replaced);
671                entry.spare_at = self.frames;
672                if !had {
673                    self.spared.push(id);
674                }
675            }
676        }
677        // The size, revision and backing before `fill`, so a `fill` that
678        // panics leaves stale pixels at the right length rather than a
679        // buffer whose length its size does not match.
680        entry.width = width;
681        entry.height = height;
682        entry.rev = entry.rev.wrapping_add(1);
683        entry.backing = ImageBacking::Texture;
684        let buf = Arc::get_mut(&mut entry.rgba).expect("unshared: checked or replaced above");
685        buf.resize(len, 0);
686        // A stream that shrank does not keep its old size's allocation.
687        if buf.capacity() > len.saturating_mul(2) {
688            buf.shrink_to(len);
689        }
690        fill(buf);
691        true
692    }
693
694    /// Called as each frame begins: drops the spare buffer of every image
695    /// not updated for [`SPARE_FRAMES`] frames.
696    pub(crate) fn release_spares(&mut self) {
697        self.frames += 1;
698        if self.spared.is_empty() {
699            return;
700        }
701        let (images, frames) = (&mut self.images, self.frames);
702        self.spared.retain(|&id| match images.get_mut(id) {
703            Some(entry) if entry.spare.is_some() => {
704                if frames - entry.spare_at > SPARE_FRAMES {
705                    entry.spare = None;
706                    false
707                } else {
708                    true
709                }
710            }
711            _ => false,
712        });
713    }
714
715    pub fn remove_image(&mut self, id: ImageId) -> Option<ImageEntry> {
716        let entry = self.images.remove(id);
717        match entry {
718            Some(_) => {
719                mint().images.remove(id);
720            }
721            None => self.note_miss(ResourceKind::Image, id.to_ffi()),
722        }
723        entry
724    }
725
726    /// The pixels behind an image handle, if it is live here.
727    pub fn image(&self, id: ImageId) -> Option<&ImageEntry> {
728        let entry = self.images.get(id);
729        if entry.is_none() {
730            self.note_miss(ResourceKind::Image, id.to_ffi());
731        }
732        entry
733    }
734
735    /// The handle an identical source already has, if any. What makes a
736    /// view that calls `add_fragment` every frame cost a comparison
737    /// instead of a validation (55-73 us) and a pipeline build.
738    pub(crate) fn find_fragment(&self, source: &str) -> Option<FragmentId> {
739        self.fragments
740            .iter()
741            .find(|(_, f)| &*f.source == source)
742            .map(|(id, _)| id)
743    }
744
745    /// Registers validated WGSL, or hands back the handle an identical
746    /// source already has.
747    pub(crate) fn add_fragment(&mut self, source: &str) -> FragmentId {
748        if let Some(id) = self.find_fragment(source) {
749            return id;
750        }
751        let id = mint().fragments.insert(self.session);
752        self.fragments.insert(
753            id,
754            FragmentEntry {
755                source: Arc::from(source),
756            },
757        );
758        id
759    }
760
761    pub(crate) fn remove_fragment(&mut self, id: FragmentId) -> Option<FragmentEntry> {
762        let entry = self.fragments.remove(id);
763        match entry {
764            Some(_) => {
765                mint().fragments.remove(id);
766            }
767            None => self.note_miss(ResourceKind::Fragment, id.to_ffi()),
768        }
769        entry
770    }
771
772    /// The WGSL behind a fragment handle, if it is live here. A miss is
773    /// what makes the node draw nothing, and records a foreign handle.
774    pub fn fragment(&self, id: FragmentId) -> Option<&Arc<str>> {
775        let entry = self.fragments.get(id);
776        if entry.is_none() {
777            self.note_miss(ResourceKind::Fragment, id.to_ffi());
778        }
779        entry.map(|f| &f.source)
780    }
781
782    /// Registers a sound from its encoded file bytes.
783    pub fn add_sound(&mut self, bytes: Vec<u8>) -> SoundId {
784        let id = mint().sounds.insert(self.session);
785        self.sounds.insert(
786            id,
787            SoundEntry {
788                bytes: Arc::from(bytes),
789            },
790        );
791        id
792    }
793
794    pub fn remove_sound(&mut self, id: SoundId) -> Option<SoundEntry> {
795        let entry = self.sounds.remove(id);
796        match entry {
797            Some(_) => {
798                mint().sounds.remove(id);
799            }
800            None => self.note_miss(ResourceKind::Sound, id.to_ffi()),
801        }
802        entry
803    }
804
805    /// Whether any sound is registered: what tells an audio backend it
806    /// will be asked to play something, before it is.
807    pub fn has_sounds(&self) -> bool {
808        !self.sounds.is_empty()
809    }
810
811    /// The encoded bytes behind a sound handle, if it is live here.
812    pub fn sound(&self, id: SoundId) -> Option<&Arc<[u8]>> {
813        let entry = self.sounds.get(id);
814        if entry.is_none() {
815            self.note_miss(ResourceKind::Sound, id.to_ffi());
816        }
817        entry.map(|s| &s.bytes)
818    }
819}
820
821impl Drop for Resources {
822    /// A session's handles leave the mint with it, so the slots come back
823    /// and a process that opens and closes many sessions (a test binary)
824    /// does not keep every id it ever minted.
825    fn drop(&mut self) {
826        let mut m = mint();
827        for (id, _) in self.images.iter() {
828            m.images.remove(id);
829        }
830        for (id, _) in self.fonts.iter() {
831            m.fonts.remove(id);
832        }
833        for (id, _) in self.fragments.iter() {
834            m.fragments.remove(id);
835        }
836        for (id, _) in self.sounds.iter() {
837            m.sounds.remove(id);
838        }
839    }
840}
841
842#[cfg(test)]
843mod tests {
844    use super::*;
845    use slotmap::KeyData;
846
847    /// RG59: a reweigh reports a change only to a family registered
848    /// before — text may have been shaped in it — and never for the one
849    /// just registered, so a list registering a family per row as it
850    /// scrolls does not drop every window's shaped text each time.
851    #[test]
852    fn a_reweigh_reports_only_a_family_text_may_be_shaped_in() {
853        use crate::weights::Weights;
854        use cosmic_text::fontdb::{Database, Source};
855        let mut db = Database::new();
856        let load = |db: &mut Database, weight| {
857            let bytes = crate::testing::font_face("Kui Fresh", weight, false, true);
858            db.load_font_source(Source::Binary(std::sync::Arc::new(bytes)));
859        };
860        load(&mut db, 400);
861        let touched = std::iter::once("Kui Fresh".to_string()).collect();
862        let mut r = Resources::new(SessionId::next());
863        let id = r.add_font("Kui Fresh".into(), vec![]);
864        assert!(!r.reweigh(&db, &touched, Some(id)), "just registered");
865        assert_ne!(r.weights_of(FontFamily::Custom(id)), Weights::CSS);
866        assert!(!r.reweigh(&db, &touched, None), "nothing moved");
867        load(&mut db, 700);
868        assert!(r.reweigh(&db, &touched, None), "its Bold came");
869        assert_eq!(r.weights_of(FontFamily::Custom(id)), Weights::CSS);
870    }
871
872    #[test]
873    fn stale_handle_is_rejected_after_removal() {
874        let mut r = Resources::new(SessionId::next());
875        let id = r.add_image(1, 1, vec![0; 4]);
876        r.remove_image(id);
877        assert!(r.image(id).is_none());
878        // A new insert may reuse the slot but bumps the generation.
879        let id2 = r.add_image(1, 1, vec![0; 4]);
880        assert_ne!(id, id2);
881        assert!(r.image(id).is_none());
882        assert!(r.image(id2).is_some());
883        // Removed, not foreign: nothing to report.
884        assert!(r.take_foreign().is_empty());
885    }
886
887    /// Raw 0 is index 0, the slot the mint never fills, so it misses in
888    /// every session and is nobody's — the `fragments` scene's dead `src`
889    /// and the doors' "no image" both rest on it. Raw 1 is *not* that:
890    /// `from_ffi` reads every handle at an odd generation, so it is the
891    /// first key a fresh process hands out.
892    #[test]
893    fn raw_zero_is_dead_whatever_was_minted() {
894        let mut a = Resources::new(SessionId::next());
895        let b = Resources::new(SessionId::next());
896        let _ = a.add_image(1, 1, vec![0; 4]);
897        let _ = a.add_fragment("");
898        for r in [&a, &b] {
899            assert!(r.image(ImageId::from_ffi(0)).is_none());
900            assert!(r.fragment(FragmentId::from_ffi(0)).is_none());
901            assert!(r.take_foreign().is_empty(), "raw 0 is nobody's");
902        }
903    }
904
905    #[test]
906    fn handles_round_trip_through_u64() {
907        let mut r = Resources::new(SessionId::next());
908        let id = r.add_image(1, 1, vec![0; 4]);
909        let raw = id.data().as_ffi();
910        let back = ImageId::from(KeyData::from_ffi(raw));
911        assert_eq!(id, back);
912        assert!(r.image(back).is_some());
913    }
914
915    #[test]
916    fn two_registries_never_mint_the_same_handle() {
917        let mut a = Resources::new(SessionId::next());
918        let mut b = Resources::new(SessionId::next());
919        let ia = a.add_image(1, 1, vec![0; 4]);
920        let ib = b.add_image(2, 2, vec![0; 16]);
921        assert_ne!(ia, ib, "two first images, two handles");
922        assert_ne!(
923            a.add_font("A".into(), vec![]),
924            b.add_font("B".into(), vec![])
925        );
926        assert_ne!(a.add_sound(vec![0]), b.add_sound(vec![1]));
927    }
928
929    #[test]
930    fn a_foreign_handle_misses_and_is_reported_once() {
931        let mut a = Resources::new(SessionId::next());
932        let b = Resources::new(SessionId::next());
933        let id = a.add_image(1, 1, vec![0; 4]);
934        assert!(b.image(id).is_none(), "b never draws a's pixels");
935        assert!(b.image(id).is_none());
936        let hits = b.take_foreign();
937        assert_eq!(
938            hits,
939            [Foreign {
940                kind: ResourceKind::Image,
941                raw: id.to_ffi(),
942                owner: a.session(),
943                here: b.session(),
944            }]
945        );
946        assert!(b.take_foreign().is_empty(), "drained");
947        // The owner resolving its own handle records nothing.
948        assert!(a.image(id).is_some());
949        assert!(a.take_foreign().is_empty());
950        // Once the owner removes it, the miss is a removal everywhere.
951        a.remove_image(id);
952        assert!(b.image(id).is_none());
953        assert!(b.take_foreign().is_empty());
954    }
955
956    #[test]
957    fn removing_a_foreign_handle_touches_nothing_and_reports() {
958        let mut a = Resources::new(SessionId::next());
959        let mut b = Resources::new(SessionId::next());
960        let sound = a.add_sound(vec![1, 2, 3]);
961        assert!(b.remove_sound(sound).is_none());
962        assert!(a.sound(sound).is_some(), "a's sound is still a's");
963        assert_eq!(b.take_foreign()[0].kind, ResourceKind::Sound);
964    }
965
966    #[test]
967    fn a_dropped_registry_gives_its_slots_back() {
968        let id = {
969            let mut a = Resources::new(SessionId::next());
970            a.add_image(1, 1, vec![0; 4])
971        };
972        assert!(mint().images.get(id).is_none(), "gone with its session");
973        let b = Resources::new(SessionId::next());
974        assert!(b.image(id).is_none());
975        assert!(
976            b.take_foreign().is_empty(),
977            "a dead session's handle is just removed"
978        );
979    }
980}