Skip to content

Commit 7eafcaf

Browse files
committed
Polish slint::register_font_from_memory
- Make `FontHandle` opaque. - Avoid memory allocations - Reword documentation - Avoid indirection to i_slint_core (prevent documentation to be repeated) ammends for #9762
1 parent 428aae8 commit 7eafcaf

File tree

4 files changed

+23
-68
lines changed

4 files changed

+23
-68
lines changed

api/rs/slint/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ i-slint-core = { workspace = true }
259259
slint-macros = { workspace = true }
260260
i-slint-backend-selector = { workspace = true }
261261
i-slint-core-macros = { workspace = true }
262+
i-slint-common = { workspace = true }
262263
slint-interpreter = { workspace = true, optional = true, default-features = false, features = ["display-diagnostics", "compat-1-2", "internal-live-preview"] }
263264

264265
const-field-offset = { version = "0.1.2", path = "../../../helper_crates/const-field-offset" }

api/rs/slint/lib.rs

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ pub use i_slint_core::component_factory::ComponentFactory;
218218
#[cfg(not(target_arch = "wasm32"))]
219219
pub use i_slint_core::graphics::{BorrowedOpenGLTextureBuilder, BorrowedOpenGLTextureOrigin};
220220
// keep in sync with internal/interpreter/api.rs
221+
#[cfg(feature = "std")]
222+
pub use i_slint_common::sharedfontique::{
223+
register_font_from_memory, FontHandle, RegisterFontError,
224+
};
221225
pub use i_slint_core::graphics::{
222226
Brush, Color, Image, LoadImageError, Rgb8Pixel, Rgba8Pixel, RgbaColor, SharedPixelBuffer,
223227
};
@@ -233,39 +237,6 @@ pub use i_slint_core::{
233237
string::{SharedString, ToSharedString},
234238
};
235239

236-
/// Register a custom font from byte data at runtime.
237-
///
238-
/// **This is an experimental API.** The API may change in future versions.
239-
///
240-
/// Returns a [`FontHandle`] on success, or a [`RegisterFontError`] on failure.
241-
///
242-
/// This API is available when the `std` feature is enabled.
243-
///
244-
/// # Example
245-
///
246-
/// ```ignore
247-
/// # use slint::*;
248-
/// let font_data = include_bytes!("path/to/font.ttf");
249-
/// match register_font_from_memory(font_data.to_vec()) {
250-
/// Ok(handle) => println!("Registered {} font families", handle.family_ids.len()),
251-
/// Err(e) => eprintln!("Failed to register font: {}", e),
252-
/// }
253-
/// ```
254-
#[cfg(feature = "std")]
255-
pub use i_slint_core::register_font_from_memory;
256-
257-
/// Handle to a registered font that can be used for future operations.
258-
///
259-
/// **This is an experimental API.** The API may change in future versions.
260-
#[cfg(feature = "std")]
261-
pub use i_slint_core::FontHandle;
262-
263-
/// Error type for font registration failures.
264-
///
265-
/// **This is an experimental API.** The API may change in future versions.
266-
#[cfg(feature = "std")]
267-
pub use i_slint_core::RegisterFontError;
268-
269240
pub mod private_unstable_api;
270241

271242
/// Enters the main event loop. This is necessary in order to receive

internal/common/sharedfontique.rs

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -132,14 +132,17 @@ impl std::ops::DerefMut for Collection {
132132
}
133133

134134
/// Handle to a registered font that can be used for future operations.
135+
///
136+
/// Returned by [`register_font_from_memory()`].
135137
#[derive(Debug, Clone)]
136-
pub struct FontHandle {
137-
/// Family IDs of the registered fonts
138-
pub family_ids: Vec<fontique::FamilyId>,
139-
}
138+
#[non_exhaustive]
139+
pub struct FontHandle {}
140140

