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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use std::{
    collections::BTreeMap,
    hash::{Hash, Hasher},
    sync::Arc,
};

use crate::mutex::Mutex;

use super::{
    font::{Font, FontImpl},
    texture_atlas::{Texture, TextureAtlas},
};

// TODO: rename
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum TextStyle {
    Small,
    Body,
    Button,
    Heading,
    Monospace,
}

impl TextStyle {
    pub fn all() -> impl Iterator<Item = TextStyle> {
        [
            TextStyle::Small,
            TextStyle::Body,
            TextStyle::Button,
            TextStyle::Heading,
            TextStyle::Monospace,
        ]
        .iter()
        .copied()
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
// #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum FontFamily {
    Monospace,
    VariableWidth,
}

/// The data of a `.ttf` or `.otf` file.
pub type FontData = std::borrow::Cow<'static, [u8]>;

fn rusttype_font_from_font_data(name: &str, data: &FontData) -> rusttype::Font<'static> {
    match data {
        std::borrow::Cow::Borrowed(bytes) => rusttype::Font::try_from_bytes(bytes),
        std::borrow::Cow::Owned(bytes) => rusttype::Font::try_from_vec(bytes.clone()),
    }
    .unwrap_or_else(|| panic!("Error parsing {:?} TTF/OTF font file", name))
}

/// This is how you tell Egui which fonts and font sizes to use.
#[derive(Clone, Debug, PartialEq)]
pub struct FontDefinitions {
    /// The dpi scale factor. Needed to get pixel perfect fonts.
    pub pixels_per_point: f32,

    /// List of font names and their definitions.
    /// The definition must be the contents of either a `.ttf` or `.otf` font file.
    ///
    /// Egui has built-in-default for these,
    /// but you can override them if you like.
    pub font_data: BTreeMap<String, FontData>,

    /// Which fonts (names) to use for each `FontFamily`.
    ///
    /// The list should be a list of keys into `font_data`.
    /// When looking for a character glyph Egui will start with
    /// the first font and then move to the second, and so on.
    /// So the first font is the primary, and then comes a list of fallbacks in order of priority.
    pub fonts_for_family: BTreeMap<FontFamily, Vec<String>>,

    /// The `FontFaily` and size you want to use for a specific `TextStyle`.
    pub family_and_size: BTreeMap<TextStyle, (FontFamily, f32)>,
}

impl Default for FontDefinitions {
    fn default() -> Self {
        Self::default_with_pixels_per_point(f32::NAN) // must be set later
    }
}

impl FontDefinitions {
    /// Default values for the fonts
    pub fn default_with_pixels_per_point(pixels_per_point: f32) -> Self {
        let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();
        // Use size 13 for this. NOTHING ELSE:
        font_data.insert(
            "ProggyClean".to_owned(),
            std::borrow::Cow::Borrowed(include_bytes!("../../fonts/ProggyClean.ttf")),
        );
        font_data.insert(
            "Ubuntu-Light".to_owned(),
            std::borrow::Cow::Borrowed(include_bytes!("../../fonts/Ubuntu-Light.ttf")),
        );

        // Few, but good looking. Use as first priority:
        font_data.insert(
            "NotoEmoji-Regular".to_owned(),
            std::borrow::Cow::Borrowed(include_bytes!("../../fonts/NotoEmoji-Regular.ttf")),
        );
        // Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>:
        font_data.insert(
            "emoji-icon-font".to_owned(),
            std::borrow::Cow::Borrowed(include_bytes!("../../fonts/emoji-icon-font.ttf")),
        );

        // TODO: figure out a way to make the WASM smaller despite including fonts. Zip them?

        let mut fonts_for_family = BTreeMap::new();
        fonts_for_family.insert(
            FontFamily::Monospace,
            vec![
                "ProggyClean".to_owned(),
                "Ubuntu-Light".to_owned(), // fallback for √ etc
                "NotoEmoji-Regular".to_owned(),
                "emoji-icon-font".to_owned(),
            ],
        );
        fonts_for_family.insert(
            FontFamily::VariableWidth,
            vec![
                "Ubuntu-Light".to_owned(),
                "NotoEmoji-Regular".to_owned(),
                "emoji-icon-font".to_owned(),
            ],
        );

        let mut family_and_size = BTreeMap::new();
        family_and_size.insert(TextStyle::Small, (FontFamily::VariableWidth, 10.0));
        family_and_size.insert(TextStyle::Body, (FontFamily::VariableWidth, 14.0));
        family_and_size.insert(TextStyle::Button, (FontFamily::VariableWidth, 16.0));
        family_and_size.insert(TextStyle::Heading, (FontFamily::VariableWidth, 24.0));
        family_and_size.insert(TextStyle::Monospace, (FontFamily::Monospace, 13.0)); // 13 for `ProggyClean`

        Self {
            pixels_per_point,
            font_data,
            fonts_for_family,
            family_and_size,
        }
    }
}

