Skip to main content

epaint/text/
font_id.rs

1use alloc::sync::Arc;
2
3/// How to select a sized font.
4#[derive(Clone, Debug, PartialEq)]
5#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
6pub struct FontId {
7    /// Height in points.
8    pub size: f32,
9
10    /// What font family to use.
11    pub family: FontFamily,
12    // TODO(emilk): weight (bold), italics, …
13}
14
15impl Default for FontId {
16    #[inline]
17    fn default() -> Self {
18        Self {
19            size: 14.0,
20            family: FontFamily::Proportional,
21        }
22    }
23}
24
25impl FontId {
26    #[inline]
27    pub const fn new(size: f32, family: FontFamily) -> Self {
28        Self { size, family }
29    }
30
31    #[inline]
32    pub const fn proportional(size: f32) -> Self {
33        Self::new(size, FontFamily::Proportional)
34    }
35
36    #[inline]
37    pub const fn monospace(size: f32) -> Self {
38        Self::new(size, FontFamily::Monospace)
39    }
40}
41
42impl core::hash::Hash for FontId {
43    #[inline(always)]
44    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
45        let Self { size, family } = self;
46        emath::OrderedFloat(*size).hash(state);
47        family.hash(state);
48    }
49}
50
51// ----------------------------------------------------------------------------
52
53/// Font of unknown size.
54///
55/// Which style of font: [`Monospace`][`FontFamily::Monospace`], [`Proportional`][`FontFamily::Proportional`],
56/// or by user-chosen name.
57#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
58#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
59pub enum FontFamily {
60    /// A font where some characters are wider than other (e.g. 'w' is wider than 'i').
61    ///
62    /// Proportional fonts are easier to read and should be the preferred choice in most situations.
63    #[default]
64    Proportional,
65
66    /// A font where each character is the same width (`w` is the same width as `i`).
67    ///
68    /// Useful for code snippets, or when you need to align numbers or text.
69    Monospace,
70
71    /// One of the names in [`FontDefinitions::families`](crate::text::FontDefinitions::families).
72    ///
73    /// ```
74    /// # use epaint::FontFamily;
75    /// // User-chosen names:
76    /// FontFamily::Name("arial".into());
77    /// FontFamily::Name("serif".into());
78    /// ```
79    Name(Arc<str>),
80}
81
82impl core::fmt::Display for FontFamily {
83    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
84        match self {
85            Self::Monospace => "Monospace".fmt(f),
86            Self::Proportional => "Proportional".fmt(f),
87            Self::Name(name) => (*name).fmt(f),
88        }
89    }
90}