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
use std::rc::Rc;

use truetype::glyph_data::{self, CompositeDescription, GlyphData, SimpleDescription};

use super::mapping::Mapping;
use super::metrics::Metrics;
use crate::builder::Builder;
use crate::case::Case;
use crate::glyph::Glyph;
use crate::{Offset, Result};

pub struct TrueType {
    glyph_data: Rc<GlyphData>,
    metrics: Rc<Metrics>,
    mapping: Rc<Mapping>,
}

impl TrueType {
    #[inline]
    pub fn new(glyph_data: Rc<GlyphData>, metrics: Rc<Metrics>, mapping: Rc<Mapping>) -> Self {
        TrueType {
            glyph_data: glyph_data,
            metrics: metrics,
            mapping: mapping,
        }
    }

    fn draw_glyph(&self, builder: &mut Builder, glyph: &glyph_data::Glyph) -> Result<()> {
        use truetype::glyph_data::Description::*;

        match &glyph.description {
            &Simple(ref description) => draw_simple(builder, description),
            &Composite(ref description) => draw_composite(self, builder, description),
        }
    }
}

impl Case for TrueType {
    fn draw(&self, character: char) -> Result<Option<Glyph>> {
        let mut builder = Builder::default();
        let glyph_index = match self.mapping.find(character) {
            Some(glyph_index) => glyph_index,
            _ => return Ok(None),
        };
        let glyph = match self.glyph_data.get(glyph_index as usize) {
            Some(glyph) => glyph,
            _ => raise!(
                "found no data for character {} with glyph {}",
                character,
                glyph_index,
            ),
        };
        builder.set_horizontal_metrics(self.metrics.get(glyph_index));
        if let &Some(ref glyph) = glyph {
            self.draw_glyph(&mut builder, glyph)?;
            builder.set_bounding_box((glyph.min_x, glyph.min_y, glyph.max_x, glyph.max_y));
        }
        Ok(Some(builder.into()))
    }
}

fn draw_simple(builder: &mut Builder, description: &SimpleDescription) -> Result<()> {
    macro_rules! expect(
        ($condition:expr) => (
            if !$condition {
                raise!(concat!("found a malformed glyph (", stringify!($condition), ")"));
            }
        )
    );

    let &SimpleDescription {
        ref end_points,
        ref flags,
        ref x,
        ref y,
        ..
    } = description;
    let point_count = flags.len();
    expect!(point_count == x.len());
    expect!(point_count == y.len());
    let mut i = 0;
    let mut sum = Offset::default();
    for k in end_points.iter().map(|&k| k as usize) {
        expect!(i < point_count);
        let start = Offset::from((x[i], y[i]));
        let mut control = match flags[i].is_on_curve() {
            false => Some(Offset::default()),
            _ => None,
        };
        let mut sum_delta = start;
        let mut offset = Offset::default();
        for j in (i + 1)..=k {
            expect!(j < point_count);
            let current = (x[j], y[j]).into();
            sum_delta += current;
            match (flags[j].is_on_curve(), &mut control) {
                (false, control @ &mut None) => {
                    *control = Some(current);
                }
                (false, &mut Some(ref mut control)) => {
                    let current = current / 2.0;
                    builder.add_quadratic(*control, current);
                    offset += *control + current;
                    *control = current;
                }
                (true, &mut None) => {
                    builder.add_linear(current);
                    offset += current;
                }
                (true, control @ &mut Some(_)) => {
                    let control = control.take().unwrap();
                    builder.add_quadratic(control, current);
                    offset += control + current;
                }
            }
        }
        match (flags[i].is_on_curve(), control) {
            (false, None) => {
                let control = (sum + start) - (sum + sum_delta);
                builder.move_control(control);
                offset += control;
                builder.move_absolute(sum + sum_delta);
            }
            (false, Some(control)) => {
                let current = ((sum + start) - (sum + sum_delta)) / 2.0;
                if !control.is_zero() || !current.is_zero() {
                    builder.add_quadratic(control, current);
                }
                offset += control + current;
                builder.move_control(current);
                offset += current;
                builder.move_absolute(sum + sum_delta + current);
            }
            (true, None) => {
                let current = -offset;
                if !current.is_zero() {
                    builder.add_linear(current);
                }
                offset += current;
                builder.move_absolute(sum + start);
            }
            (true, Some(control)) => {
                let current = -offset - control;
                if !control.is_zero() || !current.is_zero() {
                    builder.add_quadratic(control, current);
                }
                offset += control + current;
                builder.move_absolute(sum + start);
            }
        }
        debug_assert!(offset.is_zero());
        builder.flush();
        sum += sum_delta;
        i = k + 1;
    }
    Ok(())
}

fn draw_composite(
    case: &TrueType,
    builder: &mut Builder,
    description: &CompositeDescription,
) -> Result<()> {
    use truetype::glyph_data::{Arguments, Options};

    for component in description.components.iter() {
        let glyph_index = component.glyph_index;
        let offset = match &component.arguments {
            &Arguments::Offsets(x, y) => Offset::from((x, y)),
            &Arguments::Indices(..) => unimplemented!(),
        };
        match &component.options {
            &Options::None => {}
            &Options::Scalar(..) => unimplemented!(),
            &Options::Vector(..) => unimplemented!(),
            &Options::Matrix(..) => unimplemented!(),
        }
        let glyph = match case.glyph_data.get(glyph_index as usize) {
            Some(&Some(ref glyph)) => glyph,
            Some(&None) => continue,
            _ => raise!("found no data for glyph index {}", glyph_index),
        };
        if component.flags.should_use_metrics() {
            builder.set_horizontal_metrics(case.metrics.get(glyph_index));
        }
        builder.nest(offset, |builder| case.draw_glyph(builder, glyph))?;
    }
    Ok(())
}