1mod defs;
13mod draw;
14mod gouraud;
15mod metadata;
16mod style;
17mod tex;
18mod text;
19mod text_elements;
20mod xml;
21
22use std::collections::{HashMap, HashSet};
23use std::fmt;
24use std::str::FromStr;
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::time::{SystemTime, UNIX_EPOCH};
27
28use pltrs_codec::sha256::sha256_hex;
29use pltrs_core::path::convert::SimplifySettings;
30use pltrs_core::{Affine2D, Path, Point, Rgba};
31use pltrs_text::TextRun;
32use pltrs_text::tex::{TexError, TexText};
33
34use self::defs::{Clips, Hatches};
35pub use self::xml::{Attribute, XmlWriter};
36use crate::collection::PathCollection;
37use crate::gc::GraphicsContext;
38use crate::image::RgbaImage;
39use crate::renderer::Renderer;
40use crate::vector::{FontCache, Metadata, Problems, VectorError, check_canvas, short};
41
42pub const PROLOG: &str = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n\
45<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n \
46\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50pub enum SvgFontType {
51 #[default]
53 Path,
54 None,
56}
57
58pltrs_core::archive_enum!(SvgFontType { Path, None });
59
60impl SvgFontType {
61 pub const fn name(self) -> &'static str {
63 match self {
64 Self::Path => "path",
65 Self::None => "none",
66 }
67 }
68}
69
70impl fmt::Display for SvgFontType {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(self.name())
73 }
74}
75
76impl FromStr for SvgFontType {
77 type Err = UnknownSvgFontType;
78
79 fn from_str(name: &str) -> Result<Self, UnknownSvgFontType> {
81 [Self::Path, Self::None]
82 .into_iter()
83 .find(|fonttype| fonttype.name() == name)
84 .ok_or_else(|| UnknownSvgFontType(name.to_owned()))
85 }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct UnknownSvgFontType(pub String);
91
92impl fmt::Display for UnknownSvgFontType {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 write!(f, "{:?} is not a valid SVG font type", self.0)
95 }
96}
97
98impl std::error::Error for UnknownSvgFontType {}
99
100#[derive(Clone, Debug, PartialEq)]
103pub struct SvgOptions {
104 pub hashsalt: Option<String>,
108 pub id: Option<String>,
110 pub metadata: Metadata,
112 pub simplify: SimplifySettings,
114 pub composite_images: bool,
117 pub fonttype: SvgFontType,
119 pub image_files: Option<String>,
123}
124
125#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct ImageFile {
129 pub name: String,
131 pub png: Vec<u8>,
133}
134
135impl Default for SvgOptions {
136 fn default() -> Self {
137 Self {
138 hashsalt: None,
139 id: None,
140 metadata: Metadata::default(),
141 simplify: SimplifySettings::default(),
142 composite_images: true,
143 fonttype: SvgFontType::Path,
144 image_files: None,
145 }
146 }
147}
148
149#[derive(Debug)]
154pub struct SvgRenderer {
155 width: f64,
156 height: f64,
157 image_dpi: f64,
158 writer: XmlWriter,
159 root: usize,
160 salt: String,
161 options: SvgOptions,
162 groups: HashMap<String, usize>,
163 clips: Clips,
164 hatches: Hatches,
165 markers: HashMap<(String, String), String>,
166 path_collection_id: usize,
167 has_gouraud: bool,
168 gradients: usize,
169 glyphs: HashSet<String>,
170 fonts: FontCache,
171 images: Vec<ImageFile>,
173 problems: Problems,
174}
175
176impl SvgRenderer {
177 pub fn new(
180 width: f64,
181 height: f64,
182 image_dpi: f64,
183 options: SvgOptions,
184 ) -> Result<Self, VectorError> {
185 check_canvas(width, height, image_dpi)?;
186 let salt = options.hashsalt.clone().unwrap_or_else(fresh_salt);
187 let mut writer = XmlWriter::new(PROLOG);
188 let (w, h) = (short(width), short(height));
189 let root = writer.start(
190 "svg",
191 &[
192 ("xmlns:xlink", "http://www.w3.org/1999/xlink".to_owned()),
193 ("width", format!("{w}pt")),
194 ("height", format!("{h}pt")),
195 ("viewBox", format!("0 0 {w} {h}")),
196 ("xmlns", "http://www.w3.org/2000/svg".to_owned()),
197 ("version", "1.1".to_owned()),
198 ("id", options.id.clone().unwrap_or_default()),
199 ],
200 );
201 metadata::write(&mut writer, &options.metadata);
202 writer.start("defs", &[]);
203 writer.element(
204 "style",
205 "*{stroke-linejoin: round; stroke-linecap: butt}",
206 &[("type", "text/css".to_owned())],
207 );
208 writer.end(true);
209 Ok(Self {
210 width,
211 height,
212 image_dpi,
213 writer,
214 root,
215 salt,
216 options,
217 groups: HashMap::new(),
218 clips: Clips::default(),
219 hatches: Hatches::default(),
220 markers: HashMap::new(),
221 path_collection_id: 0,
222 has_gouraud: false,
223 gradients: 0,
224 glyphs: HashSet::new(),
225 fonts: FontCache::default(),
226 images: Vec::new(),
227 problems: Problems::default(),
228 })
229 }
230
231 pub fn finish(self) -> Result<String, VectorError> {
238 self.finish_with_images().map(|(document, _)| document)
239 }
240
241 pub fn finish_with_images(mut self) -> Result<(String, Vec<ImageFile>), VectorError> {
248 self.clips.write(&mut self.writer);
249 self.hatches.write(&mut self.writer);
250 self.writer.close(self.root);
251 let images = std::mem::take(&mut self.images);
252 self.problems
253 .into_result(self.writer.into_string())
254 .map(|document| (document, images))
255 }
256
257 fn make_id(&self, kind: &str, content: &str) -> String {
260 let digest = sha256_hex(format!("{}{content}", self.salt).as_bytes());
261 format!("{kind}{}", &digest[..10])
262 }
263
264 fn flip(&self) -> Affine2D {
266 Affine2D::scaling(1.0, -1.0).translate(0.0, self.height)
267 }
268
269 fn open_link(&mut self, gc: &GraphicsContext) -> bool {
271 let Some(url) = gc.url.clone() else {
272 return false;
273 };
274 self.writer
275 .start("a", &[("xlink:href", url), ("target", "_blank".to_owned())]);
276 true
277 }
278
279 fn close_link(&mut self, opened: bool) {
281 if opened {
282 self.writer.end(true);
283 }
284 }
285}
286
287impl Renderer for SvgRenderer {
288 fn canvas_size(&self) -> (f64, f64) {
289 (self.width, self.height)
290 }
291
292 fn dpi(&self) -> f64 {
294 self.image_dpi
295 }
296
297 fn points_to_pixels(&self, points: f64) -> f64 {
299 points
300 }
301
302 fn draw_path(
303 &mut self,
304 gc: &GraphicsContext,
305 path: &Path,
306 transform: &Affine2D,
307 fill: Option<Rgba>,
308 ) {
309 self.svg_path(gc, path, *transform, fill);
310 }
311
312 fn draw_markers(
313 &mut self,
314 gc: &GraphicsContext,
315 marker: &Path,
316 marker_transform: &Affine2D,
317 path: &Path,
318 transform: &Affine2D,
319 fill: Option<Rgba>,
320 ) {
321 self.svg_markers(gc, marker, *marker_transform, path, *transform, fill);
322 }
323
324 fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
325 self.svg_path_collection(gc, collection);
326 }
327
328 fn draw_gouraud_triangles(
329 &mut self,
330 gc: &GraphicsContext,
331 triangles: &[[Point; 3]],
332 colors: &[[Rgba; 3]],
333 transform: &Affine2D,
334 ) {
335 self.svg_gouraud_triangles(gc, triangles, colors, *transform);
336 }
337
338 fn draw_image(
339 &mut self,
340 gc: &GraphicsContext,
341 origin: Point,
342 image: &RgbaImage,
343 transform: Option<&Affine2D>,
344 ) {
345 self.svg_image(gc, origin, image, transform.copied());
346 }
347
348 fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
349 self.svg_text(gc, run, origin, angle);
350 }
351
352 fn draw_tex(
353 &mut self,
354 gc: &GraphicsContext,
355 _run: &TextRun,
356 tex: &TexText,
357 origin: Point,
358 angle: f64,
359 ) -> Result<(), TexError> {
360 self.svg_tex(gc, tex, origin, angle)
361 }
362
363 fn open_group(&mut self, name: &str, gid: Option<&str>) {
364 let id = gid.filter(|g| !g.is_empty()).map_or_else(
365 || {
366 let count = self.groups.entry(name.to_owned()).or_insert(0);
367 *count += 1;
368 format!("{name}_{count}")
369 },
370 str::to_owned,
371 );
372 self.writer.start("g", &[("id", id)]);
373 }
374
375 fn close_group(&mut self, _name: &str) {
376 self.writer.end(true);
377 }
378
379 fn option_image_nocomposite(&self) -> bool {
380 !self.options.composite_images
381 }
382
383 fn option_scale_image(&self) -> bool {
384 true
385 }
386
387 fn image_magnification(&self) -> f64 {
388 self.image_dpi / 72.0
389 }
390}
391
392fn fresh_salt() -> String {
396 static SALTED: AtomicU64 = AtomicU64::new(0);
397 let nanos = SystemTime::now()
398 .duration_since(UNIX_EPOCH)
399 .map_or(0, |elapsed| elapsed.as_nanos());
400 format!(
401 "pltrs-{nanos}-{}-{}",
402 std::process::id(),
403 SALTED.fetch_add(1, Ordering::Relaxed)
404 )
405}
406
407#[cfg(test)]
408mod tests;