multi-mono-font 0.5.0

Multi mono font mixed typesetting for embedded-graphics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::{
    ChSzTy, GlyphData, MultiMonoFont, MultiMonoFontList, char_size::CharSize,
    draw_target::MultiMonoFontDrawTarget,
};
use embedded_graphics::{
    draw_target::DrawTarget,
    geometry::{Point, Size},
    pixelcolor::{BinaryColor, PixelColor},
    prelude::OriginDimensions,
    primitives::Rectangle,
    text::{
        Baseline,
        renderer::{CharacterStyle, TextMetrics, TextRenderer},
    },
};

#[cfg(feature = "font-rawimg")]
use embedded_graphics::{Drawable, image::Image};

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MultiMonoLineHeight {
    Max,
    Min,
    Specify(ChSzTy),
}

const fn get_line_height<'a>(
    fonts_height: MultiMonoLineHeight,
    fonts: MultiMonoFontList<'a>,
) -> ChSzTy {
    let mut idx = 0;
    match fonts_height {
        MultiMonoLineHeight::Max => {
            let mut max = ChSzTy::MIN;
            while idx < fonts.len() {
                let h = fonts[idx].character_size.height as ChSzTy;
                idx += 1;
                if h > max {
                    max = h;
                }
            }
            max
        }
        MultiMonoLineHeight::Min => {
            let mut min = ChSzTy::MAX;
            while idx < fonts.len() {
                let h = fonts[idx].character_size.height as ChSzTy;
                idx += 1;
                if h < min {
                    min = h;
                }
            }
            min
        }
        MultiMonoLineHeight::Specify(h) => h,
    }
}

/// Style properties for text using a monospaced font.
///
/// A `MultiMonoTextStyle` can be applied to a [`Text`] object to define how the text is drawn.
///
/// Because `MultiMonoTextStyle` has the [`non_exhaustive`] attribute, it cannot be created using a
/// struct literal. To create a `MultiMonoTextStyle` with a given text color and transparent
/// background, use the [`new`] method. For more complex text styles, use the
/// [`MultiMonoTextStyleBuilder`].
///
/// [`Text`]: crate::text::Text
/// [`non_exhaustive`]: https://blog.rust-lang.org/2019/12/19/Rust-1.40.0.html#[non_exhaustive]-structs,-enums,-and-variants
/// [`new`]: MultiMonoTextStyle::new()
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(::defmt::Format))]
#[non_exhaustive]
pub struct MultiMonoTextStyle<'a, C> {
    /// Text color.
    pub text_color: C,

    /// Background color.
    pub background_color: Option<C>,

    /// Font.
    pub fonts: MultiMonoFontList<'a>,

    ///Line height
    pub line_height: ChSzTy,
}

impl<'a, C> MultiMonoTextStyle<'a, C>
where
    C: PixelColor,
{
    /// Creates a text style with transparent background.
    pub const fn new(font_list: MultiMonoFontList<'a>, text_color: C) -> Self {
        MultiMonoTextStyleBuilder::new(text_color)
            .font(font_list, MultiMonoLineHeight::Max)
            .build()
    }

    pub const fn new_with_line_height(
        font_list: MultiMonoFontList<'a>,
        line_height: MultiMonoLineHeight,
        text_color: C,
    ) -> Self {
        MultiMonoTextStyleBuilder::new(text_color)
            .font(font_list, line_height)
            .build()
    }

    fn get_font_info(&self, c: char) -> &MultiMonoFont<'a> {
        for font in self.fonts {
            if font.glyph_mapping.contains(c) {
                return font;
            }
        }

        self.fonts[0]
    }

    fn draw_string_binary<D>(
        &self,
        text: &str,
        position: Point,
        baseline: Baseline,
        mut target: D,
    ) -> Result<Point, D::Error>
    where
        D: DrawTarget<Color = BinaryColor>,
    {
        let mut next_pos = position;
        let mut draw_pos;

        for c in text.chars() {
            let font = self.get_font_info(c);
            draw_pos = next_pos - Point::new(0, self.baseline_offset(baseline, font));
            match font.glyph_data {
                #[cfg(feature = "font-rawimg")]
                GlyphData::ImgRaw(img_raw) => {
                    let glyph = font.glyph_img(c, &img_raw);
                    Image::new(&glyph, draw_pos).draw(&mut target)?;
                }
                #[cfg(feature = "font-rle")]
                GlyphData::RLE(rle_raw) => {
                    let glyph = font.glyph_rle(c, &rle_raw);
                    crate::glyph_reader::render_glyph_as_box_fill(
                        &Rectangle::new(draw_pos, font.character_size.size()),
                        glyph,
                        &mut target,
                    )?;
                }
            }

            next_pos.x += font.character_size.width as i32;
            if font.character_spacing > 0 {
                draw_pos.x += font.character_size.width as i32;
                if self.background_color.is_some() {
                    target.fill_solid(
                        &Rectangle::new(
                            draw_pos,
                            CharSize::new(font.character_spacing, font.character_size.height)
                                .size(),
                        ),
                        BinaryColor::Off,
                    )?;
                }
                next_pos.x += font.character_spacing as i32;
            }
        }

        Ok(next_pos)
    }

    /// Returns the vertical offset between the line position and the top edge of the bounding box.
    fn baseline_offset(&self, baseline: Baseline, font: &MultiMonoFont<'a>) -> i32 {
        match baseline {
            Baseline::Top => 0,
            Baseline::Bottom => font.character_size.height.saturating_sub(1) as i32,
            Baseline::Middle => (font.character_size.height.saturating_sub(1) / 2) as i32,
            Baseline::Alphabetic => font.baseline as i32,
        }
    }
}

