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
use fontref::FontRef;
use fontsource::{BuiltinFont, FontSource};
use graphicsstate::*;
use outline::OutlineItem;
use std::collections::HashMap;
use std::io::{self, Write};
use std::sync::Arc;
use textobject::TextObject;

/// A visual area where content can be drawn (a page).
///
/// Provides methods for defining and stroking or filling paths, as
/// well as placing text objects.
///
/// TODO Everything here that takes a `BuiltinFont` should take any
/// `FontSource` instead.
pub struct Canvas<'a> {
    output: &'a mut Write,
    fonts: &'a mut HashMap<BuiltinFont, FontRef>,
    outline_items: &'a mut Vec<OutlineItem>,
}

// Should not be called by user code.
pub fn create_canvas<'a>(
    output: &'a mut Write,
    fonts: &'a mut HashMap<BuiltinFont, FontRef>,
    outline_items: &'a mut Vec<OutlineItem>,
) -> Canvas<'a> {
    Canvas {
        output,
        fonts,
        outline_items,
    }
}

impl<'a> Canvas<'a> {
    /// Append a closed rectangle with a corner at (x, y) and
    /// extending width × height to the to the current path.
    pub fn rectangle(
        &mut self,
        x: f32,
        y: f32,
        width: f32,
        height: f32,
    ) -> io::Result<()> {
        writeln!(self.output, "{} {} {} {} re", x, y, width, height)
    }
    /// Set the line join style in the graphics state.
    pub fn set_line_join_style(
        &mut self,
        style: JoinStyle,
    ) -> io::Result<()> {
        writeln!(
            self.output,
            "{} j",
            match style {
                JoinStyle::Miter => 0,
                JoinStyle::Round => 1,
                JoinStyle::Bevel => 2,
            }
        )
    }
    /// Set the line join style in the graphics state.
    pub fn set_line_cap_style(&mut self, style: CapStyle) -> io::Result<()> {
        writeln!(
            self.output,
            "{} J",
            match style {
                CapStyle::Butt => 0,
                CapStyle::Round => 1,
                CapStyle::ProjectingSquare => 2,
            }
        )
    }
    /// Set the line width in the graphics state.
    pub fn set_line_width(&mut self, w: f32) -> io::Result<()> {
        writeln!(self.output, "{} w", w)
    }
    /// Set color for stroking operations.
    pub fn set_stroke_color(&mut self, color: Color) -> io::Result<()> {
        let norm = |c| f32::from(c) / 255.0;
        match color {
            Color::RGB { red, green, blue } => writeln!(
                self.output,
                "{} {} {} SC",
                norm(red),
                norm(green),
                norm(blue),
            ),
            Color::Gray { gray } => writeln!(self.output, "{} G", norm(gray)),
        }
    }
    /// Set color for non-stroking operations.
    pub fn set_fill_color(&mut self, color: Color) -> io::Result<()> {
        let norm = |c| f32::from(c) / 255.0;
        match color {
            Color::RGB { red, green, blue } => writeln!(
                self.output,
                "{} {} {} sc",
                norm(red),
                norm(green),
                norm(blue),
            ),
            Color::Gray { gray } => writeln!(self.output, "{} g", norm(gray)),
        }
    }

    /// Modify the current transformation matrix for coordinates by
    /// concatenating the specified matrix.
    pub fn concat(&mut self, m: Matrix) -> io::Result<()> {
        writeln!(self.output, "{} cm", m)
    }

