Skip to main content

draftwright/
png.rs

1//! The drawing as a PNG: the layers [`Drawing::pdf`] draws, rasterised at a resolution (draftwright
2//! renders its PDF through PDFium at `dpi`, 150 by default, and refuses `dpi <= 0`). The pixels need
3//! not match PDFium's; the page is the same size, `ceil(page × dpi)` pixels each way as PDFium makes
4//! it, white, with each layer's lines and faces in its style (round caps, mitred joins, faces filled
5//! non-zero and stroked, as in the PDF). The glyphs are the faces the drawing already holds; the
6//! invisible text and the link are not drawn.
7//!
8//! The bytes depend only on the drawing and the resolution. tiny-skia rasterises on one thread
9//! without SIMD (the scalar path, so no float differs between instruction sets); every point is put
10//! on a 1/256-pixel grid before it is handed over, so a last-bit difference in the platform's sine
11//! and cosine (arcs become cubics) does not reach the pixels, short of a point on a grid boundary.
12//! The PNG is 8-bit RGB with fixed filtering and compression, its physical size in a `pHYs` chunk
13//! and no time chunk. The spec is carried in an iTXt chunk keyed [`SPEC_KEY`], uncompressed, and
14//! read back by [`spec`].
15
16use tiny_skia::{
17    Color, FillRule, LineCap, Paint, PathBuilder, Pixmap, Stroke, StrokeDash, Transform,
18};
19
20use crate::output::{Curve, Drawing, GENERATED_BY, Item, LINK, P, PathSeg, path_segments};
21
22/// draftwright's default resolution, pixels per inch.
23pub const DPI: f64 = 150.0;
24
25/// The most pixels a PNG may have (a 1 GiB raster while it is drawn): A0 at 400 dpi fits.
26pub const MAX_PIXELS: u64 = 1 << 28;
27
28/// The keyword of the iTXt chunk that carries the spec, as the PDF's document information does.
29pub const SPEC_KEY: &str = "DraftwrightSpec";
30
31const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
32
33/// The size in pixels of a page *page* (mm) at *dpi*, rounded up as PDFium rounds it. A page
34/// that is a whole number of pixels to within 1e-9 of one is that number.
35pub fn size(page: P, dpi: f64) -> [u64; 2] {
36    page.map(|mm| (mm / 25.4 * dpi - 1e-9).ceil().max(1.0) as u64)
37}
38
39impl Drawing {
40    /// The PNG at *dpi*, or why there is none: a *dpi* that is not positive, or a page too large
41    /// at it.
42    pub fn png(&self, dpi: f64) -> Result<Vec<u8>, String> {
43        self.png_region(dpi, None)
44    }
45    /// Render a paper region directly, keeping the full drawing's embedded Spec.
46    pub fn png_region(&self, dpi: f64, region: Option<[f64; 4]>) -> Result<Vec<u8>, String> {
47        if !(dpi > 0.0 && dpi.is_finite()) {
48            return Err(format!("png export needs dpi > 0, got {dpi}"));
49        }
50        let [left, bottom, right, top] = region.unwrap_or([0.0, 0.0, self.page[0], self.page[1]]);
51        if ![left, bottom, right, top].iter().all(|x| x.is_finite())
52            || left < 0.0
53            || bottom < 0.0
54            || right > self.page[0]
55            || top > self.page[1]
56            || right <= left
57            || top <= bottom
58        {
59            return Err(format!(
60                "region must be [left,bottom,right,top] within page {:?}, with positive width and height",
61                self.page
62            ));
63        }
64        let [w, h] = size([right - left, top - bottom], dpi);
65        if w.checked_mul(h).is_none_or(|pixels| pixels > MAX_PIXELS) {
66            return Err(format!(
67                "a {w} × {h} pixel PNG at {dpi} dpi is more than {MAX_PIXELS} pixels; choose a lower dpi"
68            ));
69        }
70        let mut pixmap = Pixmap::new(w as u32, h as u32)
71            .ok_or_else(|| format!("cannot make a {w} × {h} pixel raster"))?;
72        pixmap.fill(Color::WHITE);
73        let k = dpi / 25.4;
74        let page_h = top;
75        // Page mm, y up, to pixels, y down, on the 1/256-pixel grid.
76        let at = |p: P| {
77            let q = |v: f64| ((v * 256.0).round() / 256.0) as f32;
78            (q((p[0] - left) * k), q((page_h - p[1]) * k))
79        };
80        for layer in self.paint_layers() {
81            let st = &layer.style;
82            let mut paint = Paint::default();
83            let [r, g, b] = st.colour;
84            paint.set_color_rgba8(r, g, b, 255);
85            // Adjacent opaque facets share boundaries exactly. Rasterising each with
86            // partial coverage would blend the white page through their shared edge.
87            // The HLR outline over them retains its normal antialiasing.
88            paint.anti_alias = !layer.name.starts_with("shaded-");
89            let mut stroke = Stroke {
90                width: (st.width * k) as f32,
91                line_cap: LineCap::Round,
92                dash: st.dash.and_then(|pattern| {
93                    StrokeDash::new(pattern.iter().map(|n| (n * k) as f32).collect(), 0.0)
94                }),
95                ..Stroke::default()
96            };
97            for item in &layer.items {
98                stroke.width = match item {
99                    Item::FrameText(..) => (crate::output::TEXT_PEN * k) as f32,
100                    _ => (st.width * k) as f32,
101                };
102                if layer.name == "centres" {
103                    stroke.dash = StrokeDash::new(
104                        st.dash.unwrap().iter().map(|n| (n * k) as f32).collect(),
105                        (crate::output::centre_phase(item) * k) as f32,
106                    );
107                }
108                let mut pb = PathBuilder::new();
109                let mut trace = |wire: &[Curve]| {
110                    let (x, y) = at(wire[0].start());
111                    pb.move_to(x, y);
112                    for curve in wire {
113                        for seg in path_segments(curve) {
114                            match seg {
115                                PathSeg::Line(b) => {
116                                    let (x, y) = at(b);
117                                    pb.line_to(x, y);
118                                }
119                                PathSeg::Cubic(c1, c2, b) => {
120                                    let ((x1, y1), (x2, y2), (x, y)) = (at(c1), at(c2), at(b));
121                                    pb.cubic_to(x1, y1, x2, y2, x, y);
122                                }
123                            }
124                        }
125                    }
126                };
127                match item {
128                    Item::Edge(curve) | Item::TextStroke(curve, _) | Item::FrameText(curve, _) => {
129                        trace(std::slice::from_ref(curve))
130                    }
131                    Item::Face(wires) | Item::Glyph(wires, _) => {
132                        wires.iter().for_each(|w| trace(w))
133                    }
134                }
135                // A path of no extent (a curve whose ends and poles fall on one grid point) has
136                // nothing to draw.
137                let Some(path) = pb.finish() else { continue };
138                if matches!(item, Item::Face(_) | Item::Glyph(_, _)) && st.fill {
139                    pixmap.fill_path(
140                        &path,
141                        &paint,
142                        FillRule::Winding,
143                        Transform::identity(),
144                        None,
145                    );
146                }
147                pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
148            }
149        }
150        encode(&pixmap, dpi, self.spec.as_deref())
151    }
152}
153
154/// *pixmap* (opaque) as an 8-bit RGB PNG at *dpi*, carrying *spec*.
155fn encode(pixmap: &Pixmap, dpi: f64, spec: Option<&str>) -> Result<Vec<u8>, String> {
156    let rgb: Vec<u8> = pixmap
157        .data()
158        .as_chunks::<4>()
159        .0
160        .iter()
161        .flat_map(|&[r, g, b, _]| [r, g, b])
162        .collect();
163    let mut out = Vec::new();
164    let mut encoder = ::png::Encoder::new(&mut out, pixmap.width(), pixmap.height());
165    encoder.set_color(::png::ColorType::Rgb);
166    encoder.set_depth(::png::BitDepth::Eight);
167    encoder.set_compression(::png::Compression::Balanced);
168    encoder.set_filter(::png::Filter::Adaptive);
169    let per_metre = (dpi / 0.0254).round() as u32;
170    encoder.set_pixel_dims(Some(::png::PixelDimensions {
171        xppu: per_metre,
172        yppu: per_metre,
173        unit: ::png::Unit::Meter,
174    }));
175    let failed = |e: ::png::EncodingError| format!("cannot encode the PNG: {e}");
176    encoder
177        .add_text_chunk("Software".into(), "draftwright".into())
178        .map_err(failed)?;
179    encoder
180        .add_text_chunk("Comment".into(), format!("{GENERATED_BY}: {LINK}"))
181        .map_err(failed)?;
182    if let Some(spec) = spec {
183        encoder
184            .add_itxt_chunk(SPEC_KEY.into(), spec.into())
185            .map_err(failed)?;
186    }
187    let mut writer = encoder.write_header().map_err(failed)?;
188    writer.write_image_data(&rgb).map_err(failed)?;
189    writer.finish().map_err(failed)?;
190    Ok(out)
191}
192
193/// Whether *file* is a PNG.
194pub fn is_png(file: &[u8]) -> bool {
195    file.starts_with(SIGNATURE)
196}
197
198/// The JSON of a PNG's spec: the text of its first iTXt chunk keyed [`SPEC_KEY`] (compressed or
199/// not, so a tool that re-saves it compressed still reads), or none.
200pub fn spec(file: &[u8]) -> Result<Option<String>, String> {
201    let truncated = || "its PNG chunks are truncated".to_string();
202    let mut rest = file.strip_prefix(SIGNATURE).ok_or("it is not a PNG")?;
203    while !rest.is_empty() {
204        let len = u32::from_be_bytes(rest.get(..4).ok_or_else(truncated)?.try_into().unwrap());
205        let len = len as usize;
206        let kind = rest.get(4..8).ok_or_else(truncated)?;
207        let data = rest.get(8..8 + len).ok_or_else(truncated)?;
208        rest = rest.get(12 + len..).ok_or_else(truncated)?;
209        if kind == b"IEND" {
210            break;
211        }
212        if kind != b"iTXt" {
213            continue;
214        }
215        let mut fields = data.splitn(2, |&b| b == 0);
216        if fields.next() != Some(SPEC_KEY.as_bytes()) {
217            continue;
218        }
219        let broken = || format!("its {SPEC_KEY} chunk is not a valid iTXt chunk");
220        let after = fields.next().ok_or_else(broken)?;
221        let (&compressed, after) = after.split_first().ok_or_else(broken)?;
222        let after = after.get(1..).ok_or_else(broken)?;
223        // The language tag and the translated keyword, each ended by a zero.
224        let mut fields = after.splitn(3, |&b| b == 0);
225        let (_, _, text) = (
226            fields.next(),
227            fields.next(),
228            fields.next().ok_or_else(broken)?,
229        );
230        let text = if compressed == 1 {
231            use std::io::Read as _;
232            let mut out = Vec::new();
233            flate2::read::ZlibDecoder::new(text)
234                .read_to_end(&mut out)
235                .map_err(|_| broken())?;
236            out
237        } else {
238            text.to_vec()
239        };
240        return String::from_utf8(text).map(Some).map_err(|_| broken());
241    }
242    Ok(None)
243}