Skip to main content

fyrox_ui/font/
loader.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Font loader.
22
23use crate::{
24    core::{reflect::prelude::*, uuid::Uuid, TypeUuidProvider},
25    font::{Font, FontResource},
26};
27use fyrox_resource::{
28    io::ResourceIo,
29    loader::{BoxedImportOptionsLoaderFuture, BoxedLoaderFuture, LoaderPayload, ResourceLoader},
30    manager::ResourceManager,
31    options::{
32        try_get_import_settings, try_get_import_settings_opaque, BaseImportOptions, ImportOptions,
33    },
34    state::LoadError,
35};
36use serde::{Deserialize, Serialize};
37use std::{path::PathBuf, sync::Arc};
38
39fn default_page_size() -> usize {
40    1024
41}
42
43/// Options to control how a font is imported, allowing data to be included beyond
44/// what is stored in the font file.
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Reflect, Eq)]
46pub struct FontImportOptions {
47    /// The size of each page of the atlas where glyphs are copied before they are rendered.
48    /// Each page is a square `page_size` x `page_size` large, and no glyph may be so large
49    /// that it cannot fit in that square or else it will fail to render.
50    #[serde(default = "default_page_size")]
51    pub page_size: usize,
52    /// The bold version of this font.
53    pub bold: Option<FontResource>,
54    /// The italic version of this font.
55    pub italic: Option<FontResource>,
56    /// The bold italic version of this font.
57    pub bold_italic: Option<FontResource>,
58    /// Fallback fonts are used for rendering special characters that do not have glyphs in this
59    /// font.
60    pub fallbacks: Vec<Option<FontResource>>,
61}
62
63impl Default for FontImportOptions {
64    fn default() -> Self {
65        Self {
66            page_size: default_page_size(),
67            bold: None,
68            italic: None,
69            bold_italic: None,
70            fallbacks: Vec::default(),
71        }
72    }
73}
74
75impl ImportOptions for FontImportOptions {}
76
77/// Default implementation for font loading.
78pub struct FontLoader {
79    /// Resource manager to allow fallback font loading.
80    pub resource_manager: ResourceManager,
81    default_import_options: FontImportOptions,
82}
83
84impl FontLoader {
85    /// Create an instance of the font loader using the given resource manager.
86    pub fn new(resource_manager: ResourceManager) -> Self {
87        Self {
88            resource_manager,
89            default_import_options: FontImportOptions::default(),
90        }
91    }
92}
93
94impl ResourceLoader for FontLoader {
95    fn extensions(&self) -> &[&str] {
96        &["ttf", "otf"]
97    }
98
99    fn data_type_uuid(&self) -> Uuid {
100        Font::type_uuid()
101    }
102
103    fn default_import_options(&self) -> Option<Box<dyn BaseImportOptions>> {
104        Some(Box::new(self.default_import_options.clone()))
105    }
106
107    fn try_load_import_settings(
108        &self,
109        resource_path: PathBuf,
110        io: Arc<dyn ResourceIo>,
111    ) -> BoxedImportOptionsLoaderFuture {
112        Box::pin(async move {
113            try_get_import_settings_opaque::<FontImportOptions>(&resource_path, &*io).await
114        })
115    }
116
117    fn load(&self, path: PathBuf, io: Arc<dyn ResourceIo>) -> BoxedLoaderFuture {
118        let default_import_options = self.default_import_options.clone();
119        let resource_manager = self.resource_manager.clone();
120        Box::pin(async move {
121            let io = io.as_ref();
122
123            let import_options = try_get_import_settings(&path, io)
124                .await
125                .unwrap_or(default_import_options);
126
127            let font = Font::from_file(&path, import_options, io, &resource_manager)
128                .await
129                .map_err(LoadError::new)?;
130            Ok(LoaderPayload::new(font))
131        })
132    }
133}