1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// Copyright © SixtyFPS GmbH <info@slint-ui.com>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial

use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::RefCell;

#[cfg(all(not(feature = "std"), feature = "unsafe-single-threaded"))]
use crate::thread_local_ as thread_local;

use super::{PhysicalLength, PhysicalSize};
use crate::graphics::{BitmapFont, FontRequest};
use crate::lengths::{LogicalLength, LogicalSize, ScaleFactor};
use crate::textlayout::TextLayout;
use crate::Coord;

thread_local! {
    static BITMAP_FONTS: RefCell<Vec<&'static BitmapFont>> = RefCell::default()
}

#[derive(derive_more::From, Clone)]
pub enum GlyphAlphaMap {
    Static(&'static [u8]),
    Shared(Rc<[u8]>),
}

#[derive(Clone)]
pub struct RenderableGlyph {
    pub x: PhysicalLength,
    pub y: PhysicalLength,
    pub width: PhysicalLength,
    pub height: PhysicalLength,
    pub alpha_map: GlyphAlphaMap,
}

impl RenderableGlyph {
    pub fn size(&self) -> PhysicalSize {
        PhysicalSize::from_lengths(self.width, self.height)
    }
}

pub trait GlyphRenderer {
    fn render_glyph(&self, glyph_id: core::num::NonZeroU16) -> RenderableGlyph;
}

pub(super) const DEFAULT_FONT_SIZE: LogicalLength = LogicalLength::new(12 as Coord);

mod pixelfont;
#[cfg(feature = "software-renderer-systemfonts")]
pub mod vectorfont;

#[cfg(feature = "software-renderer-systemfonts")]
pub mod systemfonts;

#[derive(derive_more::From)]
pub enum Font {
    PixelFont(pixelfont::PixelFont),
    #[cfg(feature = "software-renderer-systemfonts")]
    VectorFont(vectorfont::VectorFont),
}

pub fn match_font(request: &FontRequest, scale_factor: ScaleFactor) -> Font {
    let bitmap_font = BITMAP_FONTS.with(|fonts| {
        let fonts = fonts.borrow();

        request.family.as_ref().and_then(|requested_family| {
            fonts
                .iter()
                .find(|bitmap_font| {
                    core::str::from_utf8(bitmap_font.family_name.as_slice()).unwrap()
                        == requested_family.as_str()
                })
                .copied()
        })
    });

    let font = match bitmap_font {
        Some(bitmap_font) => bitmap_font,
        None => {
            #[cfg(feature = "software-renderer-systemfonts")]
            if let Some(vectorfont) = systemfonts::match_font(request, scale_factor) {
                return vectorfont.into();
            }
            if let Some(fallback_bitmap_font) =
                BITMAP_FONTS.with(|fonts| fonts.borrow().first().cloned())
            {
                fallback_bitmap_font
            } else {
                #[cfg(feature = "software-renderer-systemfonts")]
                return systemfonts::fallbackfont(request.pixel_size, scale_factor).into();
                #[cfg(not(feature = "software-renderer-systemfonts"))]
                panic!("No font fallback found. The software renderer requires enabling the `EmbedForSoftwareRenderer` option when compiling slint files.")
            }
        }
    };

    let requested_pixel_size: PhysicalLength =
        (request.pixel_size.unwrap_or(DEFAULT_FONT_SIZE).cast() * scale_factor).cast();

    let nearest_pixel_size = font
        .glyphs
        .partition_point(|glyphs| glyphs.pixel_size() <= requested_pixel_size)
        .saturating_sub(1);

    let matching_glyphs = &font.glyphs[nearest_pixel_size];

    pixelfont::PixelFont { bitmap_font: font, glyphs: matching_glyphs }.into()
}

pub fn text_layout_for_font<'a, Font: crate::textlayout::AbstractFont>(
    font: &'a Font,
    font_request: &FontRequest,
    scale_factor: ScaleFactor,
) -> TextLayout<'a, Font>
where
    Font: crate::textlayout::TextShaper<Length = PhysicalLength>,
{
    let letter_spacing =
        font_request.letter_spacing.map(|spacing| (spacing.cast() * scale_factor).cast());

    TextLayout { font, letter_spacing }
}

pub fn register_bitmap_font(font_data: &'static BitmapFont) {
    BITMAP_FONTS.with(|fonts| fonts.borrow_mut().push(font_data))
}

pub fn text_size(
    font_request: FontRequest,
    text: &str,
    max_width: Option<LogicalLength>,
    scale_factor: ScaleFactor,
) -> LogicalSize {
    let font = match_font(&font_request, scale_factor);
    let (longest_line_width, height) = match font {
        Font::PixelFont(pf) => {
            let layout = text_layout_for_font(&pf, &font_request, scale_factor);
            layout.text_size(
                text,
                max_width.map(|max_width| (max_width.cast() * scale_factor).cast()),
            )
        }
        #[cfg(feature = "software-renderer-systemfonts")]
        Font::VectorFont(vf) => {
            let layout = text_layout_for_font(&vf, &font_request, scale_factor);
            layout.text_size(
                text,
                max_width.map(|max_width| (max_width.cast() * scale_factor).cast()),
            )
        }
    };

    (PhysicalSize::from_lengths(longest_line_width, height).cast() / scale_factor).cast()
}