Skip to main content

iced_runtime/
font.rs

1//! Load and use fonts.
2use crate::core::Pixels;
3use crate::core::font::{Error, Family, Font};
4use crate::futures::futures::channel::oneshot;
5use crate::task::{self, Task};
6
7use std::borrow::Cow;
8use std::fmt;
9
10/// A font action.
11pub enum Action {
12    /// Load a font from its bytes.
13    Load {
14        /// The bytes of the font to load.
15        bytes: Cow<'static, [u8]>,
16        /// The channel to send back the load result.
17        channel: oneshot::Sender<Result<(), Error>>,
18    },
19
20    /// Lists all system font families.
21    List {
22        /// The channel to send back the list result.
23        channel: oneshot::Sender<Result<Vec<Family>, Error>>,
24    },
25
26    /// Sets the new font defaults for the running application.
27    SetDefaults {
28        /// The new default [`Font`].
29        font: Font,
30        /// The new default text size.
31        text_size: Pixels,
32    },
33}
34
35impl fmt::Debug for Action {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Self::Load { .. } => f.write_str("Load"),
39            Self::List { .. } => f.write_str("List"),
40            Self::SetDefaults { font, text_size } => f
41                .debug_struct("SetDefaults")
42                .field("font", font)
43                .field("text_size", text_size)
44                .finish(),
45        }
46    }
47}
48
49/// Load a font from its bytes.
50pub fn load(bytes: impl Into<Cow<'static, [u8]>>) -> Task<Result<(), Error>> {
51    task::oneshot(|channel| {
52        crate::Action::Font(Action::Load {
53            bytes: bytes.into(),
54            channel,
55        })
56    })
57}
58
59/// Lists all the available font families in the system.
60pub fn list() -> Task<Result<Vec<Family>, Error>> {
61    task::oneshot(|channel| crate::Action::Font(Action::List { channel }))
62}
63
64/// Sets a new default [`Font`] and text size for the running application.
65pub fn set_defaults<Message>(font: Font, text_size: impl Into<Pixels>) -> Task<Message> {
66    task::effect(crate::Action::Font(Action::SetDefaults {
67        font,
68        text_size: text_size.into(),
69    }))
70}