iced_graphics/
text.rs

1//! Draw text.
2pub mod cache;
3pub mod editor;
4pub mod paragraph;
5
6pub use cache::Cache;
7pub use editor::Editor;
8pub use paragraph::Paragraph;
9
10pub use cosmic_text;
11
12use crate::core::alignment;
13use crate::core::font::{self, Font};
14use crate::core::text::{Alignment, Shaping, Wrapping};
15use crate::core::{Color, Pixels, Point, Rectangle, Size, Transformation};
16
17use std::borrow::Cow;
18use std::collections::HashSet;
19use std::sync::{Arc, OnceLock, RwLock, Weak};
20
21/// A text primitive.
22#[derive(Debug, Clone, PartialEq)]
23pub enum Text {
24    /// A paragraph.
25    #[allow(missing_docs)]
26    Paragraph {
27        paragraph: paragraph::Weak,
28        position: Point,
29        color: Color,
30        clip_bounds: Rectangle,
31        transformation: Transformation,
32    },
33    /// An editor.
34    #[allow(missing_docs)]
35    Editor {
36        editor: editor::Weak,
37        position: Point,
38        color: Color,
39        clip_bounds: Rectangle,
40        transformation: Transformation,
41    },
42    /// Some cached text.
43    Cached {
44        /// The contents of the text.
45        content: String,
46        /// The bounds of the text.
47        bounds: Rectangle,
48        /// The color of the text.
49        color: Color,
50        /// The size of the text in logical pixels.
51        size: Pixels,
52        /// The line height of the text.
53        line_height: Pixels,
54        /// The font of the text.
55        font: Font,
56        /// The horizontal alignment of the text.
57        align_x: Alignment,
58        /// The vertical alignment of the text.
59        align_y: alignment::Vertical,
60        /// The shaping strategy of the text.
61        shaping: Shaping,
62        /// The clip bounds of the text.
63        clip_bounds: Rectangle,
64    },
65    /// Some raw text.
66    #[allow(missing_docs)]
67    Raw {
68        raw: Raw,
69        transformation: Transformation,
70    },
71}
72
73impl Text {
74    /// Returns the visible bounds of the [`Text`].
75    pub fn visible_bounds(&self) -> Option<Rectangle> {
76        match self {
77            Text::Paragraph {
78                position,
79                paragraph,
80                clip_bounds,
81                transformation,
82                ..
83            } => Rectangle::new(*position, paragraph.min_bounds)
84                .intersection(clip_bounds)
85                .map(|bounds| bounds * *transformation),
86            Text::Editor {
87                editor,
88                position,
89                clip_bounds,
90                transformation,
91                ..
92            } => Rectangle::new(*position, editor.bounds)
93                .intersection(clip_bounds)
94                .map(|bounds| bounds * *transformation),
95            Text::Cached {
96                bounds,
97                clip_bounds,
98                ..
99            } => bounds.intersection(clip_bounds),
100            Text::Raw { raw, .. } => Some(raw.clip_bounds),
101        }
102    }
103}
104
105/// The regular variant of the [Fira Sans] font.
106///
107/// It is loaded as part of the default fonts when the `fira-sans`
108/// feature is enabled.
109///
110/// [Fira Sans]: https://mozilla.github.io/Fira/
111#[cfg(feature = "fira-sans")]
112pub const FIRA_SANS_REGULAR: &[u8] =
113    include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice();
114
115/// Returns the global [`FontSystem`].
116pub fn font_system() -> &'static RwLock<FontSystem> {
117    static FONT_SYSTEM: OnceLock<RwLock<FontSystem>> = OnceLock::new();
118
119    FONT_SYSTEM.get_or_init(|| {
120        RwLock::new(FontSystem {
121            raw: cosmic_text::FontSystem::new_with_fonts([
122                cosmic_text::fontdb::Source::Binary(Arc::new(
123                    include_bytes!("../fonts/Iced-Icons.ttf").as_slice(),
124                )),
125                #[cfg(feature = "fira-sans")]
126                cosmic_text::fontdb::Source::Binary(Arc::new(
127                    include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(),
128                )),
129            ]),
130            loaded_fonts: HashSet::new(),
131            version: Version::default(),
132        })
133    })
134}
135
136/// A set of system fonts.
137#[allow(missing_debug_implementations)]
138pub struct FontSystem {
139    raw: cosmic_text::FontSystem,
140    loaded_fonts: HashSet<usize>,
141    version: Version,
142}
143
144impl FontSystem {
145    /// Returns the raw [`cosmic_text::FontSystem`].
146    pub fn raw(&mut self) -> &mut cosmic_text::FontSystem {
147        &mut self.raw
148    }
149
150    /// Loads a font from its bytes.
151    pub fn load_font(&mut self, bytes: Cow<'static, [u8]>) {
152        if let Cow::Borrowed(bytes) = bytes {
153            let address = bytes.as_ptr() as usize;
154
155            if !self.loaded_fonts.insert(address) {
156                return;
157            }
158        }
159
160        let _ = self.raw.db_mut().load_font_source(
161            cosmic_text::fontdb::Source::Binary(Arc::new(bytes.into_owned())),
162        );
163
164        self.version = Version(self.version.0 + 1);
165    }
166
167    /// Returns the current [`Version`] of the [`FontSystem`].
168    ///
169    /// Loading a font will increase the version of a [`FontSystem`].
170    pub fn version(&self) -> Version {
171        self.version
172    }
173}
174
175/// A version number.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
177pub struct Version(u32);
178
179/// A weak reference to a [`cosmic-text::Buffer`] that can be drawn.
180#[derive(Debug, Clone)]
181pub struct Raw {
182    /// A weak reference to a [`cosmic_text::Buffer`].
183    pub buffer: Weak<cosmic_text::Buffer>,
184    /// The position of the text.
185    pub position: Point,
186    /// The color of the text.
187    pub color: Color,
188    /// The clip bounds of the text.
189    pub clip_bounds: Rectangle,
190}
191
192impl PartialEq for Raw {
193    fn eq(&self, _other: &Self) -> bool {
194        // TODO: There is no proper way to compare raw buffers
195        // For now, no two instances of `Raw` text will be equal.
196        // This should be fine, but could trigger unnecessary redraws
197        // in the future.
198        false
199    }
200}
201
202/// Measures the dimensions of the given [`cosmic_text::Buffer`].
203pub fn measure(buffer: &cosmic_text::Buffer) -> (Size, bool) {
204    let (width, height, has_rtl) = buffer.layout_runs().fold(
205        (0.0, 0.0, false),
206        |(width, height, has_rtl), run| {
207            (
208                run.line_w.max(width),
209                height + run.line_height,
210                has_rtl || run.rtl,
211            )
212        },
213    );
214
215    (Size::new(width, height), has_rtl)
216}
217
218/// Aligns the given [`cosmic_text::Buffer`] with the given [`Alignment`]
219/// and returns its minimum [`Size`].
220pub fn align(
221    buffer: &mut cosmic_text::Buffer,
222    font_system: &mut cosmic_text::FontSystem,
223    alignment: Alignment,
224) -> Size {
225    let (min_bounds, has_rtl) = measure(buffer);
226    let mut needs_relayout = has_rtl;
227
228    if let Some(align) = to_align(alignment) {
229        let has_multiple_lines = buffer.lines.len() > 1
230            || buffer.lines.first().is_some_and(|line| {
231                line.layout_opt().is_some_and(|layout| layout.len() > 1)
232            });
233
234        if has_multiple_lines {
235            for line in &mut buffer.lines {
236                let _ = line.set_align(Some(align));
237            }
238
239            needs_relayout = true;
240        } else if let Some(line) = buffer.lines.first_mut() {
241            needs_relayout = line.set_align(None);
242        }
243    }
244
245    // TODO: Avoid relayout with some changes to `cosmic-text` (?)
246    if needs_relayout {
247        log::trace!("Relayouting paragraph...");
248
249        buffer.set_size(
250            font_system,
251            Some(min_bounds.width),
252            Some(min_bounds.height),
253        );
254    }
255
256    min_bounds
257}
258
259/// Returns the attributes of the given [`Font`].
260pub fn to_attributes(font: Font) -> cosmic_text::Attrs<'static> {
261    cosmic_text::Attrs::new()
262        .family(to_family(font.family))
263        .weight(to_weight(font.weight))
264        .stretch(to_stretch(font.stretch))
265        .style(to_style(font.style))
266}
267
268fn to_family(family: font::Family) -> cosmic_text::Family<'static> {
269    match family {
270        font::Family::Name(name) => cosmic_text::Family::Name(name),
271        font::Family::SansSerif => cosmic_text::Family::SansSerif,
272        font::Family::Serif => cosmic_text::Family::Serif,
273        font::Family::Cursive => cosmic_text::Family::Cursive,
274        font::Family::Fantasy => cosmic_text::Family::Fantasy,
275        font::Family::Monospace => cosmic_text::Family::Monospace,
276    }
277}
278
279fn to_weight(weight: font::Weight) -> cosmic_text::Weight {
280    match weight {
281        font::Weight::Thin => cosmic_text::Weight::THIN,
282        font::Weight::ExtraLight => cosmic_text::Weight::EXTRA_LIGHT,
283        font::Weight::Light => cosmic_text::Weight::LIGHT,
284        font::Weight::Normal => cosmic_text::Weight::NORMAL,
285        font::Weight::Medium => cosmic_text::Weight::MEDIUM,
286        font::Weight::Semibold => cosmic_text::Weight::SEMIBOLD,
287        font::Weight::Bold => cosmic_text::Weight::BOLD,
288        font::Weight::ExtraBold => cosmic_text::Weight::EXTRA_BOLD,
289        font::Weight::Black => cosmic_text::Weight::BLACK,
290    }
291}
292
293fn to_stretch(stretch: font::Stretch) -> cosmic_text::Stretch {
294    match stretch {
295        font::Stretch::UltraCondensed => cosmic_text::Stretch::UltraCondensed,
296        font::Stretch::ExtraCondensed => cosmic_text::Stretch::ExtraCondensed,
297        font::Stretch::Condensed => cosmic_text::Stretch::Condensed,
298        font::Stretch::SemiCondensed => cosmic_text::Stretch::SemiCondensed,
299        font::Stretch::Normal => cosmic_text::Stretch::Normal,
300        font::Stretch::SemiExpanded => cosmic_text::Stretch::SemiExpanded,
301        font::Stretch::Expanded => cosmic_text::Stretch::Expanded,
302        font::Stretch::ExtraExpanded => cosmic_text::Stretch::ExtraExpanded,
303        font::Stretch::UltraExpanded => cosmic_text::Stretch::UltraExpanded,
304    }
305}
306
307fn to_style(style: font::Style) -> cosmic_text::Style {
308    match style {
309        font::Style::Normal => cosmic_text::Style::Normal,
310        font::Style::Italic => cosmic_text::Style::Italic,
311        font::Style::Oblique => cosmic_text::Style::Oblique,
312    }
313}
314
315fn to_align(alignment: Alignment) -> Option<cosmic_text::Align> {
316    match alignment {
317        Alignment::Default => None,
318        Alignment::Left => Some(cosmic_text::Align::Left),
319        Alignment::Center => Some(cosmic_text::Align::Center),
320        Alignment::Right => Some(cosmic_text::Align::Right),
321        Alignment::Justified => Some(cosmic_text::Align::Justified),
322    }
323}
324
325/// Converts some [`Shaping`] strategy to a [`cosmic_text::Shaping`] strategy.
326pub fn to_shaping(shaping: Shaping) -> cosmic_text::Shaping {
327    match shaping {
328        Shaping::Basic => cosmic_text::Shaping::Basic,
329        Shaping::Advanced => cosmic_text::Shaping::Advanced,
330    }
331}
332
333/// Converts some [`Wrapping`] strategy to a [`cosmic_text::Wrap`] strategy.
334pub fn to_wrap(wrapping: Wrapping) -> cosmic_text::Wrap {
335    match wrapping {
336        Wrapping::None => cosmic_text::Wrap::None,
337        Wrapping::Word => cosmic_text::Wrap::Word,
338        Wrapping::Glyph => cosmic_text::Wrap::Glyph,
339        Wrapping::WordOrGlyph => cosmic_text::Wrap::WordOrGlyph,
340    }
341}
342
343/// Converts some [`Color`] to a [`cosmic_text::Color`].
344pub fn to_color(color: Color) -> cosmic_text::Color {
345    let [r, g, b, a] = color.into_rgba8();
346
347    cosmic_text::Color::rgba(r, g, b, a)
348}