use crate::colour::{Colours, Rgb};
use super::coord;
use super::units;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Cap {
#[default]
Butt,
Round,
Square,
}
impl Cap {
pub fn code(self) -> u8 {
match self {
Cap::Butt => 0,
Cap::Round => 1,
Cap::Square => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Join {
#[default]
Miter,
Round,
Bevel,
}
impl Join {
pub fn code(self) -> u8 {
match self {
Join::Miter => 0,
Join::Round => 1,
Join::Bevel => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tip {
To,
Stealth,
Latex,
}
impl Tip {
fn named(name: &str) -> Option<Tip> {
match name {
">" | "<" | "to" | "To" => Some(Tip::To),
"stealth" | "Stealth" => Some(Tip::Stealth),
"latex" | "Latex" => Some(Tip::Latex),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
pub a: f64,
pub b: f64,
pub c: f64,
pub d: f64,
pub tx: f64,
pub ty: f64,
}
impl Default for Transform {
fn default() -> Transform {
Transform {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
tx: 0.0,
ty: 0.0,
}
}
}
impl Transform {
pub fn apply(&self, (x, y): (f64, f64)) -> (f64, f64) {
(
self.a * x + self.c * y + self.tx,
self.b * x + self.d * y + self.ty,
)
}
pub fn apply_vector(&self, (x, y): (f64, f64)) -> (f64, f64) {
(self.a * x + self.c * y, self.b * x + self.d * y)
}
pub fn then(&self, outer: &Transform) -> Transform {
Transform {
a: outer.a * self.a + outer.c * self.b,
b: outer.b * self.a + outer.d * self.b,
c: outer.a * self.c + outer.c * self.d,
d: outer.b * self.c + outer.d * self.d,
tx: outer.a * self.tx + outer.c * self.ty + outer.tx,
ty: outer.b * self.tx + outer.d * self.ty + outer.ty,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Anchor {
#[default]
Center,
North,
South,
East,
West,
NorthEast,
NorthWest,
SouthEast,
SouthWest,
}
impl Anchor {
pub fn named(name: &str) -> Option<Anchor> {
match name.trim() {
"center" | "centre" => Some(Anchor::Center),
"north" => Some(Anchor::North),
"south" => Some(Anchor::South),
"east" => Some(Anchor::East),
"west" => Some(Anchor::West),
"north east" => Some(Anchor::NorthEast),
"north west" => Some(Anchor::NorthWest),
"south east" => Some(Anchor::SouthEast),
"south west" => Some(Anchor::SouthWest),
_ => None,
}
}
pub fn offset(self) -> (f64, f64) {
match self {
Anchor::Center => (0.0, 0.0),
Anchor::North => (0.0, 1.0),
Anchor::South => (0.0, -1.0),
Anchor::East => (1.0, 0.0),
Anchor::West => (-1.0, 0.0),
Anchor::NorthEast => (1.0, 1.0),
Anchor::NorthWest => (-1.0, 1.0),
Anchor::SouthEast => (1.0, -1.0),
Anchor::SouthWest => (-1.0, -1.0),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Shape {
#[default]
Rectangle,
Circle,
Ellipse,
Diamond,
Coordinate,
}
impl Shape {
pub fn named(name: &str) -> Option<Shape> {
match name.trim() {
"rectangle" => Some(Shape::Rectangle),
"circle" => Some(Shape::Circle),
"ellipse" => Some(Shape::Ellipse),
"diamond" => Some(Shape::Diamond),
"coordinate" => Some(Shape::Coordinate),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Shading {
#[default]
Axis,
Radial,
Ball,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decoration {
Snake,
Zigzag,
Saw,
Brace,
}
impl Decoration {
pub fn named(name: &str) -> Option<Decoration> {
match name.trim() {
"snake" => Some(Decoration::Snake),
"zigzag" => Some(Decoration::Zigzag),
"saw" => Some(Decoration::Saw),
"brace" => Some(Decoration::Brace),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Style {
pub stroke: Rgb,
pub draw: bool,
pub fill: Rgb,
pub filled: bool,
pub width: f64,
pub dash: Vec<f64>,
pub cap: Cap,
pub join: Join,
pub draw_opacity: f64,
pub fill_opacity: f64,
pub even_odd: bool,
pub arrow_start: Option<Tip>,
pub arrow_end: Option<Tip>,
pub transform: Transform,
pub text: Rgb,
pub anchor: Anchor,
pub shape: Shape,
pub inner_sep: (f64, f64),
pub outer_sep: Option<f64>,
pub minimum: (f64, f64),
pub aspect: f64,
pub font_size: f64,
pub rounded: f64,
pub shade: Option<Shade>,
pub decoration: Option<Decoration>,
pub decorate: bool,
pub segment_length: f64,
pub amplitude: f64,
pub decoration_aspect: f64,
pub label: Option<(f64, String)>,
pub label_distance: f64,
pub pattern: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Shade {
pub kind: Shading,
pub angle: f64,
pub top: Rgb,
pub bottom: Rgb,
pub middle: Rgb,
pub middle_set: bool,
pub inner: Rgb,
pub outer: Rgb,
pub ball: Rgb,
}
impl Default for Shade {
fn default() -> Shade {
let gray = (0.5, 0.5, 0.5);
let white = (1.0, 1.0, 1.0);
Shade {
kind: Shading::Axis,
angle: 0.0,
top: gray,
bottom: white,
middle: (0.75, 0.75, 0.75),
middle_set: false,
inner: gray,
outer: white,
ball: (0.0, 0.0, 1.0),
}
}
}
impl Shade {
fn remix(&mut self) {
if !self.middle_set {
self.middle = (
(self.top.0 + self.bottom.0) / 2.0,
(self.top.1 + self.bottom.1) / 2.0,
(self.top.2 + self.bottom.2) / 2.0,
);
}
}
}
impl Default for Style {
fn default() -> Style {
Style {
stroke: (0.0, 0.0, 0.0),
draw: false,
fill: (0.0, 0.0, 0.0),
filled: false,
width: 0.4,
dash: Vec::new(),
cap: Cap::Butt,
join: Join::Miter,
draw_opacity: 1.0,
fill_opacity: 1.0,
even_odd: false,
arrow_start: None,
arrow_end: None,
transform: Transform::default(),
text: (0.0, 0.0, 0.0),
anchor: Anchor::Center,
shape: Shape::Rectangle,
inner_sep: (3.333, 3.333),
outer_sep: None,
minimum: (0.0, 0.0),
aspect: 1.0,
font_size: 10.0,
rounded: 0.0,
shade: None,
decoration: None,
decorate: false,
segment_length: 10.0,
amplitude: 2.5,
decoration_aspect: 0.5,
label: None,
label_distance: 0.0,
pattern: false,
}
}
}
impl Style {
pub fn with(&self, options: &str, colours: &Colours) -> Style {
let mut style = self.clone();
for option in split(options) {
style.apply(option.trim(), colours);
}
style
}
fn apply(&mut self, option: &str, colours: &Colours) {
let (key, value) = match option.split_once('=') {
Some((key, value)) => (key.trim(), strip_braces(value.trim())),
None => (option, ""),
};
match key {
"draw" => match value == "none" {
true => self.draw = false,
false => {
self.draw = true;
if let Some(rgb) = colour(value, colours) {
self.stroke = rgb;
}
}
},
"fill" => match value == "none" {
true => self.filled = false,
false => {
self.filled = true;
if let Some(rgb) = colour(value, colours) {
self.fill = rgb;
}
}
},
"color" | "text" => {
if let Some(rgb) = colour(value, colours) {
self.stroke = rgb;
self.fill = rgb;
self.text = rgb;
}
}
"line width" => {
if let Some(width) = units::dimension(value) {
self.width = width;
}
}
"ultra thin" => self.width = 0.1,
"very thin" => self.width = 0.2,
"thin" => self.width = 0.4,
"semithick" => self.width = 0.6,
"thick" => self.width = 0.8,
"very thick" => self.width = 1.2,
"ultra thick" => self.width = 1.6,
"solid" => self.dash.clear(),
"dotted" => self.dash = vec![self.width, 2.0],
"densely dotted" => self.dash = vec![self.width, 1.0],
"loosely dotted" => self.dash = vec![self.width, 4.0],
"dashed" => self.dash = vec![3.0, 3.0],
"densely dashed" => self.dash = vec![3.0, 2.0],
"loosely dashed" => self.dash = vec![3.0, 6.0],
"dash dot" | "dashdotted" => self.dash = vec![3.0, 2.0, self.width, 2.0],
"densely dash dot" | "densely dashdotted" => {
self.dash = vec![3.0, 1.0, self.width, 1.0]
}
"loosely dash dot" | "loosely dashdotted" => {
self.dash = vec![3.0, 4.0, self.width, 4.0]
}
"dash pattern" => self.dash = dash_pattern(value),
"line cap" => {
self.cap = match value {
"round" => Cap::Round,
"rect" => Cap::Square,
_ => Cap::Butt,
}
}
"line join" => {
self.join = match value {
"round" => Join::Round,
"bevel" => Join::Bevel,
_ => Join::Miter,
}
}
"opacity" => {
if let Some(alpha) = units::number(value) {
self.draw_opacity = alpha;
self.fill_opacity = alpha;
}
}
"draw opacity" => {
if let Some(alpha) = units::number(value) {
self.draw_opacity = alpha;
}
}
"fill opacity" => {
if let Some(alpha) = units::number(value) {
self.fill_opacity = alpha;
}
}
"even odd rule" => self.even_odd = true,
"nonzero rule" => self.even_odd = false,
"rotate" => {
if let Some(degrees) = units::number(value) {
let (sin, cos) = degrees.to_radians().sin_cos();
self.compose(Transform {
a: cos,
b: sin,
c: -sin,
d: cos,
tx: 0.0,
ty: 0.0,
});
}
}
"scale" => {
if let Some(factor) = units::number(value) {
self.compose(Transform {
a: factor,
d: factor,
..Transform::default()
});
}
}
"xscale" => {
if let Some(factor) = units::number(value) {
self.compose(Transform {
a: factor,
..Transform::default()
});
}
}
"yscale" => {
if let Some(factor) = units::number(value) {
self.compose(Transform {
d: factor,
..Transform::default()
});
}
}
"xshift" => self.shift(units::dimension(value).unwrap_or(0.0), 0.0),
"yshift" => self.shift(0.0, units::dimension(value).unwrap_or(0.0)),
"shift" => {
let inside = value.trim().trim_start_matches('(').trim_end_matches(')');
if let Some(point) = coord::parse(inside) {
let frame = coord::Frame::new(1.0, 1.0);
let (x, y) = point.resolve(&frame);
self.shift(x, y);
}
}
"anchor" => {
if let Some(anchor) = Anchor::named(value) {
self.anchor = anchor;
}
}
"above" => self.anchor = Anchor::South,
"below" => self.anchor = Anchor::North,
"left" => self.anchor = Anchor::East,
"right" => self.anchor = Anchor::West,
"above left" => self.anchor = Anchor::SouthEast,
"above right" => self.anchor = Anchor::SouthWest,
"below left" => self.anchor = Anchor::NorthEast,
"below right" => self.anchor = Anchor::NorthWest,
"rectangle" | "circle" | "ellipse" | "diamond" => {
if let Some(shape) = Shape::named(key) {
self.shape = shape;
}
}
"shape" => {
if let Some(shape) = Shape::named(value) {
self.shape = shape;
}
}
"aspect" => {
if let Some(ratio) = units::number(value) {
self.aspect = ratio;
}
}
"inner sep" => {
if let Some(sep) = units::dimension(value) {
self.inner_sep = (sep, sep);
}
}
"inner xsep" => {
if let Some(sep) = units::dimension(value) {
self.inner_sep.0 = sep;
}
}
"inner ysep" => {
if let Some(sep) = units::dimension(value) {
self.inner_sep.1 = sep;
}
}
"outer sep" => self.outer_sep = units::dimension(value),
"rounded corners" => {
self.rounded = units::dimension(value).unwrap_or(4.0);
}
"sharp corners" => self.rounded = 0.0,
"shading" => {
let shade = self.shade.get_or_insert_with(Shade::default);
shade.kind = match value {
"radial" => Shading::Radial,
"ball" => Shading::Ball,
_ => Shading::Axis,
};
}
"shading angle" => {
if let Some(angle) = units::number(value) {
self.shade.get_or_insert_with(Shade::default).angle = angle;
}
}
"top color" | "bottom color" | "left color" | "right color" | "middle color" => {
if let Some(rgb) = colour(value, colours) {
let shade = self.shade.get_or_insert_with(Shade::default);
shade.kind = Shading::Axis;
match key {
"top color" => shade.top = rgb,
"bottom color" => shade.bottom = rgb,
"left color" => {
shade.top = rgb;
shade.angle = 90.0;
}
"right color" => {
shade.bottom = rgb;
shade.angle = 90.0;
}
_ => {
shade.middle = rgb;
shade.middle_set = true;
}
}
if matches!(key, "top color" | "bottom color") {
shade.angle = 0.0;
}
shade.remix();
}
}
"inner color" | "outer color" => {
if let Some(rgb) = colour(value, colours) {
let shade = self.shade.get_or_insert_with(Shade::default);
shade.kind = Shading::Radial;
match key {
"inner color" => shade.inner = rgb,
_ => shade.outer = rgb,
}
}
}
"ball color" => {
if let Some(rgb) = colour(value, colours) {
let shade = self.shade.get_or_insert_with(Shade::default);
shade.kind = Shading::Ball;
shade.ball = rgb;
}
}
"decorate" => self.decorate = true,
"pattern" | "pattern color" => self.pattern = true,
"decoration" => self.decoration(value),
"label" => self.label = label(value),
"label distance" => {
if let Some(distance) = units::dimension(value) {
self.label_distance = distance;
}
}
"minimum size" => {
if let Some(size) = units::dimension(value) {
self.minimum = (size, size);
}
}
"minimum width" => {
if let Some(size) = units::dimension(value) {
self.minimum.0 = size;
}
}
"minimum height" => {
if let Some(size) = units::dimension(value) {
self.minimum.1 = size;
}
}
"font size" => {
if let Some(size) = units::dimension(value) {
self.font_size = size;
}
}
other => self.bare(other, colours),
}
}
fn decoration(&mut self, value: &str) {
for option in split(value) {
let (key, inner) = match option.split_once('=') {
Some((key, inner)) => (key.trim(), strip_braces(inner.trim())),
None => (option.trim(), ""),
};
match key {
"name" => self.decoration = Decoration::named(inner),
"amplitude" => {
if let Some(length) = units::dimension(inner) {
self.amplitude = length;
}
}
"segment length" => {
if let Some(length) = units::dimension(inner) {
self.segment_length = length;
}
}
"aspect" => {
if let Some(ratio) = units::number(inner) {
self.decoration_aspect = ratio;
}
}
other => {
if let Some(decoration) = Decoration::named(other) {
self.decoration = Some(decoration);
}
}
}
}
}
fn bare(&mut self, key: &str, colours: &Colours) {
if let Some((start, end)) = arrow_spec(key) {
self.arrow_start = start;
self.arrow_end = end;
return;
}
if let Some(rgb) = colour(key, colours) {
self.stroke = rgb;
self.fill = rgb;
self.text = rgb;
}
}
pub fn outer(&self) -> f64 {
self.outer_sep.unwrap_or(self.width / 2.0)
}
fn compose(&mut self, inner: Transform) {
self.transform = inner.then(&self.transform);
}
fn shift(&mut self, x: f64, y: f64) {
self.compose(Transform {
tx: x,
ty: y,
..Transform::default()
});
}
}
pub fn arrow_spec(key: &str) -> Option<(Option<Tip>, Option<Tip>)> {
let key = key.trim();
let at = key.find('-')?;
let (start, end) = (&key[..at], &key[at + 1..]);
let tip = |name: &str| match name.is_empty() {
true => Some(None),
false => Tip::named(name).map(Some),
};
Some((tip(start)?, tip(end)?))
}
fn label(value: &str) -> Option<(f64, String)> {
let value = value.trim();
let value = match value.strip_prefix('[') {
Some(rest) => rest.split_once(']').map(|(_, tail)| tail).unwrap_or(rest),
None => value,
};
let (where_, text) = match value.split_once(':') {
Some((placement, text)) => (placement.trim(), text.trim()),
None => ("above", value.trim()),
};
let degrees = match where_ {
"above" | "north" => 90.0,
"below" | "south" => 270.0,
"left" | "west" => 180.0,
"right" | "east" => 0.0,
"above left" | "north west" => 135.0,
"above right" | "north east" => 45.0,
"below left" | "south west" => 225.0,
"below right" | "south east" => 315.0,
other => units::number(other)?,
};
Some((degrees, strip_braces(text).to_string()))
}
fn dash_pattern(value: &str) -> Vec<f64> {
let mut out = Vec::new();
let mut words = value.split_whitespace();
while let Some(word) = words.next() {
if matches!(word, "on" | "off") {
if let Some(length) = words.next().and_then(units::dimension) {
out.push(length);
}
}
}
out
}
pub fn colour(spec: &str, colours: &Colours) -> Option<Rgb> {
let spec = spec.trim();
if spec.is_empty() {
return None;
}
let mut parts = spec.split('!');
let mut current = colours.get(parts.next()?)?;
while let Some(percent) = parts.next() {
let fraction = units::number(percent)? / 100.0;
let against = match parts.next() {
Some(name) => colours.get(name)?,
None => (1.0, 1.0, 1.0),
};
current = (
current.0 * fraction + against.0 * (1.0 - fraction),
current.1 * fraction + against.1 * (1.0 - fraction),
current.2 * fraction + against.2 * (1.0 - fraction),
);
}
Some(current)
}
pub fn split(options: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut start = 0;
for (at, ch) in options.char_indices() {
match ch {
'{' | '[' | '(' => depth += 1,
'}' | ']' | ')' => depth -= 1,
',' if depth == 0 => {
out.push(&options[start..at]);
start = at + 1;
}
_ => {}
}
}
out.push(&options[start..]);
out.into_iter().filter(|o| !o.trim().is_empty()).collect()
}
fn strip_braces(value: &str) -> &str {
match value.strip_prefix('{').and_then(|v| v.strip_suffix('}')) {
Some(inner) => inner.trim(),
None => value,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn style(options: &str) -> Style {
Style::default().with(options, &Colours::new())
}
#[test]
fn the_named_widths_are_pgfs_own_numbers() {
assert_eq!(style("ultra thin").width, 0.1);
assert_eq!(style("thin").width, 0.4);
assert_eq!(style("thick").width, 0.8);
assert_eq!(style("ultra thick").width, 1.6);
assert_eq!(style("line width=1.52pt").width, 1.52);
}
#[test]
fn the_dash_patterns_are_pgfs_own_numbers() {
assert_eq!(style("dashed").dash, vec![3.0, 3.0]);
assert_eq!(style("densely dashed").dash, vec![3.0, 2.0]);
assert_eq!(style("loosely dashed").dash, vec![3.0, 6.0]);
assert_eq!(style("line width=1pt,dotted").dash, vec![1.0, 2.0]);
assert_eq!(style("dotted").dash, vec![0.4, 2.0]);
assert_eq!(style("dashed,solid").dash, Vec::<f64>::new());
assert_eq!(style("dash pattern=on 4pt off 1pt").dash, vec![4.0, 1.0]);
}
#[test]
fn an_arrow_spec_is_told_apart_from_a_style_name() {
assert_eq!(arrow_spec("->"), Some((None, Some(Tip::To))));
assert_eq!(arrow_spec("<-"), Some((Some(Tip::To), None)));
assert_eq!(arrow_spec("<->"), Some((Some(Tip::To), Some(Tip::To))));
assert_eq!(arrow_spec("-stealth"), Some((None, Some(Tip::Stealth))));
assert_eq!(
arrow_spec("latex-latex"),
Some((Some(Tip::Latex), Some(Tip::Latex)))
);
assert_eq!(arrow_spec("dash dot"), None);
assert_eq!(arrow_spec("even-odd"), None);
}
#[test]
fn a_colour_reaches_the_style_by_every_spelling() {
let red = (1.0, 0.0, 0.0);
assert_eq!(style("red").stroke, red);
assert_eq!(style("color=red").stroke, red);
assert_eq!(style("draw=red").stroke, red);
assert_eq!(style("fill=red").fill, red);
assert!(style("draw=red").draw);
assert!(style("fill=blue").filled);
assert_eq!(style("red!50").stroke, (1.0, 0.5, 0.5));
assert_eq!(style("red!0!blue").stroke, (0.0, 0.0, 1.0));
assert_eq!(style("draw=red,nosuchcolour").stroke, red);
}
#[test]
fn a_transform_lands_where_lualatex_puts_it() {
let style = style("rotate=30,scale=2");
let (x, y) = style.transform.apply((2.0, 0.0));
assert!((x - 4.0 * 30f64.to_radians().cos()).abs() < 1e-9, "{x}");
assert!((y - 4.0 * 30f64.to_radians().sin()).abs() < 1e-9, "{y}");
let style = style.clone();
let shifted = Style::default().with("xshift=3pt", &Colours::new());
assert_eq!(shifted.transform.apply((1.0, 1.0)), (4.0, 1.0));
let _ = style;
}
#[test]
fn an_option_value_may_carry_its_own_comma() {
assert_eq!(split("a,shift={(1,2)},b"), vec!["a", "shift={(1,2)}", "b"]);
let style = style("shift={(1,2)}");
assert_eq!(style.transform.apply((0.0, 0.0)), (1.0, 2.0));
}
}