141141
/// Error type for font registration failures.
142+
///
143+
/// Returned by [`register_font_from_memory()`].
142144
#[derive(Debug, Clone)]
145+
#[non_exhaustive]
143146
pub enum RegisterFontError {
144147
/// The provided font data was empty
145148
EmptyData,
@@ -165,22 +168,18 @@ impl std::error::Error for RegisterFontError {}
165168

166169
/// Register a font from byte data dynamically.
167170
///
168-
/// # Arguments
169-
///
170-
/// * `font_data` - Font data as bytes (supports any type that can be converted to a byte slice)
171+
/// The argument is the owner of a slice of byte that contains the data of the font.
172+
/// It can for example be a `&'static [u8]` obtained from [`include_bytes!()`] or a `Vec<u8>`
173+
/// obtained from [`std::fs::read()`].
171174
///
172-
/// # Returns
173-
///
174-
/// Returns a `FontHandle` on success, or a `RegisterFontError` on failure.
175+
/// The data must be in the [TrueType (TTF) format](https://en.wikipedia.org/wiki/TrueType).
175176
///
176177
/// # Example
177178
///
178-
/// ```ignore
179-
/// let font_bytes = include_bytes!("my_font.ttf");
180-
/// match register_font_from_memory(font_bytes.to_vec()) {
181-
/// Ok(handle) => println!("Registered {} font families", handle.family_ids.len()),
182-
/// Err(e) => eprintln!("Failed to register font: {}", e),
183-
/// }
179+
/// ```
180+
/// # use i_slint_common::sharedfontique as slint;
181+
/// let font_bytes = include_bytes!("sharedfontique/DejaVuSans.ttf");
182+
/// slint::register_font_from_memory(font_bytes).expect("Failed to register font");
184183
/// ```
185184
pub fn register_font_from_memory(
186185
font_data: impl AsRef<[u8]> + Send + Sync + 'static,
@@ -191,9 +190,7 @@ pub fn register_font_from_memory(
191190
return Err(RegisterFontError::EmptyData);
192191
}
193192

194-
// Convert to owned data for Arc
195-
let owned_data: Vec<u8> = data.to_vec();
196-
let blob = fontique::Blob::new(Arc::new(owned_data));
193+
let blob = fontique::Blob::new(Arc::new(font_data));
197194

198195
let mut collection = get_collection();
199196
let fonts = collection.register_fonts(blob, None);
@@ -202,15 +199,13 @@ pub fn register_font_from_memory(
202199
return Err(RegisterFontError::NoFontsFound);
203200
}
204201

205-
let family_ids: Vec<_> = fonts.iter().map(|(family_id, _)| *family_id).collect();
206-
207202
// Set up fallbacks for all scripts
208203
for script in fontique::Script::all_samples().iter().map(|(script, _)| *script) {
209204
collection
210-
.append_fallbacks(fontique::FallbackKey::new(script, None), family_ids.iter().copied());
205+
.append_fallbacks(fontique::FallbackKey::new(script, None), fonts.iter().map(|x| x.0));
211206
}
212207

213-
Ok(FontHandle { family_ids })
208+
Ok(FontHandle {})
214209
}
215210

216211
/// Font metrics in design space. Scale with desired pixel size and divided by units_per_em

internal/core/lib.rs

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,6 @@ pub mod window;
6262
#[doc(inline)]
6363
pub use string::SharedString;
6464

65-
/// Register a font from memory.
66-
#[cfg(feature = "std")]
67-
pub use i_slint_common::sharedfontique::register_font_from_memory;
68-
69-
/// Handle to a registered font.
70-
#[cfg(feature = "std")]
71-
pub use i_slint_common::sharedfontique::FontHandle;
72-
73-
/// Error type for font registration failures.
74-
#[cfg(feature = "std")]
75-
pub use i_slint_common::sharedfontique::RegisterFontError;
76-
7765
#[doc(inline)]
7866
pub use sharedvector::SharedVector;
7967

0 commit comments

Comments
 (0)