/// Note: the `default()` fonts are invalid (missing `pixels_per_point`).
#[derive(Default)]
pub struct Fonts {
    definitions: FontDefinitions,
    fonts: BTreeMap<TextStyle, Font>,
    atlas: Arc<Mutex<TextureAtlas>>,
    /// Copy of the texture in the texture atlas.
    /// This is so we can return a reference to it (the texture atlas is behind a lock).
    buffered_texture: Mutex<Arc<Texture>>,
}

impl Fonts {
    pub fn from_definitions(definitions: FontDefinitions) -> Fonts {
        let mut fonts = Self::default();
        fonts.set_definitions(definitions);
        fonts
    }

    pub fn definitions(&self) -> &FontDefinitions {
        &self.definitions
    }

    pub fn set_definitions(&mut self, definitions: FontDefinitions) {
        if self.definitions == definitions {
            return;
        }
        self.definitions = definitions;

        // We want an atlas big enough to be able to include all the Emojis in the `TextStyle::Heading`,
        // so we can show the Emoji picker demo window.
        let mut atlas = TextureAtlas::new(2048, 64);

        {
            // Make the top left pixel fully white:
            let pos = atlas.allocate((1, 1));
            assert_eq!(pos, (0, 0));
            atlas.texture_mut()[pos] = 255;
        }

        let atlas = Arc::new(Mutex::new(atlas));

        let mut font_impl_cache = FontImplCache::new(atlas.clone(), &self.definitions);

        self.fonts = self
            .definitions
            .family_and_size
            .iter()
            .map(|(&text_style, &(family, scale_in_points))| {
                let fonts: Vec<Arc<FontImpl>> = self.definitions.fonts_for_family[&family]
                    .iter()
                    .map(|font_name| font_impl_cache.font_impl(font_name, scale_in_points))
                    .collect();

                (text_style, Font::new(fonts))
            })
            .collect();

        {
            let mut atlas = atlas.lock();
            let texture = atlas.texture_mut();
            // Make sure we seed the texture version with something unique based on the default characters:
            use std::collections::hash_map::DefaultHasher;
            let mut hasher = DefaultHasher::default();
            texture.pixels.hash(&mut hasher);
            texture.version = hasher.finish();
        }

        self.buffered_texture = Default::default(); //atlas.lock().texture().clone();
        self.atlas = atlas;
    }

    pub fn texture(&self) -> Arc<Texture> {
        let atlas = self.atlas.lock();
        let mut buffered_texture = self.buffered_texture.lock();
        if buffered_texture.version != atlas.texture().version {
            *buffered_texture = Arc::new(atlas.texture().clone());
        }

        buffered_texture.clone()
    }
}

impl std::ops::Index<TextStyle> for Fonts {
    type Output = Font;

    fn index(&self, text_style: TextStyle) -> &Font {
        &self.fonts[&text_style]
    }
}

// ----------------------------------------------------------------------------

#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FontSource {
    Family(FontFamily),
    /// Emoji fonts are numbered from hight priority (0) and onwards
    Emoji(usize),
}

pub struct FontImplCache {
    atlas: Arc<Mutex<TextureAtlas>>,
    pixels_per_point: f32,
    rusttype_fonts: std::collections::BTreeMap<String, Arc<rusttype::Font<'static>>>,

    /// Map font names and size to the cached `FontImpl`.
    /// Can't have f32 in a HashMap or BTreeMap, so let's do a linear search
    cache: Vec<(String, f32, Arc<FontImpl>)>,
}

impl FontImplCache {
    pub fn new(atlas: Arc<Mutex<TextureAtlas>>, definitions: &super::FontDefinitions) -> Self {
        let rusttype_fonts = definitions
            .font_data
            .iter()
            .map(|(name, font_data)| {
                (
                    name.clone(),
                    Arc::new(rusttype_font_from_font_data(name, font_data)),
                )
            })
            .collect();

        Self {
            atlas,
            pixels_per_point: definitions.pixels_per_point,
            rusttype_fonts,
            cache: Default::default(),
        }
    }

    pub fn rusttype_font(&self, font_name: &str) -> Arc<rusttype::Font<'static>> {
        self.rusttype_fonts
            .get(font_name)
            .unwrap_or_else(|| panic!("No font data found for {:?}", font_name))
            .clone()
    }

    pub fn font_impl(&mut self, font_name: &str, scale_in_points: f32) -> Arc<FontImpl> {
        for entry in &self.cache {
            if (entry.0.as_str(), entry.1) == (font_name, scale_in_points) {
                return entry.2.clone();
            }
        }

        let font_impl = Arc::new(FontImpl::new(
            self.atlas.clone(),
            self.pixels_per_point,
            self.rusttype_font(font_name),
            scale_in_points,
        ));
        self.cache
            .push((font_name.to_owned(), scale_in_points, font_impl.clone()));
        font_impl
    }
}