mod path;
mod text;
pub use text::{pgf_text, pgf_unknown_family};
use std::fmt::Write as _;
use pltrs_core::alloc::OutOfMemory;
use pltrs_core::path::convert::SimplifySettings;
use pltrs_core::{Affine2D, Path, Point, Rgba};
use pltrs_text::TextRun;
use pltrs_text::tex::{TexError, TexText};
use crate::gc::GraphicsContext;
use crate::image::RgbaImage;
use crate::renderer::Renderer;
use crate::svg::ImageFile;
use crate::vector::{Problems, VectorError, check_canvas, fixed};
const LATEX_POINTS_PER_INCH: f64 = 72.27;
const POINTS_PER_INCH: f64 = 72.0;
#[derive(Clone, Debug, PartialEq)]
pub struct PgfOptions {
pub simplify: SimplifySettings,
pub composite_images: bool,
pub rcfonts: bool,
pub font_names: Vec<String>,
pub preamble: String,
pub image_stem: Option<String>,
}
impl Default for PgfOptions {
fn default() -> Self {
Self {
simplify: SimplifySettings::default(),
composite_images: true,
rcfonts: true,
font_names: Vec::new(),
preamble: String::new(),
image_stem: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PgfDocument {
pub text: String,
pub images: Vec<ImageFile>,
}
#[derive(Debug)]
pub struct PgfRenderer {
width: f64,
height: f64,
dpi: f64,
options: PgfOptions,
body: String,
images: Vec<ImageFile>,
ignored_fonts: Vec<String>,
problems: Problems,
}
impl PgfRenderer {
pub fn new(
width: f64,
height: f64,
dpi: f64,
options: PgfOptions,
) -> Result<Self, VectorError> {
check_canvas(width, height, dpi)?;
Ok(Self {
width: width * dpi,
height: height * dpi,
dpi,
options,
body: String::new(),
images: Vec::new(),
ignored_fonts: Vec::new(),
problems: Problems::default(),
})
}
pub fn take_body(&mut self) -> (String, Vec<ImageFile>) {
(
std::mem::take(&mut self.body),
std::mem::take(&mut self.images),
)
}
pub fn take_ignored_fonts(&mut self) -> Vec<String> {
std::mem::take(&mut self.ignored_fonts)
}
pub fn finish(self) -> Result<PgfDocument, VectorError> {
let mut text = String::from(HEADER);
text.push_str("%% pltrs used the following preamble\n");
for line in self.options.preamble.lines() {
let _ = writeln!(text, "%% {line}");
}
text.push_str("%%\n");
writeln_pgf(&mut text, r"\begingroup");
writeln_pgf(&mut text, r"\makeatletter");
writeln_pgf(&mut text, r"\begin{pgfpicture}");
writeln_pgf(
&mut text,
&format!(
r"\pgfpathrectangle{{\pgfpointorigin}}{{\pgfqpoint{{{}in}}{{{}in}}}}",
num(self.width / self.dpi),
num(self.height / self.dpi)
),
);
writeln_pgf(&mut text, r"\pgfusepath{use as bounding box, clip}");
if text.try_reserve(self.body.len()).is_err() {
let bytes = text.len().saturating_add(self.body.len());
return Err(OutOfMemory { bytes }.into());
}
text.push_str(&self.body);
writeln_pgf(&mut text, r"\end{pgfpicture}");
writeln_pgf(&mut text, r"\makeatother");
writeln_pgf(&mut text, r"\endgroup");
self.problems.into_result(PgfDocument {
text,
images: self.images,
})
}
fn line(&mut self, line: &str) {
let needed = line.len() + 2;
if self.body.try_reserve(needed).is_err() {
let bytes = self.body.len().saturating_add(needed);
self.problems
.record::<()>(Err(OutOfMemory { bytes }.into()));
return;
}
writeln_pgf(&mut self.body, line);
}
fn inches(&self, pixels: f64) -> f64 {
pixels / self.dpi
}
}
const HEADER: &str = r"%% Creator: pltrs, PGF backend
%%
%% To include the figure in your LaTeX document, write
%% \input{<filename>.pgf}
%%
%% Make sure the required packages are loaded in your preamble
%% \usepackage{pgf}
%%
%% Also ensure that all the required font packages are loaded; for instance,
%% the lmodern package is sometimes necessary when using math font.
%% \usepackage{lmodern}
%%
%% Figures using additional raster images can only be included by \input if
%% they are in the same directory as the main LaTeX file. For loading figures
%% from other directories you can use the `import` package
%% \usepackage{import}
%%
%% and then include the figures with
%% \import{<path to file>}{<filename>.pgf}
%%
";
fn writeln_pgf(out: &mut String, line: &str) {
out.push_str(line);
out.push_str("%\n");
}
fn num(value: f64) -> String {
fixed(value, 6)
}
fn latex_points(points: f64) -> f64 {
points / POINTS_PER_INCH * LATEX_POINTS_PER_INCH
}
impl Renderer for PgfRenderer {
fn canvas_size(&self) -> (f64, f64) {
(self.width, self.height)
}
fn dpi(&self) -> f64 {
self.dpi
}
fn draw_path(
&mut self,
gc: &GraphicsContext,
path: &Path,
transform: &Affine2D,
fill: Option<Rgba>,
) {
self.pgf_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.pgf_markers(gc, marker, marker_transform, path, transform, fill);
}
fn draw_gouraud_triangles(
&mut self,
_gc: &GraphicsContext,
_triangles: &[[Point; 3]],
_colors: &[[Rgba; 3]],
_transform: &Affine2D,
) {
self.problems.record::<()>(Err(VectorError::Unsupported(
"PGF cannot draw Gouraud-shaded triangles",
)));
}
fn draw_image(
&mut self,
gc: &GraphicsContext,
origin: Point,
image: &RgbaImage,
transform: Option<&Affine2D>,
) {
self.pgf_image(gc, origin, image, transform);
}
fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
self.pgf_text(gc, run, origin, angle);
}
fn draw_tex(
&mut self,
gc: &GraphicsContext,
run: &TextRun,
_tex: &TexText,
origin: Point,
angle: f64,
) -> Result<(), TexError> {
self.pgf_text(gc, run, origin, angle);
Ok(())
}
fn option_image_nocomposite(&self) -> bool {
!self.options.composite_images
}
fn option_scale_image(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn documents_hold_one_clipped_picture() {
let renderer = PgfRenderer::new(2.0, 1.0, 100.0, PgfOptions::default()).unwrap();
let document = renderer.finish().unwrap();
assert!(
document
.text
.starts_with("%% Creator: pltrs, PGF backend\n")
);
assert!(document.text.contains(
"\\begin{pgfpicture}%\n\\pgfpathrectangle{\\pgfpointorigin}{\\pgfqpoint{2.000000in}{1.000000in}}%\n\\pgfusepath{use as bounding box, clip}%\n\\end{pgfpicture}%\n"
));
assert!(document.text.ends_with("\\makeatother%\n\\endgroup%\n"));
assert_eq!(document.images, []);
}
#[test]
fn numbers_and_widths() {
assert_eq!(num(1.0 / 3.0), "0.333333");
assert_eq!(num(-0.0), "-0.000000");
assert_eq!(num(1e20), "100000000000000000000.000000");
assert!((latex_points(72.0) - 72.27).abs() < 1e-12);
}
#[test]
fn gouraud_shading_is_an_error() {
let mut renderer = PgfRenderer::new(1.0, 1.0, 72.0, PgfOptions::default()).unwrap();
renderer.draw_gouraud_triangles(
&GraphicsContext::default(),
&[[Point::new(0.0, 0.0); 3]],
&[[Rgba::BLACK; 3]],
&Affine2D::IDENTITY,
);
assert!(matches!(
renderer.finish(),
Err(VectorError::Unsupported(_))
));
}
}