1use 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
22pub const DPI: f64 = 150.0;
24
25pub const MAX_PIXELS: u64 = 1 << 28;
27
28pub const SPEC_KEY: &str = "DraftwrightSpec";
30
31const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
32
33pub 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 pub fn png(&self, dpi: f64) -> Result<Vec<u8>, String> {
43 self.png_region(dpi, None)
44 }
45 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 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 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 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
154fn 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
193pub fn is_png(file: &[u8]) -> bool {
195 file.starts_with(SIGNATURE)
196}
197
198pub 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 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}