1mod font;
6mod format;
7mod image;
8mod metadata;
9mod text;
10mod tracker;
11
12use std::fmt;
13
14use pltrs_codec::CompressionLevel;
15use pltrs_codec::checksum::crc32;
16use pltrs_codec::png::EncodeError;
17use pltrs_core::Path;
18use pltrs_core::alloc::{self, OutOfMemory};
19use pltrs_core::path::convert::VertexSource;
20use pltrs_core::{Affine2D, Bbox, Point};
21use pltrs_text::TextError;
22use pltrs_text::tex::TexError;
23
24pub(crate) use font::{FontCache, FontInfo};
25pub(crate) use format::{fixed, general, hex, repr, repr_bytes, repr_str, short, trimmed};
26pub(crate) use image::{flipped_rows, png_idat};
27pub use metadata::{Metadata, PNG_SOFTWARE, PngMetadata, SvgMetadata, Timestamp, Trapped};
28pub(crate) use text::{POINTS_DPI, glyph_chars, in_points, prev_kerns};
29pub(crate) use tracker::{CharacterTracker, Subset};
30
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum FontType {
35 #[default]
37 Type3,
38 Type42,
40}
41
42impl FontType {
43 pub const fn from_number(number: u32) -> Option<Self> {
45 match number {
46 3 => Some(Self::Type3),
47 42 => Some(Self::Type42),
48 _ => None,
49 }
50 }
51
52 pub(crate) const fn subset_size(self) -> u32 {
55 match self {
56 Self::Type3 => 256,
57 Self::Type42 => 65536,
58 }
59 }
60}
61
62#[derive(Debug)]
64pub enum VectorError {
65 InvalidCanvas {
67 width: f64,
69 height: f64,
71 dpi: f64,
73 },
74 Font(TextError),
76 Image(EncodeError),
78 NonFinite(&'static str),
80 Unsupported(&'static str),
82 StreamedImage,
85 Tex(TexError),
87 UnwrittenObject(usize),
90 StreamOpen,
93 OutOfMemory(OutOfMemory),
95}
96
97impl fmt::Display for VectorError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 Self::InvalidCanvas { width, height, dpi } => write!(
101 f,
102 "invalid page {width} x {height} at {dpi} dpi: all must be positive"
103 ),
104 Self::Font(err) => write!(f, "cannot embed font: {err}"),
105 Self::Image(err) => write!(f, "cannot encode image: {err}"),
106 Self::NonFinite(what) => write!(f, "cannot write a non-finite {what}"),
107 Self::Unsupported(what) => f.write_str(what),
108 Self::StreamedImage => f.write_str(
109 "streamed pgf-code does not support raster graphics, consider using the \
110 pgf-to-pdf option",
111 ),
112 Self::Tex(err) => write!(f, "cannot draw TeX text: {err}"),
113 Self::UnwrittenObject(id) => {
114 write!(f, "PDF object {id} was reserved but never written")
115 }
116 Self::StreamOpen => f.write_str("a PDF stream is open already"),
117 Self::OutOfMemory(err) => write!(f, "cannot write the document: {err}"),
118 }
119 }
120}
121
122impl std::error::Error for VectorError {
123 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
124 match self {
125 Self::Font(err) => Some(err),
126 Self::Image(err) => Some(err),
127 Self::Tex(err) => Some(err),
128 Self::OutOfMemory(err) => Some(err),
129 Self::InvalidCanvas { .. }
130 | Self::NonFinite(_)
131 | Self::Unsupported(_)
132 | Self::StreamedImage
133 | Self::UnwrittenObject(_)
134 | Self::StreamOpen => None,
135 }
136 }
137}
138
139impl From<TextError> for VectorError {
140 fn from(err: TextError) -> Self {
141 Self::Font(err)
142 }
143}
144
145impl From<TexError> for VectorError {
146 fn from(err: TexError) -> Self {
147 Self::Tex(err)
148 }
149}
150
151impl From<OutOfMemory> for VectorError {
152 fn from(err: OutOfMemory) -> Self {
153 Self::OutOfMemory(err)
154 }
155}
156
157impl From<EncodeError> for VectorError {
158 fn from(err: EncodeError) -> Self {
159 Self::Image(err)
160 }
161}
162
163pub(crate) fn check_canvas(width: f64, height: f64, dpi: f64) -> Result<(), VectorError> {
165 let valid = |v: f64| v.is_finite() && v > 0.0;
166 if valid(width) && valid(height) && valid(dpi) {
167 Ok(())
168 } else {
169 Err(VectorError::InvalidCanvas { width, height, dpi })
170 }
171}
172
173#[derive(Debug, Default)]
175pub(crate) struct Problems(Option<VectorError>);
176
177impl Problems {
178 pub(crate) fn record<T>(&mut self, result: Result<T, VectorError>) -> Option<T> {
180 match result {
181 Ok(value) => Some(value),
182 Err(err) => {
183 self.0.get_or_insert(err);
184 None
185 }
186 }
187 }
188
189 pub(crate) fn into_result<T>(self, value: T) -> Result<T, VectorError> {
191 self.0.map_or(Ok(value), Err)
192 }
193}
194
195pub(crate) fn segment_ends(path: &Path, transform: Affine2D, clip: Option<Bbox>) -> Vec<Point> {
199 segment_points(path, transform, clip, false)
200}
201
202pub(crate) fn segment_starts(path: &Path, transform: Affine2D, clip: Option<Bbox>) -> Vec<Point> {
205 segment_points(path, transform, clip, true)
206}
207
208fn segment_points(path: &Path, transform: Affine2D, clip: Option<Bbox>, first: bool) -> Vec<Point> {
210 let mut stream = path
211 .iter_vertices()
212 .transform(transform)
213 .remove_nans(true, path.codes().is_some())
214 .clip_to(clip);
215 let mut points = Vec::new();
216 while let Some(vertex) = stream.next() {
217 let mut point = vertex.point;
218 for _ in 1..vertex.code.vertex_count() {
219 if let Some(next) = stream.next()
220 && !first
221 {
222 point = next.point;
223 }
224 }
225 points.push(point);
226 }
227 points
228}
229
230pub fn gzip(data: &[u8]) -> Result<Vec<u8>, OutOfMemory> {
237 let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 2, 255];
240 pltrs_codec::deflate::compress_into(data, CompressionLevel::BEST, &mut out)?;
241 alloc::try_reserve(&mut out, 8)?;
242 out.extend_from_slice(&crc32(data).to_le_bytes());
243 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
244 Ok(out)
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn gzip_members_round_trip() {
253 let data = b"<svg/>\n".repeat(20);
254 let member = gzip(&data).unwrap();
255 assert_eq!(&member[..3], &[0x1f, 0x8b, 8]);
256 let body = &member[10..member.len() - 8];
257 assert_eq!(pltrs_codec::deflate::decompress(body).unwrap(), data);
258 assert_eq!(
259 member[member.len() - 4..],
260 (data.len() as u32).to_le_bytes()
261 );
262 }
263
264 #[test]
265 fn segment_ends_skip_nans_and_clip() {
266 let path = Path::polyline(vec![
267 Point::new(1.0, 1.0),
268 Point::new(f64::NAN, 2.0),
269 Point::new(3.0, 3.0),
270 Point::new(50.0, 3.0),
271 ]);
272 let clip = Bbox::from_extents(0.0, 0.0, 10.0, 10.0);
273 let ends = segment_ends(&path, Affine2D::scaling(2.0, 1.0), Some(clip));
274 assert_eq!(ends[0], Point::new(2.0, 1.0));
275 assert_eq!(ends[1], Point::new(6.0, 3.0));
276 assert_eq!(ends.last().map(|p| p.x), Some(11.0), "clipped one unit out");
277 }
278
279 #[test]
280 fn canvas_validation_and_problems() {
281 assert!(check_canvas(10.0, 10.0, 72.0).is_ok());
282 assert!(matches!(
283 check_canvas(0.0, 10.0, 72.0),
284 Err(VectorError::InvalidCanvas { .. })
285 ));
286 let mut problems = Problems::default();
287 assert_eq!(problems.record(Ok::<_, VectorError>(3)), Some(3));
288 assert_eq!(
289 problems.record(Err::<(), _>(VectorError::NonFinite("x"))),
290 None
291 );
292 assert!(problems.into_result(()).is_err());
293 }
294}