Skip to main content

lgui_core/text/
fonts.rs

1use std::{cell::RefCell, sync::Arc};
2
3#[derive(Clone, Copy)]
4pub(crate) struct FontFamilies(pub &'static [&'static str]);
5
6thread_local! {
7    static FONT_FAMILIES: RefCell<Vec<&'static [&'static str]>> = const { RefCell::new(Vec::new()) };
8}
9
10pub(crate) struct FontFamiliesGuard;
11
12impl Drop for FontFamiliesGuard {
13    fn drop(&mut self) {
14        FONT_FAMILIES.with(|current| {
15            current.borrow_mut().pop();
16        });
17    }
18}
19
20pub(crate) fn install_font_families(families: &'static [&'static str]) -> FontFamiliesGuard {
21    FONT_FAMILIES.with(|current| current.borrow_mut().push(families));
22    FontFamiliesGuard
23}
24
25pub(crate) fn font_families() -> &'static [&'static str] {
26    FONT_FAMILIES.with(|current| current.borrow().last().copied().unwrap_or(&["Segoe UI"]))
27}
28
29#[derive(Clone, Debug)]
30pub struct FontAsset {
31    pub bytes: Arc<Vec<u8>>,
32    pub family_alias: Option<String>,
33}
34
35impl FontAsset {
36    pub fn new(bytes: impl Into<Arc<Vec<u8>>>) -> Self {
37        Self {
38            bytes: bytes.into(),
39            family_alias: None,
40        }
41    }
42
43    pub fn family_alias(mut self, alias: impl Into<String>) -> Self {
44        self.family_alias = Some(alias.into());
45        self
46    }
47}
48
49#[derive(Clone, Default)]
50pub(crate) struct FontAssets(pub Arc<Vec<FontAsset>>);
51
52thread_local! {
53    static FONT_ASSETS: RefCell<Vec<Arc<Vec<FontAsset>>>> = const { RefCell::new(Vec::new()) };
54}
55
56pub(crate) struct FontAssetsGuard;
57
58impl Drop for FontAssetsGuard {
59    fn drop(&mut self) {
60        FONT_ASSETS.with(|current| {
61            current.borrow_mut().pop();
62        });
63    }
64}
65
66pub(crate) fn install_font_assets(assets: Arc<Vec<FontAsset>>) -> FontAssetsGuard {
67    FONT_ASSETS.with(|current| current.borrow_mut().push(assets));
68    FontAssetsGuard
69}
70
71pub(crate) fn font_assets() -> Arc<Vec<FontAsset>> {
72    FONT_ASSETS.with(|current| current.borrow().last().cloned().unwrap_or_default())
73}