pub mod arrows;
pub mod coord;
pub mod decorate;
pub mod math;
pub mod options;
pub mod path;
pub mod render;
pub mod scan;
pub mod shading;
pub mod shapes;
pub mod units;
use crate::colour::{Colours, Rgb};
pub use options::{Anchor, Cap, Decoration, Join, Shade, Shading, Shape, Style, Tip, Transform};
pub use scan::Action;
pub use shading::Ramp;
pub use shapes::Border;
pub type Point = (f64, f64);
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Segment {
Line(Point),
Curve(Point, Point, Point),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Path {
pub points: Vec<Point>,
pub start: Point,
pub segments: Vec<Segment>,
pub closed: bool,
pub width: f64,
pub group: usize,
pub action: Action,
pub stroke: Rgb,
pub fill: Rgb,
pub draw: bool,
pub filled: bool,
pub even_odd: bool,
pub dash: Vec<f64>,
pub cap: Cap,
pub join: Join,
pub draw_opacity: f64,
pub fill_opacity: f64,
pub arrow_start: Option<Tip>,
pub arrow_end: Option<Tip>,
pub rounded: f64,
pub shade: Option<Shade>,
}
impl Path {
pub fn anchor_points(&self, pic: &Picture, ox: f64, oy: f64) -> Vec<Point> {
self.points
.iter()
.map(|(x, y)| (ox + x * pic.x_scale, oy + y * pic.y_scale))
.collect()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub name: Option<String>,
pub at: Point,
pub text: String,
pub anchor: Anchor,
pub shape: Shape,
pub measured: (f64, f64, f64),
pub inner_sep: (f64, f64),
pub outer_sep: f64,
pub minimum: (f64, f64),
pub aspect: f64,
pub font_size: f64,
pub stroke: Rgb,
pub fill: Rgb,
pub text_colour: Rgb,
pub draw: bool,
pub filled: bool,
pub width: f64,
}
impl Node {
pub fn text_half(&self) -> (f64, f64) {
let (width, height, depth) = self.measured;
(
width / 2.0 + self.inner_sep.0,
(height + depth) / 2.0 + self.inner_sep.1,
)
}
pub fn border(&self) -> Border {
Border::of(
self.shape,
self.text_half(),
self.minimum,
self.outer_sep,
self.aspect,
)
}
pub fn half_size(&self) -> (f64, f64) {
self.border().half
}
pub fn centre(&self, at: Point) -> Point {
let (dx, dy) = self.border().anchor(self.anchor);
(at.0 - dx, at.1 - dy)
}
pub fn baseline_drop(&self) -> f64 {
let (_, height, depth) = self.measured;
(height - depth) / 2.0
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Picture {
pub paths: Vec<Path>,
pub nodes: Vec<Node>,
pub x_scale: f64,
pub y_scale: f64,
}
impl Default for Picture {
fn default() -> Picture {
Picture {
paths: Vec::new(),
nodes: Vec::new(),
x_scale: 1.0,
y_scale: 1.0,
}
}
}
impl Picture {
pub fn size(&self) -> (f64, f64) {
let mut w: f64 = 0.0;
let mut h: f64 = 0.0;
for p in &self.paths {
for (x, y) in &p.points {
w = w.max(x * self.x_scale);
h = h.max(y * self.y_scale);
}
}
(w, h)
}
pub fn bounds(&self) -> (f64, f64, f64, f64) {
let mut min = (f64::INFINITY, f64::INFINITY);
let mut max = (f64::NEG_INFINITY, f64::NEG_INFINITY);
let mut seen = false;
let mut widen = |(x, y): Point, pad: f64| {
seen = true;
min = (min.0.min(x - pad), min.1.min(y - pad));
max = (max.0.max(x + pad), max.1.max(y + pad));
};
for path in &self.paths {
let place = |(x, y): Point| (x * self.x_scale, y * self.y_scale);
let half = match path.draw {
true => path.width / 2.0,
false => 0.0,
};
widen(place(path.start), half);
for segment in &path.segments {
match segment {
Segment::Line(to) => widen(place(*to), half),
Segment::Curve(a, b, to) => {
widen(place(*a), half);
widen(place(*b), half);
widen(place(*to), half);
}
}
}
}
for node in &self.nodes {
let at = (node.at.0 * self.x_scale, node.at.1 * self.y_scale);
let (cx, cy) = node.centre(at);
let (hx, hy) = node.half_size();
widen((cx - hx, cy - hy), 0.0);
widen((cx + hx, cy + hy), 0.0);
}
match seen {
true => (min.0, min.1, max.0, max.1),
false => (0.0, 0.0, 0.0, 0.0),
}
}
pub fn extent(&self) -> (f64, f64) {
let (min_x, min_y, max_x, max_y) = self.bounds();
(max_x - min_x, max_y - min_y)
}
pub fn ext_gstates(&self) -> Vec<(String, &'static str, f64)> {
let mut out: Vec<(String, &'static str, f64)> = Vec::new();
for path in &self.paths {
for (alpha, key, prefix) in [
(path.draw_opacity, "CA", "pgf@CA"),
(path.fill_opacity, "ca", "pgf@ca"),
] {
if alpha == 1.0 {
continue;
}
let name = format!("{prefix}{}", render::number(alpha));
if !out.iter().any(|(existing, _, _)| existing == &name) {
out.push((name, key, alpha));
}
}
}
out
}
pub fn shades(&self) -> Vec<Shade> {
let mut out: Vec<Shade> = Vec::new();
for path in &self.paths {
if let Some(shade) = path.shade {
if !out.contains(&shade) {
out.push(shade);
}
}
}
out
}
pub fn shadings(&self) -> Vec<Ramp> {
self.shades()
.iter()
.enumerate()
.map(|(at, shade)| Ramp::of(shade, &format!("pgfsh{at}")))
.collect()
}
}
pub trait Metrics {
fn width_of(&self, text: &str, size: f64) -> f64;
fn height_of(&self, _text: &str, size: f64) -> (f64, f64) {
(0.7 * size, 0.2 * size)
}
}
pub struct Estimate;
impl Metrics for Estimate {
fn width_of(&self, text: &str, size: f64) -> f64 {
text.chars().count() as f64 * 0.5 * size
}
}
impl Metrics for crate::typeset::FontChain {
fn width_of(&self, text: &str, size: f64) -> f64 {
crate::typeset::FontChain::width_of(self, text, size)
}
}
pub fn parse(options: &str, body: &str) -> Picture {
parse_with(options, body, Colours::predefined(), &Estimate)
}
pub const UNIT: f64 = 72.27 / 2.54;
pub fn parse_with(options: &str, body: &str, colours: &Colours, metrics: &dyn Metrics) -> Picture {
parse_units(options, body, colours, metrics, 1.0)
}
pub fn parse_document(
options: &str,
body: &str,
colours: &Colours,
metrics: &dyn Metrics,
) -> Picture {
parse_units(options, body, colours, metrics, UNIT)
}
fn parse_units(
options: &str,
body: &str,
colours: &Colours,
metrics: &dyn Metrics,
unit: f64,
) -> Picture {
let mut pic = Picture {
x_scale: option_length(options, "x").unwrap_or(unit),
y_scale: option_length(options, "y").unwrap_or(unit),
..Picture::default()
};
let base = Style::default().with(options, colours);
let mut frame = coord::Frame::new(pic.x_scale, pic.y_scale);
let mut group = 0usize;
walk(
&scan::commands(body),
&base,
colours,
metrics,
&mut frame,
&mut pic,
&mut group,
);
pic
}
fn option_length(options: &str, key: &str) -> Option<f64> {
options::split(options)
.into_iter()
.filter_map(|option| option.split_once('='))
.find(|(name, _)| name.trim() == key)
.and_then(|(_, value)| units::dimension(value.trim()))
}
fn walk(
chunks: &[scan::Chunk],
base: &Style,
colours: &Colours,
metrics: &dyn Metrics,
frame: &mut coord::Frame,
pic: &mut Picture,
group: &mut usize,
) {
for chunk in chunks {
match chunk {
scan::Chunk::Scope { options, body } => {
let inner = base.with(options, colours);
walk(
&scan::commands(body),
&inner,
colours,
metrics,
frame,
pic,
group,
);
}
scan::Chunk::Path {
action,
options,
body,
} => {
let style = base.with(options, colours);
frame.current = (0.0, 0.0);
frame.relative = (0.0, 0.0);
frame.last_move = (0.0, 0.0);
let built = path::build(body, frame);
emit(&built, *action, &style, metrics, frame, pic, group);
}
}
}
}
fn emit(
built: &path::Built,
action: Action,
style: &Style,
metrics: &dyn Metrics,
frame: &mut coord::Frame,
pic: &mut Picture,
group: &mut usize,
) {
let (draw, filled) = match action {
Action::Draw => (true, style.filled),
Action::Fill => (style.draw, true),
Action::FillDraw => (true, true),
Action::ShadeDraw => (true, style.filled),
Action::None | Action::Shade | Action::Clip | Action::Node => (style.draw, style.filled),
};
let filled = filled && !style.pattern;
let action = match (action, draw, filled) {
(Action::None, true, true) => Action::FillDraw,
(Action::None, true, false) => Action::Draw,
(Action::None, false, true) => Action::Fill,
(Action::Draw, true, true) => Action::FillDraw,
(Action::Fill | Action::FillDraw, true, false) => Action::Draw,
(Action::Fill | Action::FillDraw, false, false) => Action::None,
(other, _, _) => other,
};
let point = |p: Point| style.transform.apply(p);
for sub in &built.subpaths {
let sub = match (style.decorate, style.decoration) {
(true, Some(decoration)) => decorate::apply(
sub,
decoration,
style.segment_length,
style.amplitude,
style.decoration_aspect,
),
_ => sub.clone(),
};
let sub = ⊂
pic.paths.push(Path {
points: sub.anchors().into_iter().map(point).collect(),
start: point(sub.start),
segments: sub
.segments
.iter()
.map(|segment| match segment {
Segment::Line(to) => Segment::Line(point(*to)),
Segment::Curve(a, b, to) => Segment::Curve(point(*a), point(*b), point(*to)),
})
.collect(),
closed: sub.closed,
width: style.width,
group: *group,
action,
stroke: style.stroke,
fill: style.fill,
draw,
filled,
even_odd: style.even_odd,
dash: style.dash.clone(),
cap: style.cap,
join: style.join,
draw_opacity: style.draw_opacity,
fill_opacity: style.fill_opacity,
arrow_start: style.arrow_start,
arrow_end: style.arrow_end,
rounded: style.rounded,
shade: match (action, style.shade) {
(_, Some(shade)) => Some(shade),
(Action::Shade | Action::ShadeDraw, None) => Some(Shade::default()),
_ => None,
},
});
}
for pending in &built.nodes {
let node_style = match pending.options.is_empty() {
true => style.clone(),
false => style.with(&pending.options, Colours::predefined()),
};
let node = measure(
&pending.text,
pending.name.clone(),
point(pending.at),
&node_style,
metrics,
);
let (x_scale, y_scale) = (frame.x_scale, frame.y_scale);
let unscale = |value: f64, scale: f64| match scale != 0.0 {
true => value / scale,
false => value,
};
let across = |(dx, dy): Point| (unscale(dx, x_scale), unscale(dy, y_scale));
let (adx, ady) = across(node.border().anchor(node.anchor));
let centre = (node.at.0 - adx, node.at.1 - ady);
if let Some(name) = &node.name {
frame.named.insert(
name.clone(),
coord::Placed {
at: centre,
border: node.border(),
},
);
}
if let Some((degrees, text)) = &node_style.label {
let mut label = measure(text, None, (0.0, 0.0), &node_style, metrics);
label.draw = false;
label.filled = false;
label.shape = Shape::Rectangle;
label.anchor = Anchor::Center;
let (dx, dy) = node.border().border_at(*degrees);
let reach = dx.hypot(dy) + node_style.label_distance;
let (sin, cos) = degrees.to_radians().sin_cos();
let (ox, oy) = label.border().border_at(degrees + 180.0);
let (lx, ly) = across((reach * cos - ox, reach * sin - oy));
label.at = (centre.0 + lx, centre.1 + ly);
pic.nodes.push(label);
}
pic.nodes.push(node);
}
*group += 1;
}
fn measure(
text: &str,
name: Option<String>,
at: Point,
style: &Style,
metrics: &dyn Metrics,
) -> Node {
let (height, depth) = metrics.height_of(text, style.font_size);
Node {
name,
at,
text: text.to_string(),
anchor: style.anchor,
shape: style.shape,
measured: (metrics.width_of(text, style.font_size), height, depth),
inner_sep: style.inner_sep,
outer_sep: style.outer(),
minimum: style.minimum,
aspect: style.aspect,
font_size: style.font_size,
stroke: style.stroke,
fill: style.fill,
text_colour: style.text,
draw: style.draw,
filled: style.filled,
width: style.width,
}
}
pub fn to_pdf_ops(pic: &Picture, ox: f64, oy: f64) -> String {
render::to_pdf_ops(pic, ox, oy)
}
pub fn draw_on(
pic: &Picture,
page: &mut crate::pdf::Page,
ox: f64,
oy: f64,
font: impl Into<std::sync::Arc<crate::pdf::Font>>,
) {
let font = font.into();
page.content
.push_str(&render::to_pdf_ops_where(pic, ox, oy, true));
for ramp in pic.shadings() {
page.shading(&ramp.name, &ramp.dictionary());
}
for (name, key, alpha) in pic.ext_gstates() {
page.ext_gstate(&name, key, alpha);
}
for node in &pic.nodes {
if node.text.trim().is_empty() {
continue;
}
let (ax, ay) = (ox + node.at.0 * pic.x_scale, oy + node.at.1 * pic.y_scale);
let (dx, dy) = node.border().anchor(node.anchor);
let (cx, cy) = (ax - dx, ay - dy);
page.text_in(
font.clone(),
node.font_size,
cx - node.measured.0 / 2.0,
cy - node.baseline_drop(),
&node.text,
);
}
}