    /// Append a straight line from (x1, y1) to (x2, y2) to the current path.
    pub fn line(
        &mut self,
        x1: f32,
        y1: f32,
        x2: f32,
        y2: f32,
    ) -> io::Result<()> {
        self.move_to(x1, y1)?;
        self.line_to(x2, y2)
    }
    /// Begin a new subpath at the point (x, y).
    pub fn move_to(&mut self, x: f32, y: f32) -> io::Result<()> {
        write!(self.output, "{} {} m ", x, y)
    }
    /// Add a straight line from the current point to (x, y) to the
    /// current path.
    pub fn line_to(&mut self, x: f32, y: f32) -> io::Result<()> {
        write!(self.output, "{} {} l ", x, y)
    }
    /// Add a Bézier curve from the current point to (x3, y3) with
    /// (x1, y1) and (x2, y2) as Bézier controll points.
    pub fn curve_to(
        &mut self,
        x1: f32,
        y1: f32,
        x2: f32,
        y2: f32,
        x3: f32,
        y3: f32,
    ) -> io::Result<()> {
        writeln!(self.output, "{} {} {} {} {} {} c", x1, y1, x2, y2, x3, y3)
    }
    /// Add a circle approximated by four cubic Bézier curves to the
    /// current path.  Based on
    /// http://spencermortensen.com/articles/bezier-circle/
    pub fn circle(&mut self, x: f32, y: f32, r: f32) -> io::Result<()> {
        let top = y - r;
        let bottom = y + r;
        let left = x - r;
        let right = x + r;
        #[cfg_attr(feature = "cargo-clippy", allow(excessive_precision))]
        let c = 0.551_915_024_494;
        let dist = r * c;
        let up = y - dist;
        let down = y + dist;
        let leftp = x - dist;
        let rightp = x + dist;
        self.move_to(x, top)?;
        self.curve_to(leftp, top, left, up, left, y)?;
        self.curve_to(left, down, leftp, bottom, x, bottom)?;
        self.curve_to(rightp, bottom, right, down, right, y)?;
        self.curve_to(right, up, rightp, top, x, top)?;
        Ok(())
    }
    /// Stroke the current path.
    pub fn stroke(&mut self) -> io::Result<()> {
        writeln!(self.output, "S")
    }
    /// Close and stroke the current path.
    pub fn close_and_stroke(&mut self) -> io::Result<()> {
        writeln!(self.output, "s")
    }
    /// Fill the current path.
    pub fn fill(&mut self) -> io::Result<()> {
        writeln!(self.output, "f")
    }
    /// Get a FontRef for a specific font.
    pub fn get_font(&mut self, font: BuiltinFont) -> FontRef {
        use fontref::create_font_ref;
        let next_n = self.fonts.len();
        self.fonts
            .entry(font)
            .or_insert_with(|| {
                create_font_ref(
                    next_n,
                    font.get_encoding().clone(),
                    Arc::new(font.get_metrics()),
                )
            })
            .clone()
    }

    /// Create a text object.
    ///
    /// The contents of the text object is defined by the function
    /// render_text, by applying methods to the TextObject it gets as
    /// an argument.
    /// On success, return the value returned by render_text.
    pub fn text<F, T>(&mut self, render_text: F) -> io::Result<T>
    where
        F: FnOnce(&mut TextObject) -> io::Result<T>,
    {
        use textobject::create_text_object;
        writeln!(self.output, "BT")?;
        let result = render_text(&mut create_text_object(self.output))?;
        writeln!(self.output, "ET")?;
        Ok(result)
    }
    /// Utility method for placing a string of text.
    pub fn left_text(
        &mut self,
        x: f32,
        y: f32,
        font: BuiltinFont,
        size: f32,
        text: &str,
    ) -> io::Result<()> {
        let font = self.get_font(font);
        self.text(|t| {
            t.set_font(&font, size)?;
            t.pos(x, y)?;
            t.show(text)
        })
    }
    /// Utility method for placing a string of text.
    pub fn right_text(
        &mut self,
        x: f32,
        y: f32,
        font: BuiltinFont,
        size: f32,
        text: &str,
    ) -> io::Result<()> {
        let font = self.get_font(font);
        self.text(|t| {
            let text_width = font.get_width(size, text);
            t.set_font(&font, size)?;
            t.pos(x - text_width, y)?;
            t.show(text)
        })
    }
    /// Utility method for placing a string of text.
    pub fn center_text(
        &mut self,
        x: f32,
        y: f32,
        font: BuiltinFont,
        size: f32,
        text: &str,
    ) -> io::Result<()> {
        let font = self.get_font(font);
        self.text(|t| {
            let text_width = font.get_width(size, text);
            t.set_font(&font, size)?;
            t.pos(x - text_width / 2.0, y)?;
            t.show(text)
        })
    }

    /// Add an item for this page in the document outline.
    ///
    /// An outline item associates a name (contained in an ordered
    /// tree) with a location in the document.  The PDF standard
    /// supports several ways to specify an exact location on a page,
    /// but this implementation currently only supports linking to a
    /// specific page (the page that this Canvas is for).
    pub fn add_outline(&mut self, title: &str) {
        self.outline_items.push(OutlineItem::new(title));
    }

    /// Save the current graphics state.
    /// The caller is responsible for restoring it later.
    pub fn gsave(&mut self) -> io::Result<()> {
        writeln!(self.output, "q")
    }
    /// Restor the current graphics state.
    /// The caller is responsible for having saved it earlier.
    pub fn grestore(&mut self) -> io::Result<()> {
        writeln!(self.output, "Q")
    }
}