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    /// The family `FontFamily::Mono` is shaped as by name while
410    /// `fallback` names any (backlog RG118): cosmic-text's generic
411    /// monospace family asks every monospaced face on the machine for a
412    /// character its own face lacks before it gets to the lists the app's
413    /// names lead, so the app's choice lost to whichever monospaced face
414    /// came first — Courier New's italic for Hebrew on a Mac. By name, it
415    /// asks its own face and then the app's, as a registered family does.
416    /// None with no list, where the monospaced faces are asked first as
417    /// before (`SessionState::name_mono` keeps it). With the name, the
418    /// weights its faces cover: by name cosmic-text takes a face of the
419    /// family only at a weight it has, and passes a single-weight family
420    /// over for bold — to the proportional lists — where the generic
421    /// family took any weight (backlog RG123).
422    pub(crate) mono: Option<(String, crate::weights::Weights)>,
423    /// Handles of other sessions this registry was asked for since the
424    /// last drain, each once. A `RefCell` because the resolves that find
425    /// them (`family_of` under a shaping closure, `image` under the
426    /// emitter's shared borrow) hold the registry by `&`.
427    foreign: RefCell<Vec<Foreign>>,
428    /// Frames begun by any window of the session, for aging spares.
429    frames: u64,
430    /// The images holding a spare buffer, swept each frame.
431    spared: Vec<ImageId>,
432}
433
434impl Resources {
435    /// The registry for session `session`; keys come from the process's
436    /// mint.
437    pub fn new(session: SessionId) -> Self {
438        Self {
439            session,
440            images: SparseSecondaryMap::new(),
441            fonts: SparseSecondaryMap::new(),
442            sounds: SparseSecondaryMap::new(),
443            fragments: SparseSecondaryMap::new(),
444            fallback: Vec::new(),
445            mono: None,
446            foreign: RefCell::new(Vec::new()),
447            frames: 0,
448            spared: Vec::new(),
449        }
450    }
451
452    /// The session this registry belongs to.
453    pub fn session(&self) -> SessionId {
454        self.session
455    }
456
457    /// The foreign handles resolved since the last call (see
458    /// [`Foreign`]); `Core::take_warnings` turns each into one line.
459    pub(crate) fn take_foreign(&self) -> Vec<Foreign> {
460        std::mem::take(&mut *self.foreign.borrow_mut())
461    }
462
463    /// A lookup missed: the mint says whether the handle is live in some
464    /// other session (recorded, once) or in none (removed — silent, the
465    /// documented behaviour). Only the miss path pays for the lock.
466    fn note_miss(&self, kind: ResourceKind, raw: u64) {
467        let owner = {
468            let m = mint();
469            match kind {
470                ResourceKind::Image => m.images.get(ImageId::from_ffi(raw)).copied(),
471                ResourceKind::Font => m.fonts.get(FontId::from_ffi(raw)).copied(),
472                ResourceKind::Sound => m.sounds.get(SoundId::from_ffi(raw)).copied(),
473                ResourceKind::Fragment => m.fragments.get(FragmentId::from_ffi(raw)).copied(),
474            }
475        };
476        let Some(owner) = owner else {
477            return;
478        };
479        if owner == self.session {
480            return;
481        }
482        let mut foreign = self.foreign.borrow_mut();
483        if foreign.len() >= MAX_FOREIGN || foreign.iter().any(|f| f.kind == kind && f.raw == raw) {
484            return;
485        }
486        foreign.push(Foreign {
487            kind,
488            raw,
489            owner,
490            here: self.session,
491        });
492    }
493
494    pub(crate) fn add_font(
495        &mut self,
496        family: String,
497        faces: Vec<cosmic_text::fontdb::ID>,
498    ) -> FontId {
499        let id = mint().fonts.insert(self.session);
500        self.fonts.insert(
501            id,
502            FontEntry {
503                family,
504                faces,
505                weights: crate::weights::Weights::CSS,
506            },
507        );
508        id
509    }
510
511    /// Reads again the weights of the registered families `families` holds
512    /// from what `db` has of them now: after a family is
513    /// registered, and after faces of it come into the database or leave.
514    /// Whether the weights of a font other than `fresh` — the one just
515    /// registered, which nothing has shaped in yet — changed: text shaped
516    /// in it was shaped at the old ones.
517    pub(crate) fn reweigh(
518        &mut self,
519        db: &cosmic_text::fontdb::Database,
520        families: &rustc_hash::FxHashSet<String>,
521        fresh: Option<FontId>,
522    ) -> bool {
523        let mut changed = false;
524        for (id, entry) in self.fonts.iter_mut() {
525            if families.contains(&entry.family) {
526                let weights = crate::weights::Weights::of(db, &entry.family);
527                changed |= Some(id) != fresh && weights != entry.weights;
528                entry.weights = weights;
529            }
530        }
531        changed
532    }
533
534    pub(crate) fn remove_font(&mut self, id: FontId) -> Option<FontEntry> {
535        let entry = self.fonts.remove(id);
536        match entry {
537            Some(_) => {
538                mint().fonts.remove(id);
539            }
540            None => self.note_miss(ResourceKind::Font, id.to_ffi()),
541        }
542        entry
543    }
544
545    /// The registered family name, if the handle is live here.
546    pub fn font_family(&self, id: FontId) -> Option<&str> {
547        let entry = self.fonts.get(id);
548        if entry.is_none() {
549            self.note_miss(ResourceKind::Font, id.to_ffi());
550        }
551        entry.map(|f| f.family.as_str())
552    }
553
554    /// The cosmic-text family a style's `FontFamily` shapes with; an unknown
555    /// or removed custom font falls back to sans-serif. `Mono` is its face's
556    /// family by name while the app names fallbacks (see `mono`).
557    pub(crate) fn family_of(&self, f: FontFamily) -> cosmic_text::Family<'_> {
558        match f {
559            FontFamily::Sans => cosmic_text::Family::SansSerif,
560            FontFamily::Serif => cosmic_text::Family::Serif,
561            FontFamily::Mono => self
562                .mono
563                .as_ref()
564                .map_or(cosmic_text::Family::Monospace, |(name, _)| {
565                    cosmic_text::Family::Name(name)
566                }),
567            FontFamily::Custom(id) => match self.font_family(id) {
568                Some(name) => cosmic_text::Family::Name(name),
569                None => cosmic_text::Family::SansSerif,
570            },
571        }
572    }
573
574    /// The weights a style's `FontFamily` is asked at: a
575    /// registered family's own, the pinned face's for `Mono` while it is
576    /// shaped by name (see `mono`), the CSS ones for a generic family and
577    /// for an unknown or removed custom font (which shapes as sans-serif).
578    pub(crate) fn weights_of(&self, f: FontFamily) -> crate::weights::Weights {
579        match f {
580            FontFamily::Custom(id) => self
581                .fonts
582                .get(id)
583                .map_or(crate::weights::Weights::CSS, |entry| entry.weights),
584            FontFamily::Mono => self
585                .mono
586                .as_ref()
587                .map_or(crate::weights::Weights::CSS, |&(_, weights)| weights),
588            _ => crate::weights::Weights::CSS,
589        }
590    }
591
592    pub fn add_image(&mut self, width: u32, height: u32, rgba: Vec<u8>) -> ImageId {
593        debug_assert_eq!(rgba.len(), (width * height * 4) as usize);
594        let id = mint().images.insert(self.session);
595        self.images.insert(
596            id,
597            ImageEntry {
598                width,
599                height,
600                rgba: std::sync::Arc::new(rgba),
601                rev: 0,
602                spare: None,
603                spare_at: 0,
604                // Past a page it has nowhere to go but its own texture;
605                // before ADR 0025 it was dropped at emission, silently.
606                backing: if width > crate::atlas::MAX_ATLAS_SIZE
607                    || height > crate::atlas::MAX_ATLAS_SIZE
608                {
609                    ImageBacking::Texture
610                } else {
611                    ImageBacking::Atlas
612                },
613            },
614        );
615        id
616    }
617
618    /// Replaces an image's pixels in place: the
619    /// handle is unchanged, so every node declaring it shows the new
620    /// pixels next frame with no view change; the dimensions may change.
621    /// From the first update on the image is texture-backed for life.
622    /// Returns whether the pixels were taken: false for a foreign or
623    /// removed handle (noted as a miss), and for a buffer that is not
624    /// `width × height × 4` bytes, which changes nothing rather than
625    /// handing a backend a short upload it would refuse with a validation
626    /// error — the doors that take bytes from an app check the length
627    /// first and say so; this is the guard behind them.
628    pub fn update_image(&mut self, id: ImageId, width: u32, height: u32, rgba: Vec<u8>) -> bool {
629        if rgba.len() != width as usize * height as usize * 4 {
630            return false;
631        }
632        let Some(entry) = self.images.get_mut(id) else {
633            self.note_miss(ResourceKind::Image, id.to_ffi());
634            return false;
635        };
636        entry.width = width;
637        entry.height = height;
638        entry.rgba = std::sync::Arc::new(rgba);
639        entry.spare = None;
640        entry.rev = entry.rev.wrapping_add(1);
641        entry.backing = ImageBacking::Texture;
642        true
643    }
644
645    /// [`Self::update_image`] into a buffer the core recycles: `fill` is
646    /// handed `width × height × 4` bytes to write the new pixels into, and
647    /// is not called for a foreign or removed handle (noted as a miss),
648    /// or for a size whose byte count overflows. The bytes it is handed
649    /// hold an earlier frame's pixels, not zeros, so `fill` writes every
650    /// one. The buffer is the image's own when no display list still
651    /// holds it, else the one the previous update replaced, else a new
652    /// one — so a stream updated every frame, between frames or inside
653    /// them, allocates at most three times and then never again. The replaced
654    /// buffer is kept only for an image updated before
655    /// at the same size, and let go [`SPARE_FRAMES`] frames after the
656    /// last update. What every door that copies an app's bytes goes
657    /// through.
658    pub fn update_image_with(
659        &mut self,
660        id: ImageId,
661        width: u32,
662        height: u32,
663        fill: impl FnOnce(&mut [u8]),
664    ) -> bool {
665        use std::sync::Arc;
666        let Some(len) = (width as usize)
667            .checked_mul(height as usize)
668            .and_then(|n| n.checked_mul(4))
669        else {
670            return false;
671        };
672        let Some(entry) = self.images.get_mut(id) else {
673            self.note_miss(ResourceKind::Image, id.to_ffi());
674            return false;
675        };
676        if Arc::get_mut(&mut entry.rgba).is_none() {
677            // The last frame's display list (or a backend mid-upload)
678            // still reads the current buffer: write into the spare if
679            // nothing reads that any more, else into a new one. `vec!`
680            // rather than a resize, so a fresh buffer's zeros are the
681            // allocator's and not a pass over it.
682            let had = entry.spare.is_some();
683            // Unique by both counts: a `Weak` a host took of pixels it
684            // was handed makes `get_mut` refuse the buffer as well.
685            let next = match entry.spare.take() {
686                Some(spare) if Arc::strong_count(&spare) == 1 && Arc::weak_count(&spare) == 0 => {
687                    spare
688                }
689                _ => Arc::new(vec![0; len]),
690            };
691            let replaced = std::mem::replace(&mut entry.rgba, next);
692            // The replaced buffer is worth keeping for a stream: an image
693            // updated before (not the pixels it was added with) whose size
694            // holds. A one-off update, or a resize, keeps nothing.
695            if entry.rev > 0 && replaced.len() == len {
696                entry.spare = Some(replaced);
697                entry.spare_at = self.frames;
698                if !had {
699                    self.spared.push(id);
700                }
701            }
702        }
703        // The size, revision and backing before `fill`, so a `fill` that
704        // panics leaves stale pixels at the right length rather than a
705        // buffer whose length its size does not match.
706        entry.width = width;
707        entry.height = height;
708        entry.rev = entry.rev.wrapping_add(1);
709        entry.backing = ImageBacking::Texture;
710        let buf = Arc::get_mut(&mut entry.rgba).expect("unshared: checked or replaced above");
711        buf.resize(len, 0);
712        // A stream that shrank does not keep its old size's allocation.
713        if buf.capacity() > len.saturating_mul(2) {
714            buf.shrink_to(len);
715        }
716        fill(buf);
717        true
718    }
719
720    /// Called as each frame begins: drops the spare buffer of every image
721    /// not updated for [`SPARE_FRAMES`] frames.
722    pub(crate) fn release_spares(&mut self) {
723        self.frames += 1;
724        if self.spared.is_empty() {
725            return;
726        }
727        let (images, frames) = (&mut self.images, self.frames);
728        self.spared.retain(|&id| match images.get_mut(id) {
729            Some(entry) if entry.spare.is_some() => {
730                if frames - entry.spare_at > SPARE_FRAMES {
731                    entry.spare = None;
732                    false
733                } else {
734                    true
735                }
736            }
737            _ => false,
738        });
739    }
740
741    pub fn remove_image(&mut self, id: ImageId) -> Option<ImageEntry> {
742        let entry = self.images.remove(id);
743        match entry {
744            Some(_) => {
745                mint().images.remove(id);
746            }
747            None => self.note_miss(ResourceKind::Image, id.to_ffi()),
748        }
749        entry
750    }
751
752    /// The pixels behind an image handle, if it is live here.
753    pub fn image(&self, id: ImageId) -> Option<&ImageEntry> {
754        let entry = self.images.get(id);
755        if entry.is_none() {
756            self.note_miss(ResourceKind::Image, id.to_ffi());
757        }
758        entry
759    }
760
761    /// The handle an identical source already has, if any. What makes a
762    /// view that calls `add_fragment` every frame cost a comparison
763    /// instead of a validation (55-73 us) and a pipeline build.
764    pub(crate) fn find_fragment(&self, source: &str) -> Option<FragmentId> {
765        self.fragments
766            .iter()
767            .find(|(_, f)| &*f.source == source)
768            .map(|(id, _)| id)
769    }
770
771    /// Registers validated WGSL, or hands back the handle an identical
772    /// source already has.
773    pub(crate) fn add_fragment(&mut self, source: &str) -> FragmentId {
774        if let Some(id) = self.find_fragment(source) {
775            return id;
776        }
777        let id = mint().fragments.insert(self.session);
778        self.fragments.insert(
779            id,
780            FragmentEntry {
781                source: Arc::from(source),
782            },
783        );
784        id
785    }
786
787    pub(crate) fn remove_fragment(&mut self, id: FragmentId) -> Option<FragmentEntry> {
788        let entry = self.fragments.remove(id);
789        match entry {
790            Some(_) => {
791                mint().fragments.remove(id);
792            }
793            None => self.note_miss(ResourceKind::Fragment, id.to_ffi()),
794        }
795        entry
796    }
797
798    /// The WGSL behind a fragment handle, if it is live here. A miss is
799    /// what makes the node draw nothing, and records a foreign handle.
800    pub fn fragment(&self, id: FragmentId) -> Option<&Arc<str>> {
801        let entry = self.fragments.get(id);
802        if entry.is_none() {
803            self.note_miss(ResourceKind::Fragment, id.to_ffi());
804        }
805        entry.map(|f| &f.source)
806    }
807
808    /// Registers a sound from its encoded file bytes.
809    pub fn add_sound(&mut self, bytes: Vec<u8>) -> SoundId {
810        let id = mint().sounds.insert(self.session);
811        self.sounds.insert(
812            id,
813            SoundEntry {
814                bytes: Arc::from(bytes),
815            },
816        );
817        id
818    }
819
820    pub fn remove_sound(&mut self, id: SoundId) -> Option<SoundEntry> {
821        let entry = self.sounds.remove(id);
822        match entry {
823            Some(_) => {
824                mint().sounds.remove(id);
825            }
826            None => self.note_miss(ResourceKind::Sound, id.to_ffi()),
827        }
828        entry
829    }
830
831    /// Whether any sound is registered: what tells an audio backend it
832    /// will be asked to play something, before it is.
833    pub fn has_sounds(&self) -> bool {
834        !self.sounds.is_empty()
835    }
836
837    /// The encoded bytes behind a sound handle, if it is live here.
838    pub fn sound(&self, id: SoundId) -> Option<&Arc<[u8]>> {
839        let entry = self.sounds.get(id);
840        if entry.is_none() {
841            self.note_miss(ResourceKind::Sound, id.to_ffi());
842        }
843        entry.map(|s| &s.bytes)
844    }
845}
846
847impl Drop for Resources {
848    /// A session's handles leave the mint with it, so the slots come back
849    /// and a process that opens and closes many sessions (a test binary)
850    /// does not keep every id it ever minted.
851    fn drop(&mut self) {
852        let mut m = mint();
853        for (id, _) in self.images.iter() {
854            m.images.remove(id);
855        }
856        for (id, _) in self.fonts.iter() {
857            m.fonts.remove(id);
858        }
859        for (id, _) in self.fragments.iter() {
860            m.fragments.remove(id);
861        }
862        for (id, _) in self.sounds.iter() {
863            m.sounds.remove(id);
864        }
865    }
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use slotmap::KeyData;
872
873    /// RG59: a reweigh reports a change only to a family registered
874    /// before — text may have been shaped in it — and never for the one
875    /// just registered, so a list registering a family per row as it
876    /// scrolls does not drop every window's shaped text each time.
877    #[test]
878    fn a_reweigh_reports_only_a_family_text_may_be_shaped_in() {
879        use crate::weights::Weights;
880        use cosmic_text::fontdb::{Database, Source};
881        let mut db = Database::new();
882        let load = |db: &mut Database, weight| {
883            let bytes = crate::testing::font_face("Kui Fresh", weight, false, true);
884            db.load_font_source(Source::Binary(std::sync::Arc::new(bytes)));
885        };
886        load(&mut db, 400);
887        let touched = std::iter::once("Kui Fresh".to_string()).collect();
888        let mut r = Resources::new(SessionId::next());
889        let id = r.add_font("Kui Fresh".into(), vec![]);
890        assert!(!r.reweigh(&db, &touched, Some(id)), "just registered");
891        assert_ne!(r.weights_of(FontFamily::Custom(id)), Weights::CSS);
892        assert!(!r.reweigh(&db, &touched, None), "nothing moved");
893        load(&mut db, 700);
894        assert!(r.reweigh(&db, &touched, None), "its Bold came");
895        assert_eq!(r.weights_of(FontFamily::Custom(id)), Weights::CSS);
896    }
897
898    #[test]
899    fn stale_handle_is_rejected_after_removal() {
900        let mut r = Resources::new(SessionId::next());
901        let id = r.add_image(1, 1, vec![0; 4]);
902        r.remove_image(id);
903        assert!(r.image(id).is_none());
904        // A new insert may reuse the slot but bumps the generation.
905        let id2 = r.add_image(1, 1, vec![0; 4]);
906        assert_ne!(id, id2);
907        assert!(r.image(id).is_none());
908        assert!(r.image(id2).is_some());
909        // Removed, not foreign: nothing to report.
910        assert!(r.take_foreign().is_empty());
911    }
912
913    /// Raw 0 is index 0, the slot the mint never fills, so it misses in
914    /// every session and is nobody's — the `fragments` scene's dead `src`
915    /// and the doors' "no image" both rest on it. Raw 1 is *not* that:
916    /// `from_ffi` reads every handle at an odd generation, so it is the
917    /// first key a fresh process hands out.
918    #[test]
919    fn raw_zero_is_dead_whatever_was_minted() {
920        let mut a = Resources::new(SessionId::next());
921        let b = Resources::new(SessionId::next());
922        let _ = a.add_image(1, 1, vec![0; 4]);
923        let _ = a.add_fragment("");
924        for r in [&a, &b] {
925            assert!(r.image(ImageId::from_ffi(0)).is_none());
926            assert!(r.fragment(FragmentId::from_ffi(0)).is_none());
927            assert!(r.take_foreign().is_empty(), "raw 0 is nobody's");
928        }
929    }
930
931    #[test]
932    fn handles_round_trip_through_u64() {
933        let mut r = Resources::new(SessionId::next());
934        let id = r.add_image(1, 1, vec![0; 4]);
935        let raw = id.data().as_ffi();
936        let back = ImageId::from(KeyData::from_ffi(raw));
937        assert_eq!(id, back);
938        assert!(r.image(back).is_some());
939    }
940
941    #[test]
942    fn two_registries_never_mint_the_same_handle() {
943        let mut a = Resources::new(SessionId::next());
944        let mut b = Resources::new(SessionId::next());
945        let ia = a.add_image(1, 1, vec![0; 4]);
946        let ib = b.add_image(2, 2, vec![0; 16]);
947        assert_ne!(ia, ib, "two first images, two handles");
948        assert_ne!(
949            a.add_font("A".into(), vec![]),
950            b.add_font("B".into(), vec![])
951        );
952        assert_ne!(a.add_sound(vec![0]), b.add_sound(vec![1]));
953    }
954
955    #[test]
956    fn a_foreign_handle_misses_and_is_reported_once() {
957        let mut a = Resources::new(SessionId::next());
958        let b = Resources::new(SessionId::next());
959        let id = a.add_image(1, 1, vec![0; 4]);
960        assert!(b.image(id).is_none(), "b never draws a's pixels");
961        assert!(b.image(id).is_none());
962        let hits = b.take_foreign();
963        assert_eq!(
964            hits,
965            [Foreign {
966                kind: ResourceKind::Image,
967                raw: id.to_ffi(),
968                owner: a.session(),
969                here: b.session(),
970            }]
971        );
972        assert!(b.take_foreign().is_empty(), "drained");
973        // The owner resolving its own handle records nothing.
974        assert!(a.image(id).is_some());
975        assert!(a.take_foreign().is_empty());
976        // Once the owner removes it, the miss is a removal everywhere.
977        a.remove_image(id);
978        assert!(b.image(id).is_none());
979        assert!(b.take_foreign().is_empty());
980    }
981
982    #[test]
983    fn removing_a_foreign_handle_touches_nothing_and_reports() {
984        let mut a = Resources::new(SessionId::next());
985        let mut b = Resources::new(SessionId::next());
986        let sound = a.add_sound(vec![1, 2, 3]);
987        assert!(b.remove_sound(sound).is_none());
988        assert!(a.sound(sound).is_some(), "a's sound is still a's");
989        assert_eq!(b.take_foreign()[0].kind, ResourceKind::Sound);
990    }
991
992    #[test]
993    fn a_dropped_registry_gives_its_slots_back() {
994        let id = {
995            let mut a = Resources::new(SessionId::next());
996            a.add_image(1, 1, vec![0; 4])
997        };
998        assert!(mint().images.get(id).is_none(), "gone with its session");
999        let b = Resources::new(SessionId::next());
1000        assert!(b.image(id).is_none());
1001        assert!(
1002            b.take_foreign().is_empty(),
1003            "a dead session's handle is just removed"
1004        );
1005    }
1006}