Skip to main content

kui_core/runtime/
resources_api.rs

1//! Resources through a core: fonts, sounds and images live in the
2//! session's registry (`resources`), so registering one here registers
3//! it for every window; playback is commands the driver drains
4//! (`audio`). Nothing here touches a device.
5
6use super::*;
7
8impl Core {
9    /// Turns the sounds nodes asked for (`click_sound` / `hover_sound`)
10    /// into play commands. Declarative sounds carry no tag, so they never
11    /// report `ended`.
12    pub(crate) fn flush_sound_requests(&mut self) {
13        let window = self.env.window.id;
14        let mut sess = self.session.state();
15        for sound in self.interaction.take_sound_requests() {
16            sess.audio.play(
17                OriginId::HOST,
18                window,
19                Key::ROOT,
20                sound,
21                crate::audio::PlayOptions::default(),
22            );
23        }
24    }
25
26    // -- Fragments ------------------------------------------------------
27
28    /// Registers a WGSL fragment function for a `fragment` node.
29    /// The app writes one function:
30    ///
31    /// ```wgsl
32    /// fn fragment(in: FragmentIn, params: array<vec4<f32>, 4>) -> vec4<f32>
33    /// ```
34    ///
35    /// and the core wraps it in the prelude and epilogue that give it the
36    /// node's rounded box, the inherited clip, the group opacity and the
37    /// blend (see `crate::fragment`). `None` when the source does not
38    /// compile, with a `fragment-rejected` warning carrying naga's message
39    /// in the app's own line numbers — so a bad shader is a warning at
40    /// registration, in a headless test included, and never a blank box in
41    /// a window.
42    ///
43    /// Idempotent by source: the same text gets the same handle without
44    /// validating again, so a view may call this every frame. Registering
45    /// at startup is still the advice, because the *backend* builds a
46    /// pipeline the first time it sees a handle.
47    pub fn add_fragment(&mut self, wgsl: &str) -> Option<crate::resources::FragmentId> {
48        if let Some(id) = self.session.state().resources.find_fragment(wgsl) {
49            return Some(id);
50        }
51        if let Err(message) = crate::fragment::validate(wgsl) {
52            self.warn(crate::diag::Warning {
53                code: crate::diag::FRAGMENT_REJECTED,
54                key: crate::key::Key::ROOT,
55                message: format!("fragment source rejected: {message}"),
56            });
57            return None;
58        }
59        Some(self.session.state().resources.add_fragment(wgsl))
60    }
61
62    /// Forgets a registered fragment. Nodes still naming it draw nothing,
63    /// and the next frame any window draws has the backend drop the
64    /// pipelines it built for it.
65    pub fn remove_fragment(&mut self, id: crate::resources::FragmentId) {
66        self.session.state().remove_fragment(id);
67        // The stock polygon's handle, if that is what went: the next
68        // `polygon` node registers it again rather than drawing nothing.
69        if self.stock_polygon == Some(id) {
70            self.stock_polygon = None;
71        }
72    }
73
74    /// The whole WGSL module behind a fragment handle — the app's source
75    /// between the core's prelude and epilogue — which is what a backend
76    /// compiles. A host rendering the display list itself asks for this
77    /// rather than assembling its own, so what it compiles is what the
78    /// core validated.
79    pub fn fragment_module_source(&self, id: crate::resources::FragmentId) -> Option<String> {
80        let sess = self.session.state();
81        let app = sess.resources.fragment(id)?;
82        Some(crate::fragment::module_source(app))
83    }
84
85    // -- Fonts ----------------------------------------------------------
86
87    /// Registers a font from its file bytes (TTF/OTF/TTC); `None` when the
88    /// data holds no usable face — none the font database can read, or
89    /// none whose glyphs can be measured (no `head`, `hhea` or `hmtx`).
90    /// Shape with it via `TextStyle::font`.
91    pub fn add_font_data(&mut self, data: Vec<u8>) -> Option<crate::resources::FontId> {
92        use cosmic_text::fontdb::Source;
93        let id = {
94            let sess = &mut *self.session.state();
95            let ids = sess
96                .fonts
97                .db_mut()
98                .load_font_source(Source::Binary(std::sync::Arc::new(data)));
99            sess.share_loaded_faces();
100            let db = sess.fonts.db_mut();
101            let ids = crate::text::keep_measurable(db, ids.to_vec());
102            let family = db.face(*ids.first()?)?.families.first()?.0.clone();
103            sess.fonts_rev += 1;
104            let touched = families_of(db, &ids);
105            let id = sess.resources.add_font(family, ids.to_vec());
106            if sess.resources.reweigh(sess.fonts.db(), &touched, Some(id)) {
107                sess.weights_rev += 1;
108            }
109            id
110        };
111        self.sync_font_names();
112        Some(id)
113    }
114
115    /// Registers a font file (TTF/OTF/TTC) by path, memory-mapped by the
116    /// font database; `None` when it cannot be read or holds no usable
117    /// face (see [`add_font_data`](Self::add_font_data)). Shape with it
118    /// via `TextStyle::font`.
119    pub fn load_font_file(
120        &mut self,
121        path: impl Into<std::path::PathBuf>,
122    ) -> Option<crate::resources::FontId> {
123        use cosmic_text::fontdb::Source;
124        let id = {
125            let sess = &mut *self.session.state();
126            let ids = sess
127                .fonts
128                .db_mut()
129                .load_font_source(Source::File(path.into()));
130            // Its own faces too, not only the ones before it (DX25).
131            sess.share_loaded_faces();
132            let db = sess.fonts.db_mut();
133            let ids = crate::text::keep_measurable(db, ids.to_vec());
134            let family = db.face(*ids.first()?)?.families.first()?.0.clone();
135            sess.fonts_rev += 1;
136            let touched = families_of(db, &ids);
137            let id = sess.resources.add_font(family, ids.to_vec());
138            if sess.resources.reweigh(sess.fonts.db(), &touched, Some(id)) {
139                sess.weights_rev += 1;
140            }
141            id
142        };
143        self.sync_font_names();
144        Some(id)
145    }
146
147    /// Loads every font file under `dir` (recursively) into the font
148    /// database, so their families become available to `add_system_font`
149    /// by name; returns how many faces were added. A face whose glyphs
150    /// cannot be measured is left out and not counted. A
151    /// bundled `fonts/` folder next to the app is the usual case.
152    pub fn load_fonts_dir(&mut self, dir: impl AsRef<std::path::Path>) -> usize {
153        let sess = &mut *self.session.state();
154        let db = sess.fonts.db_mut();
155        let before: rustc_hash::FxHashSet<_> = db.faces().map(|face| face.id).collect();
156        db.load_fonts_dir(dir);
157        sess.share_loaded_faces();
158        let db = sess.fonts.db_mut();
159        let added = db
160            .faces()
161            .map(|face| face.id)
162            .filter(|id| !before.contains(id))
163            .collect();
164        let added = crate::text::keep_measurable(db, added);
165        // A registered family may have gained a bold (backlog F100).
166        let touched = families_of(db, &added);
167        if sess.resources.reweigh(sess.fonts.db(), &touched, None) {
168            sess.weights_rev += 1;
169        }
170        added.len()
171    }
172
173    /// Scans the system's fonts again and brings this session's font
174    /// database up to it: a face installed since the last scan joins it,
175    /// one uninstalled leaves it. Returns how many faces came and went, 0
176    /// when nothing did.
177    ///
178    /// The system's fonts are scanned once a process, and every session
179    /// starts from that scan, so a font the user installs while the app
180    /// runs is not seen until something asks. The winit runner
181    /// (`kui-native`) asks itself when macOS or Windows says the installed
182    /// fonts changed; a host with its own windowing, or on Linux, where
183    /// fontconfig says nothing, calls this when it has reason to think the
184    /// set changed (a "fonts" pane opening, the window taking focus back).
185    /// It opens every font file on the system — tens of milliseconds on a
186    /// Mac's 1300 faces — so it is not a per-frame call. Sessions made after
187    /// it start from the new scan; another
188    /// session that already exists keeps what it has until it calls this
189    /// too.
190    ///
191    /// Faces still installed keep their handles and their place in every
192    /// cache; fonts the app loaded itself (`add_font_data`,
193    /// `load_font_file`, `load_fonts_dir`) are not touched. Every window
194    /// of the session shapes its text again on its next frame, since
195    /// fallback can land on a new face anywhere; this window is asked for
196    /// that frame, and each window's next frame reports a `fonts` event to
197    /// the host, for an app that keeps the font list in its model. A face
198    /// whose file was replaced in place, under the same
199    /// path, is not read again.
200    pub fn reload_system_fonts(&mut self) -> usize {
201        let fresh = crate::text::rescan_system_fonts();
202        let changed = self.session.state().apply_system_fonts(fresh);
203        if changed > 0 {
204            self.sync_font_names();
205            self.request_frame();
206        }
207        changed
208    }
209
210    /// The handle for a font family by name (`"Menlo"`, `"Antonio"`) —
211    /// installed on the system or loaded with `load_fonts_dir` /
212    /// `load_font_file`; `None` when no face matches (see
213    /// `system_font_families`). Idempotent: the same family gets the same
214    /// handle, so views can call it every frame.
215    pub fn add_system_font(&mut self, name: &str) -> Option<crate::resources::FontId> {
216        let id = self.session.register_family(name)?;
217        self.sync_font_names();
218        Some(id)
219    }
220
221    /// The families asked, in order, for a character the text's own
222    /// family has no glyph for — before the platform's fallback list,
223    /// whose first choice is the system's interface face: proportional on
224    /// macOS, so a Cyrillic word in a Latin-only monospaced family was
225    /// set in San Francisco. An editor names its icon face, the face it
226    /// ships and a monospaced one the machine has; a family that has not
227    /// got the character is passed over, and after the last the
228    /// platform's list runs as before. For every family and every kind of
229    /// text in the session — plain, spans, an editor, a cell grid — and
230    /// kept across `reload_system_fonts`. A handle that names no font is
231    /// left out; an empty list is the platform's alone.
232    ///
233    /// Not a per-frame call for a list that changes: a new list builds
234    /// the font system again over the same faces and every window of the
235    /// session shapes its text again. The same list twice is nothing.
236    pub fn set_fallback_fonts(&mut self, fonts: &[crate::resources::FontId]) {
237        {
238            let sess = &mut *self.session.state();
239            let names: Vec<String> = fonts
240                .iter()
241                .filter_map(|&id| sess.resources.font_family(id).map(str::to_string))
242                .collect();
243            if names == sess.resources.fallback {
244                return;
245            }
246            sess.resources.fallback = names;
247            let old = std::mem::replace(
248                &mut sess.fonts,
249                cosmic_text::FontSystem::new_with_locale_and_db(String::new(), Default::default()),
250            );
251            let (locale, db) = old.into_locale_and_db();
252            sess.fonts = crate::text::font_system_over(locale, db, &sess.resources.fallback);
253            if sess.faces_shared {
254                share_faces(sess.fonts.db_mut());
255            }
256            sess.weights_rev += 1;
257        }
258        self.request_frame();
259    }
260
261    /// The families `set_fallback_fonts` named, in order.
262    pub fn fallback_fonts(&self) -> Vec<String> {
263        self.session.state().resources.fallback.clone()
264    }
265
266    /// Forgets a registered font; faces loaded from bytes leave the font
267    /// database. Styles still naming it shape as sans-serif.
268    pub fn remove_font(&mut self, id: crate::resources::FontId) {
269        {
270            let sess = &mut *self.session.state();
271            let Some(entry) = sess.resources.remove_font(id) else {
272                return;
273            };
274            sess.fonts_rev += 1;
275            let db = sess.fonts.db_mut();
276            let touched = families_of(db, &entry.faces);
277            for face in entry.faces {
278                db.remove_face(face);
279            }
280            if sess.resources.reweigh(sess.fonts.db(), &touched, None) {
281                sess.weights_rev += 1;
282            }
283        }
284        self.sync_font_names();
285    }
286
287    /// The registered family name behind a font handle, if it is live.
288    /// Read from this window's mirror of the session's fonts (see
289    /// `session`'s module doc), which every registration refreshes and so
290    /// does every frame — a font another window registered mid-frame shows
291    /// up here on the next one.
292    pub fn font_family(&self, id: crate::resources::FontId) -> Option<&str> {
293        self.font_names.get(&id).map(|s| &**s)
294    }
295
296    /// Family names of every installed font the core can see (sorted,
297    /// deduplicated) — what `add_system_font` accepts. The names of
298    /// [`system_fonts`](Self::system_fonts), which says what each is.
299    pub fn system_font_families(&self) -> Vec<String> {
300        self.system_fonts().into_iter().map(|f| f.family).collect()
301    }
302
303    /// Every family the core can see, installed or loaded, one per family
304    /// and sorted by name — the families `system_font_families` names —
305    /// with what its faces say they are: monospaced, the weights, an
306    /// italic. Read from what the font database recorded
307    /// when it scanned each face, so a fonts pane showing the monospaced
308    /// ones first costs no file loaded and no glyph shaped. A face whose
309    /// glyphs cannot be measured never entered the database,
310    /// so a family of only such faces — macOS's GB18030 Bitmap — is not
311    /// listed.
312    pub fn system_fonts(&self) -> Vec<crate::resources::SystemFont> {
313        use crate::resources::SystemFont;
314        use cosmic_text::fontdb::Style;
315        let sess = self.session.state();
316        let mut by_family = std::collections::BTreeMap::<&str, SystemFont>::new();
317        for face in sess.fonts.db().faces() {
318            let Some((name, _)) = face.families.first() else {
319                continue;
320            };
321            let font = by_family.entry(name).or_insert_with(|| SystemFont {
322                family: name.clone(),
323                monospaced: true,
324                weights: Vec::new(),
325                italic: false,
326            });
327            font.monospaced &= face.monospaced;
328            font.italic |= face.style != Style::Normal;
329            font.weights.push(face.weight.0);
330        }
331        by_family
332            .into_values()
333            .map(|mut font| {
334                font.weights.sort_unstable();
335                font.weights.dedup();
336                font
337            })
338            .collect()
339    }
340
341    /// The installed families `FontFamily::Sans`, `Serif` and `Mono` shape
342    /// with, in that order — pinned per platform when the session's font
343    /// database was built, so the devtools can say which face
344    /// "mono" is on this machine.
345    pub(crate) fn default_font_families(&self) -> [String; 3] {
346        crate::text::default_families(&self.session.state().fonts).map(str::to_string)
347    }
348
349    // -- Audio ----------------------------------------------------------
350    // Sounds are resources, playback is commands the driver drains; see
351    // `audio`. Nothing here touches a device.
352
353    /// Registers a sound from its encoded file bytes (wav/ogg/mp3/flac —
354    /// the driver's backend decodes; the core only keeps the bytes).
355    pub fn add_sound(&mut self, bytes: Vec<u8>) -> crate::resources::SoundId {
356        self.session.state().resources.add_sound(bytes)
357    }
358
359    /// Forgets a sound; the driver drops its decoded copy. Playbacks
360    /// already running keep going.
361    pub fn remove_sound(&mut self, id: crate::resources::SoundId) {
362        let sess = &mut *self.session.state();
363        if sess.resources.remove_sound(id).is_some() {
364            sess.audio.unload(id);
365        }
366    }
367
368    /// Starts a playback; the returned id addresses it in `stop` /
369    /// `set_volume` / `pause` / `resume`. With a tag in the options, the
370    /// playback finishing on its own comes back as
371    /// `{kind="sound", phase="ended", playback, tag}` on the current
372    /// origin's root — the host's, or the extension's during its view.
373    pub fn play(
374        &mut self,
375        sound: crate::resources::SoundId,
376        opts: crate::audio::PlayOptions,
377    ) -> crate::audio::PlaybackId {
378        let origin = self.origin;
379        let window = self.env.window.id;
380        let sess = &mut *self.session.state();
381        // The driver's backend resolves the handle when it plays; a
382        // headless app has no driver, so a foreign handle is noticed here.
383        let _ = sess.resources.sound(sound);
384        sess.audio.play(origin, window, Key::ROOT, sound, opts)
385    }
386
387    /// Stops a playback, fading over `fade_ms` (0 = at once). A stopped
388    /// playback never reports `ended`.
389    pub fn stop(&mut self, playback: crate::audio::PlaybackId, fade_ms: f32) {
390        self.session.state().audio.stop(playback, fade_ms);
391    }
392
393    /// Sets a playback's volume (linear amplitude), tweening over `tween_ms`.
394    pub fn set_volume(&mut self, playback: crate::audio::PlaybackId, volume: f32, tween_ms: f32) {
395        self.session
396            .state()
397            .audio
398            .set_volume(playback, volume, tween_ms);
399    }
400
401    pub fn pause(&mut self, playback: crate::audio::PlaybackId, fade_ms: f32) {
402        self.session.state().audio.pause(playback, fade_ms);
403    }
404
405    pub fn resume(&mut self, playback: crate::audio::PlaybackId, fade_ms: f32) {
406        self.session.state().audio.resume(playback, fade_ms);
407    }
408
409    /// Sets the master volume (linear amplitude), tweening over `tween_ms`.
410    pub fn set_master_volume(&mut self, volume: f32, tween_ms: f32) {
411        self.session.state().audio.master_volume(volume, tween_ms);
412    }
413
414    /// An `audio` node: a playback retained by key for as long as the view
415    /// keeps declaring it — present means playing (once, or looped),
416    /// gone means stopped; `volume` / `paused` changes apply live, a
417    /// changed `src` restarts. The key is auto-assigned from the tree
418    /// position; see `audio_node_keyed` for a stable label. Draws nothing
419    /// and takes no layout space. The mount is this window's: it is
420    /// reconciled against this window's frames, and another window's
421    /// frame declaring nothing leaves it playing.
422    pub fn audio_node(&mut self, spec: crate::audio::AudioSpec) -> Key {
423        if self.tree.is_empty() {
424            return Key::ROOT;
425        }
426        let key = self.auto_key();
427        self.declare_audio(key, spec);
428        key
429    }
430
431    /// `audio_node` with a label-derived key (stable across reorders).
432    pub fn audio_node_keyed(&mut self, label: &str, spec: crate::audio::AudioSpec) -> Key {
433        if self.tree.is_empty() {
434            return Key::ROOT;
435        }
436        let key = self.child_key(label);
437        self.declare_audio(key, spec);
438        key
439    }
440
441    fn declare_audio(&mut self, key: Key, spec: crate::audio::AudioSpec) {
442        let origin = self.origin;
443        let window = self.env.window.id;
444        let sess = &mut *self.session.state();
445        let _ = sess.resources.sound(spec.src);
446        sess.audio.declare(window, key, origin, spec);
447    }
448
449    /// The playback an `audio` node of this window holds, if it is
450    /// mounted — after the frame that declared it has finished.
451    pub fn playback_of(&self, key: Key) -> Option<crate::audio::PlaybackId> {
452        self.audio.playback_of(self.env.window.id, key)
453    }
454
455    /// Drains the audio commands queued since the last drain. Frame
456    /// drivers apply them to a real device after each input dispatch and
457    /// after each frame; headless drivers may simply never call.
458    pub fn take_audio_commands(&mut self) -> Vec<crate::audio::AudioCommand> {
459        self.audio.take_commands()
460    }
461
462    /// The driver reports a playback finished on its own (not stopped).
463    /// A tagged playback becomes an `ended` event, pending like a `resize`
464    /// (see `take_pending_events`).
465    pub fn audio_ended(&mut self, playback: crate::audio::PlaybackId) {
466        let ended = self.session.state().audio.ended(playback);
467        if let Some(ev) = ended {
468            self.pending.push(ev);
469        }
470    }
471
472    /// The driver reports it stopped a playback that was still running,
473    /// `at` seconds into the sound. When that stop was a one-shot `audio`
474    /// node going away (or changing its `src`) without
475    /// [`finish`](crate::audio::AudioSpec::finish), the node is named in a
476    /// [`TRUNCATED_PLAYBACK`](crate::diag::TRUNCATED_PLAYBACK) warning;
477    /// anything else — a stop that landed after the sound ended, an
478    /// imperative [`Self::stop`], a loop, a released playback — reports
479    /// nothing. The driver stays key-blind, as [`Self::audio_ended`] is.
480    pub fn audio_truncated(&mut self, playback: crate::audio::PlaybackId, at: f64) {
481        let cut = self.session.state().audio.truncated(playback);
482        if let Some((key, why)) = cut {
483            self.diag
484                .raise(crate::diag::truncated_playback(key, why, at));
485        }
486    }
487
488    /// The driver refused a play: the device's voices are all held, or
489    /// the sound failed to decode. The playback never started, so it can
490    /// never report `ended` — a tagged one gets
491    /// `{kind="sound", phase="refused", playback, tag}` instead, pending
492    /// like an `ended` is, so a view waiting on the sound is unstuck and
493    /// can tell the two apart. [`crate::diag::PLAYBACK_REFUSED`] is raised
494    /// on the node that asked either way, behind the usual diagnostics
495    /// gate, so an untagged refusal is not silent.
496    pub fn audio_refused(&mut self, playback: crate::audio::PlaybackId) {
497        let (event, warning) = self.session.state().audio.refused(playback);
498        if let Some(ev) = event {
499            self.pending.push(ev);
500        }
501        self.warn(warning);
502    }
503
504    /// Drops what this window shaped when a registered family's weights
505    /// changed since it last looked: text shaped with a bold
506    /// synthesized for a family that has since gained its Bold, or at a
507    /// face since removed, would otherwise stay as it was until evicted.
508    /// Shaped text and cell tables shape again on their next draw; an
509    /// editor keeps its text and takes the new weights. Rare — a face of
510    /// a family already registered coming or going — so dropping every
511    /// family's text is cheaper than knowing which.
512    pub(crate) fn sync_weights(&mut self) {
513        let sess = self.session.state();
514        if sess.weights_rev == self.weights_rev {
515            return;
516        }
517        self.weights_rev = sess.weights_rev;
518        self.text.forget_shaped();
519        self.cells.forget_shaped();
520        self.edit.reweigh(&sess.resources);
521    }
522
523    /// Re-reads the session's font family names into the mirror
524    /// `font_family` lends from, when a registration has moved since.
525    pub(crate) fn sync_font_names(&mut self) {
526        let sess = self.session.state();
527        if sess.fonts_rev == self.fonts_rev {
528            return;
529        }
530        self.fonts_rev = sess.fonts_rev;
531        self.font_names.clear();
532        for (id, entry) in sess.resources.fonts.iter() {
533            self.font_names.insert(id, entry.family.as_str().into());
534        }
535    }
536
537    /// Replaces an image's pixels in place; see `Resources::update_image`.
538    /// If the image had been drawn from the atlas
539    /// its slot is forgotten — one eviction, once — and from here on it is
540    /// texture-backed. A foreign or removed handle warns and changes
541    /// nothing, and so does a buffer that is not `width × height × 4`
542    /// bytes; the return says whether the pixels were taken.
543    pub fn update_image(
544        &mut self,
545        id: crate::resources::ImageId,
546        width: u32,
547        height: u32,
548        rgba: Vec<u8>,
549    ) -> bool {
550        let taken = self
551            .session
552            .state()
553            .resources
554            .update_image(id, width, height, rgba);
555        if taken {
556            self.atlas.evict_image(id);
557        }
558        taken
559    }
560
561    /// Replaces an image's pixels by writing them into a buffer the core
562    /// recycles; see `Resources::update_image_with`. `fill` gets
563    /// `width × height × 4` bytes holding an earlier frame's pixels and
564    /// writes every one. Where [`Self::update_image`] takes a buffer the
565    /// app allocated — and frees the one it replaces — this one stops
566    /// allocating after a stream's third update, which on Windows is most
567    /// of what a 1080p update cost. Render into `fill`'s
568    /// slice rather than into a buffer of your own to skip the copy too.
569    /// `fill` runs while the session's resources are borrowed, so it must
570    /// not reach them through another window's `Core`; that panics.
571    pub fn update_image_with(
572        &mut self,
573        id: crate::resources::ImageId,
574        width: u32,
575        height: u32,
576        fill: impl FnOnce(&mut [u8]),
577    ) -> bool {
578        let taken = self
579            .session
580            .state()
581            .resources
582            .update_image_with(id, width, height, fill);
583        if taken {
584            self.atlas.evict_image(id);
585        }
586        taken
587    }
588
589    /// The pixels behind an image handle — its size and a shared handle on
590    /// the bytes — for a host that renders the display list itself and
591    /// meets a `QuadKind::Texture` quad. `None` for a dead or foreign
592    /// handle, which is also noted as a miss.
593    pub fn image_pixels(
594        &self,
595        id: crate::resources::ImageId,
596    ) -> Option<(u32, u32, std::sync::Arc<Vec<u8>>)> {
597        // A path's own texture is this core's, not the registry's: the
598        // handle a `Texture` quad names is answered either way.
599        if let Some(px) = self.path_textures.pixels(id) {
600            return Some(px);
601        }
602        let sess = self.session.state();
603        sess.resources
604            .image(id)
605            .map(|e| (e.width, e.height, e.rgba.clone()))
606    }
607
608    /// Unregisters an image and forgets its atlas slot — every other
609    /// window's atlas forgets its own at that window's next frame — or,
610    /// for a texture-backed one, has the next display list any window
611    /// builds tell the backend to drop the texture.
612    pub fn remove_image(&mut self, id: crate::resources::ImageId) {
613        self.session.state().remove_image(id);
614        self.atlas.evict_image(id);
615    }
616
617    /// What the session removed and no display list has carried yet,
618    /// onto this frame's — a backend frees a texture or a pipeline
619    /// once, on whichever window draws next, since both are the device's
620    /// and the device is shared. And this window's own atlas slots for
621    /// images the registry no longer holds, when a removal has moved the
622    /// revision since this core last looked: the atlas is per window, so
623    /// the removing core's eviction reached only its own.
624    /// How many `path` masks this core draws from textures of their own
625    /// rather than the atlas — too big for a page, or animating (ADR
626    /// 0040, decisions 7 and 8). For a test of which road a path took.
627    pub fn path_texture_count(&self) -> usize {
628        self.path_textures.len()
629    }
630
631    pub(crate) fn sync_dropped(&mut self) {
632        // A path's own texture the last frame did not draw goes with the
633        // removed images (ADR 0040, decisions 7 and 8).
634        self.display
635            .dropped_textures
636            .extend(self.path_textures.sweep(self.frame_no));
637        let mut sess = self.session.state();
638        self.display
639            .dropped_textures
640            .append(&mut sess.dropped.images);
641        self.display
642            .dropped_fragments
643            .append(&mut sess.dropped.fragments);
644        if sess.images_rev != self.images_rev {
645            self.images_rev = sess.images_rev;
646            let live = &sess.resources.images;
647            self.atlas.retain_images(|id| live.contains_key(id));
648        }
649    }
650}
651
652/// Every family name the faces `ids` answer to, for
653/// [`Resources::reweigh`](crate::resources::Resources::reweigh).
654fn families_of(
655    db: &cosmic_text::fontdb::Database,
656    ids: &[cosmic_text::fontdb::ID],
657) -> rustc_hash::FxHashSet<String> {
658    ids.iter()
659        .filter_map(|&id| db.face(id))
660        .flat_map(|face| face.families.iter().map(|(name, _)| name.clone()))
661        .collect()
662}
663
664impl crate::session::Session {
665    /// `Core::add_system_font`'s registration, on the session every window
666    /// shares: a query against the font database's scan and an idempotent
667    /// registry entry, with no file opened. Here rather than on `Core` so
668    /// a binding's prop parser, which holds the token lookup's borrow of
669    /// the core, can name a family while it parses.
670    pub(crate) fn register_family(&self, name: &str) -> Option<crate::resources::FontId> {
671        use cosmic_text::fontdb::{Family, Query};
672        let sess = &mut *self.state();
673        sess.share_faces_once();
674        let db = sess.fonts.db();
675        let query = Query {
676            families: &[Family::Name(name)],
677            ..Default::default()
678        };
679        let id = db.query(&query)?;
680        // The canonical spelling, so the style matches the way fontdb does.
681        let family = db.face(id)?.families.first()?.0.clone();
682        if let Some((id, _)) = sess
683            .resources
684            .fonts
685            .iter()
686            .find(|(_, f)| f.faces.is_empty() && f.family == family)
687        {
688            return Some(id);
689        }
690        sess.fonts_rev += 1;
691        let touched = std::iter::once(family.clone()).collect();
692        let id = sess.resources.add_font(family, Vec::new());
693        if sess.resources.reweigh(sess.fonts.db(), &touched, Some(id)) {
694            sess.weights_rev += 1;
695        }
696        Some(id)
697    }
698}
699
700impl crate::session::SessionState {
701    /// [`share_faces`], the first time an app names a family, unless a
702    /// load has shared them already, and never again.
703    pub(crate) fn share_faces_once(&mut self) {
704        if !self.faces_shared {
705            self.share_loaded_faces();
706        }
707    }
708
709    /// [`share_faces`] after a load, so the faces it added are shared with
710    /// the rest. Sharing before the load, as DX24 first did,
711    /// left every face a file brought in reading its file again each time
712    /// a text shaped in a new family, weight or style: kawoosh loads 167
713    /// files it ships, and each new family cost a frame ~5 ms in opens.
714    /// The walk maps only what is unshared, so a load after the first
715    /// maps its own faces and nothing else. Not for `register_family`,
716    /// which runs every frame a view names a family: `db_mut` empties
717    /// cosmic-text's match cache.
718    pub(crate) fn share_loaded_faces(&mut self) {
719        self.faces_shared = true;
720        share_faces(self.fonts.db_mut());
721    }
722
723    /// `Core::reload_system_fonts`' half on the session: the faces the
724    /// scan this session holds had and `fresh` has not leave the database,
725    /// those `fresh` has and it had not are loaded, and the rest stay
726    /// where they are, handles and all — a new database would hand out
727    /// fresh ids, and every window's atlas, raster axes and shaped text
728    /// key glyphs by id. Returns how many faces came and went.
729    pub(crate) fn apply_system_fonts(
730        &mut self,
731        fresh: std::sync::Arc<crate::text::SystemFonts>,
732    ) -> usize {
733        use cosmic_text::fontdb::{ID, Source};
734        let old = std::mem::replace(&mut self.system, fresh.clone());
735        let gone: rustc_hash::FxHashSet<_> = old.faces.difference(&fresh.faces).collect();
736        let came: Vec<_> = fresh.faces.difference(&old.faces).collect();
737        if gone.is_empty() && came.is_empty() {
738            return 0;
739        }
740        let db = self.fonts.db_mut();
741        let leaving: Vec<ID> = db
742            .faces()
743            .filter(|face| crate::text::face_file(face).is_some_and(|key| gone.contains(&key)))
744            .map(|face| face.id)
745            .collect();
746        let mut touched = families_of(db, &leaving);
747        for &id in &leaving {
748            db.remove_face(id);
749        }
750        // What came, a file at a time: fontdb loads every face of a file,
751        // and only the ones the scan kept (measurable, and not already
752        // here through a sibling that stayed) are wanted.
753        let mut by_file = rustc_hash::FxHashMap::<&std::path::Path, Vec<u32>>::default();
754        for (path, index) in &came {
755            by_file.entry(path.as_path()).or_default().push(*index);
756        }
757        let mut arrived = Vec::new();
758        for (path, indices) in by_file {
759            for id in db.load_font_source(Source::File(path.to_path_buf())) {
760                let wanted = db
761                    .face(id)
762                    .is_some_and(|face| indices.contains(&face.index));
763                if wanted {
764                    arrived.push(id);
765                } else {
766                    db.remove_face(id);
767                }
768            }
769        }
770        touched.extend(families_of(db, &arrived));
771        crate::text::pin_default_families(db);
772        // cosmic-text works out its monospaced faces, and which scripts
773        // each covers, when the font system is built; rebuilt over the
774        // same database, the ids stay and the lists are new.
775        let fonts = std::mem::replace(
776            &mut self.fonts,
777            cosmic_text::FontSystem::new_with_locale_and_db(String::new(), Default::default()),
778        );
779        let (locale, db) = fonts.into_locale_and_db();
780        self.fonts = crate::text::font_system_over(locale, db, &self.resources.fallback);
781        if self.faces_shared {
782            share_faces(self.fonts.db_mut());
783        }
784        self.resources.reweigh(self.fonts.db(), &touched, None);
785        // Every window shapes again, whatever reweigh found: a family no
786        // one registered can still be what fallback picks.
787        self.fonts_rev += 1;
788        self.weights_rev += 1;
789        self.system_fonts_rev += 1;
790        leaving.len() + arrived.len()
791    }
792}
793
794/// Maps every file-backed face in the database once and shares the
795/// mapping, as cosmic-text does for each face it loads.
796///
797/// The first time a text shapes in a family (a weight, a style) it has not
798/// shaped in, cosmic-text ranks every face in the database against it, and
799/// for each face of another weight it reads that face's `wght` axis — with
800/// the face unshared, opening and mapping its file for that one read. On a
801/// Mac's 1,311 faces that was 9.7 ms a new family, in release; kawoosh's
802/// fonts pane, drawing each of 613 families in itself, warmed them ahead of
803/// time to keep it off the frames. Shared, the read is a slice of a mapping
804/// already made: 0.42 ms a family, for 30 ms once. Done on the first font
805/// an app registers — a family by name, bytes, a file or a folder — where
806/// the per-family cost starts to add up, and after every load from then on
807/// so a loaded file's own faces are shared too; an app on the stock
808/// three pays what it always did.
809///
810/// The mapping is what fontdb's `make_shared_face_data` documents as
811/// unsafe: a font file another process rewrites while it is mapped can
812/// show the change, and may crash the read. cosmic-text already takes that
813/// risk for every face it shapes with; this takes it for every installed
814/// face, which on a desktop are the system's and the user's fonts.
815pub(crate) fn share_faces(db: &mut cosmic_text::fontdb::Database) -> usize {
816    use cosmic_text::fontdb::Source;
817    let ids: Vec<_> = db
818        .faces()
819        .filter(|f| matches!(f.source, Source::File(_)))
820        .map(|f| f.id)
821        .collect();
822    let mut shared = 0;
823    for id in ids {
824        // A face whose file was shared through a sibling face is skipped by
825        // fontdb itself: `make_shared_face_data` updates every face of the
826        // file at once and answers the existing mapping after that.
827        // SAFETY: see the function's doc — the mapping cosmic-text makes
828        // for every face it loads, made for the rest.
829        if unsafe { db.make_shared_face_data(id) }.is_some() {
830            shared += 1;
831        }
832    }
833    shared
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839
840    /// The atlas's kept page lives for the frame it was kept for and no
841    /// longer: `finish` drops it, where the next `begin_frame` did — on a
842    /// window that goes idle after emptying a 4096 page, never.
843    #[test]
844    fn the_emptied_atlas_page_is_dropped_when_its_frame_finishes() {
845        let frame = |core: &mut Core| {
846            let mut ui = core.frame(crate::Size::new(200.0, 100.0), 1.0);
847            ui.text("kept for a frame", crate::TextStyle::new(14.0));
848            ui.finish();
849        };
850        let mut core = Core::new();
851        frame(&mut core);
852        core.atlas.reset_next_frame();
853        core.begin_frame(crate::Size::new(200.0, 100.0), 1.0);
854        assert!(
855            core.atlas.keeps_prev(),
856            "the frame that emptied it keeps it"
857        );
858        core.finish_frame();
859        assert!(!core.atlas.keeps_prev());
860    }
861
862    /// `reload_system_fonts`' session half, against a scan made up for
863    /// the test (installing a font on the machine running it is not the
864    /// test's to do): the session's own scan less one installed face, plus
865    /// a font file written for it. The new face is found by name, the
866    /// gone one is gone, one that stayed keeps its id, every window is
867    /// told to shape again and hears one `fonts` event, and the same scan
868    /// a second time changes nothing.
869    #[test]
870    fn a_rescan_brings_in_what_came_drops_what_went_and_keeps_the_rest() {
871        use crate::text::{SystemFonts, face_file};
872        let mut core = Core::new();
873        let held = core.session.state().system.clone();
874        let dir = std::env::temp_dir().join(format!("kui-rescan-{}", std::process::id()));
875        std::fs::create_dir_all(&dir).unwrap();
876        let installed = dir.join("rescan.ttf");
877        std::fs::write(
878            &installed,
879            crate::testing::font_face("Kui Rescan Face", 400, false, false),
880        )
881        .unwrap();
882
883        // A file's face is uninstalled whole: one index of a file can be
884        // several faces (Ubuntu's variable `Ubuntu[wdth,wght].ttf` is two
885        // at index 0), and a scan keys on the file, so removing one id
886        // would leave the file installed. The face that stays is another
887        // file's.
888        let mut db = held.db().clone();
889        let uninstalled = db.faces().find_map(face_file);
890        let leaving: Vec<_> = db
891            .faces()
892            .filter(|f| uninstalled.is_some() && face_file(f) == uninstalled)
893            .map(|f| f.id)
894            .collect();
895        let stays = db
896            .faces()
897            .filter_map(|f| Some((f.id, face_file(f)?)))
898            .find(|(_, key)| Some(key) != uninstalled.as_ref());
899        for &id in &leaving {
900            db.remove_face(id);
901        }
902        db.load_font_file(&installed).unwrap();
903        let fresh = std::sync::Arc::new(SystemFonts::from_db(held.locale().into(), db));
904
905        let framed = |core: &mut Core| {
906            core.frame(crate::Size::new(100.0, 100.0), 1.0).finish();
907            let evs = core.take_pending_events();
908            evs.iter()
909                .filter_map(|e| e.kind().map(str::to_owned))
910                .collect::<Vec<_>>()
911        };
912        let mut other = Core::new_in(&core.session);
913        assert!(
914            framed(&mut core).is_empty(),
915            "the first frame establishes the set"
916        );
917        assert!(framed(&mut other).is_empty());
918        let face_of = |core: &Core, key: &(std::path::PathBuf, u32)| {
919            let sess = core.session.state();
920            sess.fonts
921                .db()
922                .faces()
923                .find(|f| face_file(f).as_ref() == Some(key))
924                .map(|f| f.id)
925        };
926        let weights = core.session.state().weights_rev;
927        let changed = core.session.state().apply_system_fonts(fresh.clone());
928        assert_eq!(changed, 1 + leaving.len());
929        assert!(
930            core.session.state().weights_rev > weights,
931            "every window shapes again"
932        );
933        assert!(
934            core.add_system_font("Kui Rescan Face").is_some(),
935            "the installed face is found"
936        );
937        if let Some(key) = &uninstalled {
938            assert_eq!(face_of(&core, key), None, "the uninstalled face is gone");
939        }
940        if let Some((id, key)) = &stays {
941            assert_eq!(
942                face_of(&core, key),
943                Some(*id),
944                "a face that stayed keeps its id"
945            );
946        }
947        assert_eq!(framed(&mut core), ["fonts"], "one event, on the root");
948        assert_eq!(
949            framed(&mut other),
950            ["fonts"],
951            "and one in every window of the session"
952        );
953        assert!(framed(&mut core).is_empty(), "once");
954        assert_eq!(core.session.state().apply_system_fonts(fresh), 0);
955        assert!(
956            framed(&mut core).is_empty(),
957            "a scan that found nothing new is no event"
958        );
959        let _ = std::fs::remove_dir_all(&dir);
960    }
961
962    /// The real rescan: with nothing installed or removed since the
963    /// session's scan, nothing changes and no frame is asked for — and a
964    /// session made after it starts from it.
965    #[test]
966    fn a_rescan_of_an_unchanged_system_changes_nothing() {
967        let mut core = Core::new();
968        core.frame(crate::Size::new(100.0, 100.0), 1.0).finish();
969        core.take_pending_events();
970        assert_eq!(core.reload_system_fonts(), 0);
971        // Nor does a font the app loads itself raise a `fonts` event.
972        core.add_font_data(crate::testing::font_face(
973            "Kui Rescan App",
974            400,
975            false,
976            false,
977        ))
978        .expect("the app's own font loads");
979        core.frame(crate::Size::new(100.0, 100.0), 1.0).finish();
980        assert!(
981            !core
982                .take_pending_events()
983                .iter()
984                .any(|e| e.kind() == Some("fonts"))
985        );
986        let after = Core::new();
987        assert!(std::sync::Arc::ptr_eq(
988            &after.session.state().system,
989            &core.session.state().system
990        ));
991    }
992
993    /// DX24: naming a family shares the database's file-backed faces, once;
994    /// before it, an app on the stock families has mapped nothing.
995    #[test]
996    fn the_first_named_family_shares_the_faces_once() {
997        use cosmic_text::fontdb::Source;
998        let mut core = Core::new();
999        let file_backed = |core: &Core| {
1000            let sess = core.session.state();
1001            sess.fonts
1002                .db()
1003                .faces()
1004                .filter(|f| matches!(f.source, Source::File(_)))
1005                .count()
1006        };
1007        let before = file_backed(&core);
1008        assert!(!core.session.state().faces_shared);
1009        let name = core.system_fonts().into_iter().map(|f| f.family).next();
1010        let Some(name) = name else {
1011            return; // a machine with no installed fonts has nothing to share
1012        };
1013        core.add_system_font(&name);
1014        assert!(core.session.state().faces_shared);
1015        assert_eq!(
1016            file_backed(&core),
1017            0,
1018            "all {before} file-backed faces shared"
1019        );
1020        // A second name does not walk them again.
1021        assert_eq!(share_faces(core.session.state().fonts.db_mut()), 0);
1022    }
1023
1024    /// DX25: a file loaded by path or in a folder is shared with the rest,
1025    /// its own faces too, whether it is the first font or a later one.
1026    /// Sharing before the load left them reading their file each time a
1027    /// text shaped in a new family.
1028    #[test]
1029    fn a_loaded_file_is_shared_too() {
1030        use cosmic_text::fontdb::Source;
1031        let file_backed = |core: &Core| {
1032            let sess = core.session.state();
1033            sess.fonts
1034                .db()
1035                .faces()
1036                .filter(|f| matches!(f.source, Source::File(_)))
1037                .count()
1038        };
1039        let dir = std::env::temp_dir().join(format!("kui-dx25-{}", std::process::id()));
1040        let (one, two) = (dir.join("one"), dir.join("two"));
1041        for d in [&one, &two] {
1042            std::fs::create_dir_all(d).unwrap();
1043            std::fs::write(d.join("face.ttf"), crate::testing::liga_font()).unwrap();
1044        }
1045
1046        let mut core = Core::new();
1047        core.load_font_file(one.join("face.ttf"))
1048            .expect("the first font");
1049        assert_eq!(file_backed(&core), 0, "the first file's faces shared");
1050        core.load_font_file(two.join("face.ttf"))
1051            .expect("a later font");
1052        assert_eq!(file_backed(&core), 0, "a later file's faces shared");
1053
1054        let mut fresh = Core::new();
1055        assert!(fresh.load_fonts_dir(&one) >= 1);
1056        assert!(fresh.session.state().faces_shared);
1057        assert_eq!(file_backed(&fresh), 0, "a folder's faces shared");
1058        std::fs::remove_dir_all(&dir).ok();
1059    }
1060}