impl<C> TextRenderer for MultiMonoTextStyle<'_, C>
where
    C: PixelColor,
{
    type Color = C;

    fn draw_string<D>(
        &self,
        text: &str,
        position: Point,
        baseline: Baseline,
        target: &mut D,
    ) -> Result<Point, D::Error>
    where
        D: DrawTarget<Color = Self::Color>,
    {
        self.draw_string_binary(
            text,
            position,
            baseline,
            MultiMonoFontDrawTarget::new(target, self.text_color, self.background_color),
        )
    }

    fn draw_whitespace<D>(
        &self,
        width: u32,
        position: Point,
        baseline: Baseline,
        target: &mut D,
    ) -> Result<Point, D::Error>
    where
        D: DrawTarget<Color = Self::Color>,
    {
        let (offet_y, height) = match baseline {
            Baseline::Top => (0, self.line_height),
            Baseline::Bottom => (self.line_height.saturating_sub(1) as i32, self.line_height),
            Baseline::Middle => (
                (self.line_height.saturating_sub(1) / 2) as i32,
                self.line_height,
            ),
            Baseline::Alphabetic => (
                self.fonts[0].baseline as i32,
                self.fonts[0].character_size.height,
            ),
        };
        let position = position - Point::new(0, offet_y);

        if width != 0
            && let Some(background_color) = self.background_color
        {
            target.fill_solid(
                &Rectangle::new(position, Size::new(width, height as u32)),
                background_color,
            )?;
        }

        Ok(position + Point::new(width as i32, offet_y))
    }

    fn measure_string(&self, text: &str, position: Point, baseline: Baseline) -> TextMetrics {
        let mut bb_width = 0;
        let mut bb_height = 0;
        let mut baseline_max = 0;
        let mut font = self.fonts[0];
        for c in text.chars() {
            font = self.get_font_info(c);
            bb_width += (font.character_size.width + font.character_spacing) as u32;
            bb_height = bb_height.max(font.character_size.height as u32);

            baseline_max = baseline_max.max(self.baseline_offset(baseline, font));
        }
        bb_width = bb_width.saturating_sub(font.character_spacing as u32);

        let bb_size = Size::new(bb_width, bb_height);

        let bb_position = position - Point::new(0, baseline_max);
        TextMetrics {
            bounding_box: Rectangle::new(bb_position, bb_size),
            next_position: position + bb_size.x_axis(),
        }
    }

    fn line_height(&self) -> u32 {
        self.line_height as u32
    }
}

impl<C> CharacterStyle for MultiMonoTextStyle<'_, C>
where
    C: PixelColor,
{
    type Color = C;

    fn set_text_color(&mut self, text_color: Option<Self::Color>) {
        if let Some(color) = text_color {
            self.text_color = color;
        }
    }

    fn set_background_color(&mut self, background_color: Option<Self::Color>) {
        self.background_color = background_color;
    }
}

