mod defs;
mod draw;
mod gouraud;
mod metadata;
mod style;
mod tex;
mod text;
mod text_elements;
mod xml;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use pltrs_codec::sha256::sha256_hex;
use pltrs_core::path::convert::SimplifySettings;
use pltrs_core::{Affine2D, Path, Point, Rgba};
use pltrs_text::TextRun;
use pltrs_text::tex::{TexError, TexText};
use self::defs::{Clips, Hatches};
pub use self::xml::{Attribute, XmlWriter};
use crate::collection::PathCollection;
use crate::gc::GraphicsContext;
use crate::image::RgbaImage;
use crate::renderer::Renderer;
use crate::vector::{FontCache, Metadata, Problems, VectorError, check_canvas, short};
pub const PROLOG: &str = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n\
<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n \
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SvgFontType {
#[default]
Path,
None,
}
pltrs_core::archive_enum!(SvgFontType { Path, None });
impl SvgFontType {
pub const fn name(self) -> &'static str {
match self {
Self::Path => "path",
Self::None => "none",
}
}
}
impl fmt::Display for SvgFontType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl FromStr for SvgFontType {
type Err = UnknownSvgFontType;
fn from_str(name: &str) -> Result<Self, UnknownSvgFontType> {
[Self::Path, Self::None]
.into_iter()
.find(|fonttype| fonttype.name() == name)
.ok_or_else(|| UnknownSvgFontType(name.to_owned()))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnknownSvgFontType(pub String);
impl fmt::Display for UnknownSvgFontType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?} is not a valid SVG font type", self.0)
}
}
impl std::error::Error for UnknownSvgFontType {}
#[derive(Clone, Debug, PartialEq)]
pub struct SvgOptions {
pub hashsalt: Option<String>,
pub id: Option<String>,
pub metadata: Metadata,
pub simplify: SimplifySettings,
pub composite_images: bool,
pub fonttype: SvgFontType,
pub image_files: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageFile {
pub name: String,
pub png: Vec<u8>,
}
impl Default for SvgOptions {
fn default() -> Self {
Self {
hashsalt: None,
id: None,
metadata: Metadata::default(),
simplify: SimplifySettings::default(),
composite_images: true,
fonttype: SvgFontType::Path,
image_files: None,
}
}
}
#[derive(Debug)]
pub struct SvgRenderer {
width: f64,
height: f64,
image_dpi: f64,
writer: XmlWriter,
root: usize,
salt: String,
options: SvgOptions,
groups: HashMap<String, usize>,
clips: Clips,
hatches: Hatches,
markers: HashMap<(String, String), String>,
path_collection_id: usize,
has_gouraud: bool,
gradients: usize,
glyphs: HashSet<String>,
fonts: FontCache,
images: Vec<ImageFile>,
problems: Problems,
}
impl SvgRenderer {
pub fn new(
width: f64,
height: f64,
image_dpi: f64,
options: SvgOptions,
) -> Result<Self, VectorError> {
check_canvas(width, height, image_dpi)?;
let salt = options.hashsalt.clone().unwrap_or_else(fresh_salt);
let mut writer = XmlWriter::new(PROLOG);
let (w, h) = (short(width), short(height));
let root = writer.start(
"svg",
&[
("xmlns:xlink", "http://www.w3.org/1999/xlink".to_owned()),
("width", format!("{w}pt")),
("height", format!("{h}pt")),
("viewBox", format!("0 0 {w} {h}")),
("xmlns", "http://www.w3.org/2000/svg".to_owned()),
("version", "1.1".to_owned()),
("id", options.id.clone().unwrap_or_default()),
],
);
metadata::write(&mut writer, &options.metadata);
writer.start("defs", &[]);
writer.element(
"style",
"*{stroke-linejoin: round; stroke-linecap: butt}",
&[("type", "text/css".to_owned())],
);
writer.end(true);
Ok(Self {
width,
height,
image_dpi,
writer,
root,
salt,
options,
groups: HashMap::new(),
clips: Clips::default(),
hatches: Hatches::default(),
markers: HashMap::new(),
path_collection_id: 0,
has_gouraud: false,
gradients: 0,
glyphs: HashSet::new(),
fonts: FontCache::default(),
images: Vec::new(),
problems: Problems::default(),
})
}
pub fn finish(self) -> Result<String, VectorError> {
self.finish_with_images().map(|(document, _)| document)
}
pub fn finish_with_images(mut self) -> Result<(String, Vec<ImageFile>), VectorError> {
self.clips.write(&mut self.writer);
self.hatches.write(&mut self.writer);
self.writer.close(self.root);
let images = std::mem::take(&mut self.images);
self.problems
.into_result(self.writer.into_string())
.map(|document| (document, images))
}
fn make_id(&self, kind: &str, content: &str) -> String {
let digest = sha256_hex(format!("{}{content}", self.salt).as_bytes());
format!("{kind}{}", &digest[..10])
}
fn flip(&self) -> Affine2D {
Affine2D::scaling(1.0, -1.0).translate(0.0, self.height)
}
fn open_link(&mut self, gc: &GraphicsContext) -> bool {
let Some(url) = gc.url.clone() else {
return false;
};
self.writer
.start("a", &[("xlink:href", url), ("target", "_blank".to_owned())]);
true
}
fn close_link(&mut self, opened: bool) {
if opened {
self.writer.end(true);
}
}
}
impl Renderer for SvgRenderer {
fn canvas_size(&self) -> (f64, f64) {
(self.width, self.height)
}
fn dpi(&self) -> f64 {
self.image_dpi
}
fn points_to_pixels(&self, points: f64) -> f64 {
points
}
fn draw_path(
&mut self,
gc: &GraphicsContext,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.svg_path(gc, path, *transform, fill);
}
fn draw_markers(
&mut self,
gc: &GraphicsContext,
marker: &Path,
marker_transform: &Affine2D,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.svg_markers(gc, marker, *marker_transform, path, *transform, fill);
}
fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
self.svg_path_collection(gc, collection);
}
fn draw_gouraud_triangles(
&mut self,
gc: &GraphicsContext,
triangles: &[[Point; 3]],
colors: &[[Rgba; 3]],
transform: &Affine2D,
) {
self.svg_gouraud_triangles(gc, triangles, colors, *transform);
}
fn draw_image(
&mut self,
gc: &GraphicsContext,
origin: Point,
image: &RgbaImage,
transform: Option<&Affine2D>,
) {
self.svg_image(gc, origin, image, transform.copied());
}
fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
self.svg_text(gc, run, origin, angle);
}
fn draw_tex(
&mut self,
gc: &GraphicsContext,
_run: &TextRun,
tex: &TexText,
origin: Point,
angle: f64,
) -> Result<(), TexError> {
self.svg_tex(gc, tex, origin, angle)
}
fn open_group(&mut self, name: &str, gid: Option<&str>) {
let id = gid.filter(|g| !g.is_empty()).map_or_else(
|| {
let count = self.groups.entry(name.to_owned()).or_insert(0);
*count += 1;
format!("{name}_{count}")
},
str::to_owned,
);
self.writer.start("g", &[("id", id)]);
}
fn close_group(&mut self, _name: &str) {
self.writer.end(true);
}
fn option_image_nocomposite(&self) -> bool {
!self.options.composite_images
}
fn option_scale_image(&self) -> bool {
true
}
fn image_magnification(&self) -> f64 {
self.image_dpi / 72.0
}
}
fn fresh_salt() -> String {
static SALTED: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos());
format!(
"pltrs-{nanos}-{}-{}",
std::process::id(),
SALTED.fetch_add(1, Ordering::Relaxed)
)
}
#[cfg(test)]
mod tests;