use super::options::Anchor;
use super::shapes::Border;
use super::units::{self, Length};
use std::collections::BTreeMap;
pub type Point = (f64, f64);
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Placed {
pub at: Point,
pub border: Border,
}
impl Placed {
pub fn point(at: Point) -> Placed {
Placed {
at,
border: Border::default(),
}
}
pub fn offset(&self, spec: &str) -> Point {
let spec = spec.trim();
match Anchor::named(spec) {
Some(anchor) => self.border.anchor(anchor),
None if matches!(spec, "mid" | "base" | "text") => (0.0, 0.0),
None => match units::number(spec) {
Some(degrees) => self.border.border_at(degrees),
None => (0.0, 0.0),
},
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Frame {
pub named: BTreeMap<String, Placed>,
pub current: Point,
pub relative: Point,
pub last_move: Point,
pub x_scale: f64,
pub y_scale: f64,
}
impl Frame {
pub fn new(x_scale: f64, y_scale: f64) -> Frame {
Frame {
x_scale,
y_scale,
..Frame::default()
}
}
fn on_axis(&self, length: Length, scale: f64) -> f64 {
match length.points {
Some(points) => self.unscale(points, scale),
None => length.value,
}
}
pub fn unscale(&self, points: f64, scale: f64) -> f64 {
match scale != 0.0 {
true => points / scale,
false => points,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Coord {
Cartesian(Length, Length),
Polar(f64, Length, Length),
Named(String, Option<String>),
Sum(Vec<(f64, Coord)>),
Partway(Box<Coord>, f64, Box<Coord>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Relative {
Absolute,
Offset,
Step,
}
impl Coord {
pub fn resolve(&self, frame: &Frame) -> Point {
match self {
Coord::Cartesian(x, y) => (
frame.on_axis(*x, frame.x_scale),
frame.on_axis(*y, frame.y_scale),
),
Coord::Polar(angle, rx, ry) => {
let radians = angle.to_radians();
(
frame.on_axis(*rx, frame.x_scale) * radians.cos(),
frame.on_axis(*ry, frame.y_scale) * radians.sin(),
)
}
Coord::Named(name, anchor) => {
let placed = frame.named.get(name).copied().unwrap_or_default();
match anchor {
Some(anchor) => {
let (dx, dy) = placed.offset(anchor);
(
placed.at.0 + frame.unscale(dx, frame.x_scale),
placed.at.1 + frame.unscale(dy, frame.y_scale),
)
}
None => placed.at,
}
}
Coord::Sum(terms) => terms.iter().fold((0.0, 0.0), |(x, y), (factor, term)| {
let (tx, ty) = term.resolve(frame);
(x + factor * tx, y + factor * ty)
}),
Coord::Partway(from, fraction, to) => {
let (ax, ay) = from.resolve(frame);
let (bx, by) = to.resolve(frame);
(ax + (bx - ax) * fraction, ay + (by - ay) * fraction)
}
}
}
}
pub fn parse(inside: &str) -> Option<Coord> {
let text = inside.trim();
if let Some(body) = text.strip_prefix('$').and_then(|t| t.strip_suffix('$')) {
return calc(body);
}
if let Some(at) = top_level(text, ':') {
let angle = component(&text[..at])?.value;
let (rx, ry) = radii(&text[at + 1..])?;
return Some(Coord::Polar(angle, rx, ry));
}
if let Some(at) = top_level(text, ',') {
let x = component(&text[..at])?;
let y = component(&text[at + 1..])?;
return Some(Coord::Cartesian(x, y));
}
if text.is_empty() {
return None;
}
match text.split_once('.') {
Some((name, anchor)) if !name.trim().is_empty() && units::number(name).is_none() => Some(
Coord::Named(name.trim().to_string(), Some(anchor.trim().to_string())),
),
_ => Some(Coord::Named(text.to_string(), None)),
}
}
fn radii(text: &str) -> Option<(Length, Length)> {
match text.split_once("and") {
Some((first, second)) => Some((component(first)?, component(second)?)),
None => {
let both = component(text)?;
Some((both, both))
}
}
}
fn component(text: &str) -> Option<Length> {
if let Some((length, rest)) = units::scan(text) {
if rest.trim().is_empty() {
return Some(length);
}
}
super::math::length(text)
}
fn calc(body: &str) -> Option<Coord> {
if let Some(at) = top_level(body, '!') {
let rest = &body[at + 1..];
let close = top_level(rest, '!')?;
let from = calc(&body[..at])?;
let fraction = units::number(&rest[..close])?;
let to = calc(&rest[close + 1..])?;
return Some(Coord::Partway(Box::new(from), fraction, Box::new(to)));
}
let mut terms = Vec::new();
let mut sign = 1.0;
let mut rest = body.trim();
while !rest.is_empty() {
let (factor, after) = match units::scan(rest) {
Some((number, after)) if after.trim_start().starts_with('*') => {
(number.value, after.trim_start()[1..].trim_start())
}
_ => (1.0, rest),
};
let after = after.trim_start();
let open = after.strip_prefix('(')?;
let close = matching(open)?;
terms.push((sign * factor, parse(&open[..close])?));
rest = open[close + 1..].trim_start();
match rest.chars().next() {
Some('+') => sign = 1.0,
Some('-') => sign = -1.0,
None => break,
_ => return None,
}
rest = rest[1..].trim_start();
}
match terms.is_empty() {
true => None,
false => Some(Coord::Sum(terms)),
}
}
fn top_level(text: &str, wanted: char) -> Option<usize> {
let mut depth = 0i32;
for (at, ch) in text.char_indices() {
match ch {
'(' | '{' => depth += 1,
')' | '}' => depth -= 1,
c if c == wanted && depth == 0 => return Some(at),
_ => {}
}
}
None
}
pub fn matching(after_open: &str) -> Option<usize> {
let mut depth = 0i32;
for (at, ch) in after_open.char_indices() {
match ch {
'(' => depth += 1,
')' if depth == 0 => return Some(at),
')' => depth -= 1,
_ => {}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn frame() -> Frame {
let mut frame = Frame::new(1.0, 1.0);
frame
.named
.insert("a".to_string(), Placed::point((1.0, 1.0)));
frame
.named
.insert("b".to_string(), Placed::point((3.0, 5.0)));
frame
}
fn boxed() -> Frame {
let mut frame = frame();
frame.named.insert(
"n".to_string(),
Placed {
at: (0.0, 0.0),
border: Border::of(
super::super::options::Shape::Rectangle,
(4.0, 2.0),
(0.0, 0.0),
0.0,
1.0,
),
},
);
frame
}
#[test]
fn a_polar_coordinate_is_the_point_the_angle_names() {
let point = parse("30:2cm").unwrap().resolve(&frame());
let two_cm = 2.0 * 72.27 / 2.54;
assert!((point.0 - two_cm * 30f64.to_radians().cos()).abs() < 1e-9);
assert!((point.1 - two_cm * 30f64.to_radians().sin()).abs() < 1e-9);
}
#[test]
fn a_name_is_the_point_it_was_given() {
assert_eq!(parse("a").unwrap().resolve(&frame()), (1.0, 1.0));
assert_eq!(parse("a.north").unwrap().resolve(&frame()), (1.0, 1.0));
}
#[test]
fn an_anchor_is_on_the_border_and_not_in_the_middle() {
let frame = boxed();
assert_eq!(parse("n.north").unwrap().resolve(&frame), (0.0, 2.0));
assert_eq!(parse("n.east").unwrap().resolve(&frame), (4.0, 0.0));
assert_eq!(parse("n.south west").unwrap().resolve(&frame), (-4.0, -2.0));
let (x, y) = parse("n.45").unwrap().resolve(&frame);
assert!((x - 2.0).abs() < 1e-9 && (y - 2.0).abs() < 1e-9, "{x} {y}");
assert_eq!(parse("n").unwrap().resolve(&frame), (0.0, 0.0));
}
#[test]
fn calc_adds_points_and_walks_between_them() {
assert_eq!(parse("$(a)+(1,0)$").unwrap().resolve(&frame()), (2.0, 1.0));
assert_eq!(parse("$(b)-(a)$").unwrap().resolve(&frame()), (2.0, 4.0));
assert_eq!(parse("$2*(a)$").unwrap().resolve(&frame()), (2.0, 2.0));
assert_eq!(parse("$(a)!.5!(b)$").unwrap().resolve(&frame()), (2.0, 3.0));
}
#[test]
fn a_length_with_a_unit_survives_the_pictures_scale() {
let frame = Frame::new(0.5, 0.5);
let point = parse("1cm,0").unwrap().resolve(&frame);
assert!((point.0 * 0.5 - 72.27 / 2.54).abs() < 1e-9);
assert_eq!(parse("4,2").unwrap().resolve(&frame), (4.0, 2.0));
}
}