/// Text style builder for monospaced fonts.
///
/// Use this builder to create [`MultiMonoTextStyle`]s for [`Text`].
///
/// # Examples
///
/// ## Render yellow text on a blue background
///
/// This uses the [`FONT_6X9`] font, but [other fonts] can also be used.
///
/// ```rust
/// use multi_mono_font::{ascii::FONT_6X9, MultiMonoTextStyle, MultiMonoTextStyleBuilder};
/// use embedded_graphics::{
///     pixelcolor::Rgb565,
///     prelude::*,
///     text::Text,
/// };
///
/// let style = MultiMonoTextStyleBuilder::new()
///     .font(&FONT_6X9)
///     .text_color(Rgb565::YELLOW)
///     .background_color(Rgb565::BLUE)
///     .build();
///
/// let text = Text::new("Hello Rust!", Point::new(0, 0), style);
/// ```
///
/// ## Transparent background
///
/// If a property is omitted, it will remain at its default value in the resulting
/// `MultiMonoTextStyle` returned by `.build()`. This example draws white text with no background at
/// all.
///
/// ```rust
/// use multi_mono_font::{ascii::FONT_6X9, MultiMonoTextStyle, MultiMonoTextStyleBuilder};
/// use embedded_graphics::{
///     pixelcolor::Rgb565,
///     prelude::*,
///     text::Text,
/// };
///
/// let style = MultiMonoTextStyleBuilder::new()
///     .font(&FONT_6X9)
///     .text_color(Rgb565::WHITE)
///     .build();
///
/// let text = Text::new("Hello Rust!", Point::new(0, 0), style);
/// ```
///
/// ## Modifying an existing style
///
/// The builder can also be used to modify an existing style.
///
/// ```
/// use multi_mono_font::{ascii::FONT_6X9, MultiMonoTextStyle, MultiMonoTextStyleBuilder};
/// use embedded_graphics::{
///     pixelcolor::Rgb565,
///     prelude::*,
///     text::Text,
/// };
///
/// let style = MultiMonoTextStyle::new(&FONT_6X9, Rgb565::YELLOW);
///
/// let style_larger = MultiMonoTextStyleBuilder::from(&style)
///     .font(&FONT_10X20)
///     .build();
/// ```
///
/// [`FONT_6X9`]: crate::::ascii::FONT_6X9
/// [other fonts]: super
/// [`Text`]: crate::text::Text
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(::defmt::Format))]
pub struct MultiMonoTextStyleBuilder<'a, C> {
    style: MultiMonoTextStyle<'a, C>,
}

impl<'a, C> MultiMonoTextStyleBuilder<'a, C>
where
    C: PixelColor,
{
    /// Creates a new text style builder.
    pub const fn new(text_color: C) -> Self {
        Self {
            style: MultiMonoTextStyle {
                fonts: &[&super::NULL_FONT],
                background_color: None,
                text_color,
                line_height: 0,
            },
        }
    }

    /// Sets the font.
    pub const fn font<'b>(
        self,
        font_list: &'b [&'b MultiMonoFont<'b>],
        line_height: MultiMonoLineHeight,
    ) -> MultiMonoTextStyleBuilder<'b, C> {
        let fonts = if font_list.is_empty() {
            &[&crate::NULL_FONT]
        } else {
            font_list
        };
        let line_height = get_line_height(line_height, fonts);
        let style = MultiMonoTextStyle {
            fonts,
            background_color: self.style.background_color,
            text_color: self.style.text_color,
            line_height,
        };

        MultiMonoTextStyleBuilder { style }
    }

    /// Resets the background color to transparent.
    pub const fn reset_background_color(mut self) -> Self {
        self.style.background_color = None;

        self
    }

    /// Sets the text color.
    pub const fn text_color(mut self, text_color: C) -> Self {
        self.style.text_color = text_color;

        self
    }

    /// Sets the line height.
    pub const fn line_height(mut self, line_height: MultiMonoLineHeight) -> Self {
        self.style.line_height = get_line_height(line_height, self.style.fonts);

        self
    }

    /// Sets the background color.
    pub const fn background_color(mut self, background_color: C) -> Self {
        self.style.background_color = Some(background_color);

        self
    }

    /// Builds the text style.
    ///
    /// This method can only be called after a font was set by using the [`font`] method. All other
    /// settings are optional and they will be set to their default value if they are missing.
    ///
    /// [`font`]: MultiMonoTextStyleBuilder::font()
    pub const fn build(self) -> MultiMonoTextStyle<'a, C> {
        self.style
    }
}

impl<'a, C> From<&MultiMonoTextStyle<'a, C>> for MultiMonoTextStyleBuilder<'a, C>
where
    C: PixelColor,
{
    fn from(style: &MultiMonoTextStyle<'a, C>) -> Self {
        Self { style: *style }
    }
}