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] = include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice();
113
114/// Returns the global [`FontSystem`].
115pub fn font_system() -> &'static RwLock<FontSystem> {
116    static FONT_SYSTEM: OnceLock<RwLock<FontSystem>> = OnceLock::new();
117
118    FONT_SYSTEM.get_or_init(|| {
119        RwLock::new(FontSystem {
120            raw: cosmic_text::FontSystem::new_with_fonts([
121                cosmic_text::fontdb::Source::Binary(Arc::new(
122                    include_bytes!("../fonts/Iced-Icons.ttf").as_slice(),
123                )),
124                #[cfg(feature = "fira-sans")]
125                cosmic_text::fontdb::Source::Binary(Arc::new(
126                    include_bytes!("../fonts/FiraSans-Regular.ttf").as_slice(),
127                )),
128            ]),
129            loaded_fonts: HashSet::new(),
130            version: Version::default(),
131        })
132    })
133}
134
135/// A set of system fonts.
136pub struct FontSystem {
137    raw: cosmic_text::FontSystem,
138    loaded_fonts: HashSet<usize>,
139    version: Version,
140}
141
142impl FontSystem {
143    /// Returns the raw [`cosmic_text::FontSystem`].
144    pub fn raw(&mut self) -> &mut cosmic_text::FontSystem {
145        &mut self.raw
146    }
147
148    /// Loads a font from its bytes.
149    pub fn load_font(&mut self, bytes: Cow<'static, [u8]>) {
150        if let Cow::Borrowed(bytes) = bytes {
151            let address = bytes.as_ptr() as usize;
152
153            if !self.loaded_fonts.insert(address) {
154                return;
155            }
156        }
157
158        let _ = self
159            .raw
160            .db_mut()
161            .load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(
162                bytes.into_owned(),
163            )));
164
165        self.version = Version(self.version.0 + 1);
166    }
167
168    /// Returns the current [`Version`] of the [`FontSystem`].
169    ///
170    /// Loading a font will increase the version of a [`FontSystem`].
171    pub fn version(&self) -> Version {
172        self.version
173    }
174}
175
176/// A version number.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
178pub struct Version(u32);
179
180/// A weak reference to a [`cosmic_text::Buffer`] that can be drawn.
181#[derive(Debug, Clone)]
182pub struct Raw {
183    /// A weak reference to a [`cosmic_text::Buffer`].
184    pub buffer: Weak<cosmic_text::Buffer>,
185    /// The position of the text.
186    pub position: Point,
187    /// The color of the text.
188    pub color: Color,
189    /// The clip bounds of the text.
190    pub clip_bounds: Rectangle,
191}
192
193impl PartialEq for Raw {
194    fn eq(&self, _other: &Self) -> bool {
195        // TODO: There is no proper way to compare raw buffers
196        // For now, no two instances of `Raw` text will be equal.
197        // This should be fine, but could trigger unnecessary redraws
198        // in the future.
199        false
200    }
201}
202
203/// Measures the dimensions of the given [`cosmic_text::Buffer`].
204pub fn measure(buffer: &cosmic_text::Buffer) -> (Size, bool) {
205    let (width, height, has_rtl) =
206        buffer
207            .layout_runs()
208            .fold((0.0, 0.0, false), |(width, height, has_rtl), run| {
209                (
210                    run.line_w.max(width),
211                    height + run.line_height,
212                    has_rtl || run.rtl,
213                )
214            });
215
216    (Size::new(width, height), has_rtl)
217}
218
219/// Aligns the given [`cosmic_text::Buffer`] with the given [`Alignment`]
220/// and returns its minimum [`Size`].
221pub fn align(
222    buffer: &mut cosmic_text::Buffer,
223    font_system: &mut cosmic_text::FontSystem,
224    alignment: Alignment,
225) -> Size {
226    let (min_bounds, has_rtl) = measure(buffer);
227    let mut needs_relayout = has_rtl;
228
229    if let Some(align) = to_align(alignment) {
230        let has_multiple_lines = buffer.lines.len() > 1
231            || buffer
232                .lines
233                .first()
234                .is_some_and(|line| line.layout_opt().is_some_and(|layout| layout.len() > 1));
235
236        if has_multiple_lines {
237            for line in &mut buffer.lines {
238                let _ = line.set_align(Some(align));
239            }
240
241            needs_relayout = true;
242        } else if let Some(line) = buffer.lines.first_mut() {
243            needs_relayout = line.set_align(None);
244        }
245    }
246
247    // TODO: Avoid relayout with some changes to `cosmic-text` (?)
248    if needs_relayout {
249        log::trace!("Relayouting paragraph...");
250
251        buffer.set_size(font_system, Some(min_bounds.width), Some(min_bounds.height));
252    }
253
254    min_bounds
255}
256
257/// Returns the attributes of the given [`Font`].
258pub fn to_attributes(font: Font) -> cosmic_text::Attrs<'static> {
259    cosmic_text::Attrs::new()
260        .family(to_family(font.family))
261        .weight(to_weight(font.weight))
262        .stretch(to_stretch(font.stretch))
263        .style(to_style(font.style))
264}
265
266fn to_family(family: font::Family) -> cosmic_text::Family<'static> {
267    match family {
268        font::Family::Name(name) => cosmic_text::Family::Name(name),
269        font::Family::SansSerif => cosmic_text::Family::SansSerif,
270        font::Family::Serif => cosmic_text::Family::Serif,
271        font::Family::Cursive => cosmic_text::Family::Cursive,
272        font::Family::Fantasy => cosmic_text::Family::Fantasy,
273        font::Family::Monospace => cosmic_text::Family::Monospace,
274    }
275}
276
277fn to_weight(weight: font::Weight) -> cosmic_text::Weight {
278    match weight {
279        font::Weight::Thin => cosmic_text::Weight::THIN,
280        font::Weight::ExtraLight => cosmic_text::Weight::EXTRA_LIGHT,
281        font::Weight::Light => cosmic_text::Weight::LIGHT,
282        font::Weight::Normal => cosmic_text::Weight::NORMAL,
283        font::Weight::Medium => cosmic_text::Weight::MEDIUM,
284        font::Weight::Semibold => cosmic_text::Weight::SEMIBOLD,
285        font::Weight::Bold => cosmic_text::Weight::BOLD,
286        font::Weight::ExtraBold => cosmic_text::Weight::EXTRA_BOLD,
287        font::Weight::Black => cosmic_text::Weight::BLACK,
288    }
289}
290
291fn to_stretch(stretch: font::Stretch) -> cosmic_text::Stretch {
292    match stretch {
293        font::Stretch::UltraCondensed => cosmic_text::Stretch::UltraCondensed,
294        font::Stretch::ExtraCondensed => cosmic_text::Stretch::ExtraCondensed,
295        font::Stretch::Condensed => cosmic_text::Stretch::Condensed,
296        font::Stretch::SemiCondensed => cosmic_text::Stretch::SemiCondensed,
297        font::Stretch::Normal => cosmic_text::Stretch::Normal,
298        font::Stretch::SemiExpanded => cosmic_text::Stretch::SemiExpanded,
299        font::Stretch::Expanded => cosmic_text::Stretch::Expanded,
300        font::Stretch::ExtraExpanded => cosmic_text::Stretch::ExtraExpanded,
301        font::Stretch::UltraExpanded => cosmic_text::Stretch::UltraExpanded,
302    }
303}
304
305fn to_style(style: font::Style) -> cosmic_text::Style {
306    match style {
307        font::Style::Normal => cosmic_text::Style::Normal,
308        font::Style::Italic => cosmic_text::Style::Italic,
309        font::Style::Oblique => cosmic_text::Style::Oblique,
310    }
311}
312
313fn to_align(alignment: Alignment) -> Option<cosmic_text::Align> {
314    match alignment {
315        Alignment::Default => None,
316        Alignment::Left => Some(cosmic_text::Align::Left),
317        Alignment::Center => Some(cosmic_text::Align::Center),
318        Alignment::Right => Some(cosmic_text::Align::Right),
319        Alignment::Justified => Some(cosmic_text::Align::Justified),
320    }
321}
322
323/// Converts some [`Shaping`] strategy to a [`cosmic_text::Shaping`] strategy.
324pub fn to_shaping(shaping: Shaping, text: &str) -> cosmic_text::Shaping {
325    match shaping {
326        Shaping::Auto => {
327            if text.is_ascii() {
328                cosmic_text::Shaping::Basic
329            } else {
330                cosmic_text::Shaping::Advanced
331            }
332        }
333        Shaping::Basic => cosmic_text::Shaping::Basic,
334        Shaping::Advanced => cosmic_text::Shaping::Advanced,
335    }
336}
337
338/// Converts some [`Wrapping`] strategy to a [`cosmic_text::Wrap`] strategy.
339pub fn to_wrap(wrapping: Wrapping) -> cosmic_text::Wrap {
340    match wrapping {
341        Wrapping::None => cosmic_text::Wrap::None,
342        Wrapping::Word => cosmic_text::Wrap::Word,
343        Wrapping::Glyph => cosmic_text::Wrap::Glyph,
344        Wrapping::WordOrGlyph => cosmic_text::Wrap::WordOrGlyph,
345    }
346}
347
348/// Converts some [`Color`] to a [`cosmic_text::Color`].
349pub fn to_color(color: Color) -> cosmic_text::Color {
350    let [r, g, b, a] = color.into_rgba8();
351
352    cosmic_text::Color::rgba(r, g, b, a)
353}
354
355/// A text renderer coupled to `iced_graphics`.
356pub trait Renderer {
357    /// Draws the given [`Raw`] text.
358    fn fill_raw(&mut self, raw: Raw);
359}