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