font_map_core/raw/ttf/glyf/
simple.rs

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
#![allow(clippy::cast_possible_truncation)]
use crate::error::ParseResult;
use crate::reader::{BinaryReader, Parse};

/// The outline features of a simple-type glyph
#[derive(Debug, Clone)]
pub struct SimpleGlyf {
    /// The contours of the glyph
    pub contours: Vec<Contour>,

    /// The number of contours in the glyph
    /// This field is used to prime the parser
    pub num_contours: i16,

    /// Horizontal bounds of the glyph
    pub x: (i16, i16),

    /// Vertical bounds of the glyph
    pub y: (i16, i16),
}

impl Parse for SimpleGlyf {
    fn parse<'a>(_: &'a mut BinaryReader<'a>) -> ParseResult<Self> {
        unimplemented!("Use parse_with instead")
    }

    fn parse_with<'a>(&mut self, reader: &'a mut BinaryReader<'a>) -> ParseResult<()> {
        // Simple glyph
        let mut end_pts_of_contours = Vec::with_capacity(self.num_contours as usize);
        let mut last_pt = 0;

        for _ in 0..self.num_contours {
            last_pt = reader.read_u16()?;
            end_pts_of_contours.push(last_pt);
        }

        let instruction_length = reader.read_u16()?;
        let _instructions = reader.read(instruction_length as usize)?;

        let num_points = last_pt + 1;

        //
        // Parse instructions to get real point count
        let mut flags = Vec::with_capacity(num_points as usize);
        let mut i = 0;
        while i < num_points {
            let flag = reader.read_u8()?;
            flags.push(flag);
            i += 1;

            if flag & REPEAT != 0 {
                // Repeat bit is set, read the repeat count
                let repeat = reader.read_u8()?;

                // Add the repeated flags
                flags.reserve(usize::from(repeat));
                for _ in 0..repeat {
                    flags.push(flag);
                }

                // Increment `i` for the repeated flags
                i += u16::from(repeat);
            }
        }

        //
        // Parse X coords into objective coords
        let mut last_x = 0;
        let mut x_coordinates = Vec::with_capacity(flags.len());
        for flag in &flags {
            if flag & X_SHORT != 0 {
                let x = i16::from(reader.read_u8()?);
                let is_neg = flag & X_SAME == 0;
                last_x += if is_neg { -x } else { x };
            } else if flag & X_SAME != 0 {
                // Use previous x
            } else {
                let delta = reader.read_i16()?;
                last_x += delta;
            };

            x_coordinates.push(last_x);
        }

        //
        // Parse Y coords into objective coords
        let mut last_y = 0;
        let mut y_coordinates = Vec::with_capacity(flags.len());
        for flag in &flags {
            if flag & Y_SHORT != 0 {
                let y = i16::from(reader.read_u8()?);
                let is_neg = flag & Y_SAME == 0;

                last_y += if is_neg { -y } else { y };
            } else if flag & Y_SAME != 0 {
                // Use previous y
            } else {
                let delta = reader.read_i16()?;
                last_y += delta;
            };

            y_coordinates.push(last_y);
        }

        //
        // Create points
        let mut points = Vec::with_capacity(flags.len());
        for i in 0..flags.len() {
            let x = x_coordinates[i];
            let y = y_coordinates[i];
            let on_curve = flags[i] & ON_CURVE != 0;
            points.push(Point { x, y, on_curve });
        }

        //
        // Map points to contours
        let mut start = 0;
        for end in &end_pts_of_contours {
            let contour_points = points[start..=*end as usize].to_vec();
            start = *end as usize + 1;
            self.contours.push(Contour {
                points: contour_points,
            });
        }

        Ok(())
    }
}

impl SimpleGlyf {
    /// Generate an SVG string representation of the glyph
    #[must_use]
    pub fn as_svg(&self) -> String {
        let mut shape = String::new();

        // Draw all the contours
        for contour in &self.contours {
            shape.push_str(&contour.as_svg());
        }

        // Wrap in SVG container, using x/y min/max as viewBox
        let (xmin, xmax) = (self.x.0, self.x.1);
        let (ymin, ymax) = (-self.y.1, -self.y.0);
        let width = xmax - xmin;
        let height = ymax - ymin;

        // Add a margin, preserving aspect ratio
        let x_margin = 10;
        let aspect_ratio = f32::from(width) / f32::from(height);
        let y_margin = (f32::from(x_margin) / aspect_ratio) as i16;
        let (xmin, xmax) = (xmin - x_margin, xmax + x_margin);
        let (ymin, ymax) = (ymin - y_margin, ymax + y_margin);
        let (width, height) = (xmax - xmin, ymax - ymin);

        // Calculate a new set of sizes for the final display
        let width2 = 50i16;
        let height2 = (f32::from(width2) / aspect_ratio) as i16;

        [
            r#"<?xml version="1.0" encoding="UTF-8"?>"#.to_string(),
            format!(
                "<svg xmlns='http://www.w3.org/2000/svg' width='{width2}' height='{height2}' viewBox='{xmin} {ymin} {width} {height}'>{shape}</svg>"
            ),
        ].join("")
    }
}

#[derive(Debug, Clone)]
pub struct Contour {
    pub points: Vec<Point>,
}
impl Contour {
    fn as_svg(&self) -> String {
        let mut path = String::new();

        // Move to the first point
        let mut point_iter = self.points.iter();
        if let Some(first) = point_iter.next() {
            let (x, y) = (first.x, -first.y);
            path.push_str(&format!("M{x} {y}"));
        }

        // Draw lines and curves
        for point in point_iter {
            let (x, y, on_curve) = (point.x, -point.y, point.on_curve);
            let ctrl = if on_curve { 'L' } else { 'T' };
            path.push_str(&format!("{ctrl}{x} {y}"));
        }

        // Close the path
        path.push('Z');

        format!("<path d='{path}' fill='none' stroke='red' stroke-width='5' />")
    }
}

#[derive(Debug, Default, Clone)]
pub struct Point {
    pub x: i16,
    pub y: i16,
    pub on_curve: bool,
}

const ON_CURVE: u8 = 0x01;
const X_SHORT: u8 = 0x02;
const Y_SHORT: u8 = 0x04;
const REPEAT: u8 = 0x08;
const X_SAME: u8 = 0x10;
const Y_SAME: u8 = 0x20;