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
use crate::fonts::{Em, Font, FontError, GlyphId};
use crate::primitives::Length;
use std::sync::Arc;

#[derive(Clone)]
pub struct ShapedSegment {
    pub font: Arc<Font>,
    pub glyphs: Vec<GlyphId>,
    pub advance_width: Length<Em>,
}

pub struct ShapedSegmentState {
    glyphs: usize,
    advance_width: Length<Em>,
}

impl std::fmt::Debug for ShapedSegment {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        fmt.write_str("ShapedSegment")
    }
}

impl ShapedSegment {
    /// Simplistic text shaping:
    ///
    /// * No font fallback
    /// * No support for complex scripts
    /// * No ligatures
    /// * No kerning
    pub fn naive_shape(text: &str, font: Arc<Font>) -> Result<Self, FontError> {
        let mut s = Self::new_with_naive_shaping(font);
        s.append(text.chars())?;
        Ok(s)
    }

    pub fn new_with_naive_shaping(font: Arc<Font>) -> Self {
        Self {
            font,
            glyphs: Vec::new(),
            advance_width: Length::new(0.),
        }
    }

    pub fn append(&mut self, mut text: impl Iterator<Item = char>) -> Result<(), FontError> {
        text.try_for_each(|ch| self.append_char(ch))
    }

    pub fn append_char(&mut self, ch: char) -> Result<(), FontError> {
        let id = self.font.glyph_id(ch)?;
        self.advance_width += self.font.glyph_width(id)?;
        self.glyphs.push(id);
        Ok(())
    }

    pub fn save(&self) -> ShapedSegmentState {
        ShapedSegmentState {
            glyphs: self.glyphs.len(),
            advance_width: self.advance_width,
        }
    }

    pub fn restore(&mut self, state: &ShapedSegmentState) {
        self.glyphs.truncate(state.glyphs);
        self.advance_width = state.advance_width;
    }
}