use std::path::Path;
use lichtung_plot::layout::SizeUnit;
use lichtung_plot::{
guides::CanvasLegendPolicy,
kind,
layout::TextPanel,
output::{PngOptions, PngSizing},
Canvas, CategoryValues, Error, NumericFormat, NumericValues, Output, Plot,
};
#[path = "../support/visual.rs"]
mod support;
use support::unique_dir;
struct Scene {
dimensions: (f64, f64),
svg: String,
}
fn publish(name: &str, render_scene: impl FnOnce(&Path) -> Result<Output, Error>) -> Scene {
let directory = unique_dir(name);
let destination = directory.join("plot.svg");
let output = render_scene(&destination).unwrap_or_else(|error| panic!("{name}: {error}"));
let dimensions = (output.width(), output.height());
let svg = std::fs::read_to_string(destination).unwrap();
assert_svg_dimensions(&svg, dimensions);
std::fs::remove_dir_all(directory).unwrap();
Scene { dimensions, svg }
}
fn assert_svg_dimensions(svg: &str, dimensions: (f64, f64)) {
let document = roxmltree::Document::parse(svg).unwrap();
let root = document.root_element();
assert!(root.has_tag_name("svg"));
assert_eq!(
root.attribute("width"),
Some(dimensions.0.to_string().as_str())
);
assert_eq!(
root.attribute("height"),
Some(dimensions.1.to_string().as_str())
);
assert_eq!(
root.attribute("viewBox"),
Some(format!("0 0 {} {}", dimensions.0, dimensions.1).as_str())
);
}
fn assert_complete_source(svg: &str, source: &str) {
let document = roxmltree::Document::parse(svg).unwrap();
let words = document
.descendants()
.filter(|node| node.has_tag_name("text"))
.filter_map(|node| node.text())
.flat_map(str::split_whitespace)
.collect::<Vec<_>>();
let required = source.split_whitespace().collect::<Vec<_>>();
assert!(!required.is_empty());
assert_eq!(
words
.windows(required.len())
.filter(|words| *words == required)
.count(),
1,
"the complete source must occur exactly once: {source}"
);
}
fn caption() -> String {
format!(
"CaptionBegin {}CaptionEnd",
"Measurements retain every observation and its scientific identity while complete explanatory prose reflows at the selected width without shrinking fonts omitting words or changing the requested geometry. ".repeat(8)
)
}
fn scatter() -> Plot<kind::Scatter> {
Plot::scatter(
NumericValues::new("dose", [0.0, 1.0, 2.0, 3.0]),
NumericValues::new("response", [1.0, 3.0, 2.0, 4.0]),
)
}
fn png_size(path: &Path) -> (u32, u32) {
let decoder = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(path).unwrap()));
let reader = decoder.read_info().unwrap();
reader.info().size()
}
#[test]
fn physical_pages_keep_exact_viewport_and_raster_rounding() {
let directory = unique_dir("exact-physical-page");
let output = scatter()
.size_with_unit(210.0, 297.0, SizeUnit::Millimeter)
.unwrap()
.render()
.unwrap();
let physical = output.physical_size().unwrap();
assert_eq!((physical.width(), physical.height()), (210.0, 297.0));
assert_eq!(physical.unit(), SizeUnit::Millimeter);
assert_eq!(
(output.width(), output.height()),
(100_800.0 / 127.0, 142_560.0 / 127.0)
);
for preserve_text in [false, true] {
let path = directory.join(if preserve_text {
"text.svg"
} else {
"outlined.svg"
});
if preserve_text {
output.svg_preserve_text(&path).unwrap();
} else {
output.svg(&path).unwrap();
}
let svg = std::fs::read_to_string(path).unwrap();
let document = roxmltree::Document::parse(&svg).unwrap();
let root = document.root_element();
assert_eq!(root.attribute("width"), Some("210mm"));
assert_eq!(root.attribute("height"), Some("297mm"));
assert_eq!(
root.attribute("viewBox"),
Some(format!("0 0 {} {}", output.width(), output.height()).as_str())
);
}
let publication = directory.join("a4.png");
output.png(&publication).unwrap();
assert_eq!(png_size(&publication), (2480, 3508));
let narrow = scatter()
.size_with_unit(70.0, 100.0, SizeUnit::Millimeter)
.unwrap()
.render()
.unwrap();
let width = directory.join("seventy.png");
narrow
.png_with_options(
&width,
PngOptions {
sizing: PngSizing::Width(700),
..PngOptions::default()
},
)
.unwrap();
assert_eq!(png_size(&width), (700, 1000));
let points = scatter()
.size_with_unit(769.0, 288.0, SizeUnit::Point)
.unwrap()
.render()
.unwrap();
let half_pixel = directory.join("half-pixel.png");
points
.png_with_options(
&half_pixel,
PngOptions {
sizing: PngSizing::Dpi(180.0),
..PngOptions::default()
},
)
.unwrap();
assert_eq!(png_size(&half_pixel), (1923, 720));
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn physical_root_is_replaced_by_css_and_canvas_controls_embedded_dimensions() {
let child = scatter().size_with_unit(8.0, 6.0, SizeUnit::Inch).unwrap();
let original = child.render().unwrap();
assert_eq!((original.width(), original.height()), (768.0, 576.0));
let replaced = child.clone().size(320, 240).render().unwrap();
assert_eq!((replaced.width(), replaced.height()), (320.0, 240.0));
assert!(replaced.physical_size().is_none());
let canvas = Canvas::grid(1, 1).unwrap().panel(0, 0, child).unwrap();
let output = canvas
.size_with_unit(20.0, 15.0, SizeUnit::Centimeter)
.unwrap()
.render()
.unwrap();
assert_eq!(
(output.width(), output.height()),
(96_000.0 / 127.0, 72_000.0 / 127.0)
);
assert_eq!(output.physical_size().unwrap().unit(), SizeUnit::Centimeter);
assert_eq!(original.physical_size().unwrap().unit(), SizeUnit::Inch);
let faceted = scatter()
.facet(lichtung_plot::layout::FacetSpec::column(
CategoryValues::new("group", ["A", "B", "A", "B"]).unwrap(),
))
.size_with_unit(210.0, 297.0, SizeUnit::Millimeter)
.unwrap()
.render()
.unwrap();
assert_eq!(
(faceted.width(), faceted.height()),
(100_800.0 / 127.0, 142_560.0 / 127.0)
);
for invalid in [
0.0,
-1.0,
f64::NAN,
f64::INFINITY,
f64::MAX,
f64::MIN_POSITIVE,
] {
assert!(scatter()
.size_with_unit(invalid, 8.0, SizeUnit::Inch)
.is_err());
}
assert!(scatter()
.size_with_unit(1.0, 1.0, SizeUnit::Millimeter)
.unwrap()
.preflight()
.is_err());
}
#[test]
fn automatic_roots_expand_for_complete_unbreakable_text_and_capped_width_refuses_it() {
let heading = "W".repeat(96);
let ordinary = publish("automatic-short-heading", |path| {
scatter().title("Short heading").svg_preserve_text(path)
});
let expanded = publish("automatic-unbreakable-heading", |path| {
scatter().title(&heading).svg_preserve_text(path)
});
assert!(expanded.dimensions.0 > ordinary.dimensions.0);
assert_complete_source(&expanded.svg, &heading);
let directory = unique_dir("exact-width-unbreakable-refusal");
let destination = directory.join("must-not-exist.svg");
let error = scatter()
.title(&heading)
.width(300)
.svg_preserve_text(&destination)
.err()
.unwrap();
assert!(error.to_string().contains("layout fit"), "{error}");
assert!(!destination.exists());
std::fs::write(&destination, "existing destination").unwrap();
let error = scatter()
.title(heading)
.max_width(300)
.svg_preserve_text(&destination)
.err()
.unwrap();
assert!(error.to_string().contains("layout fit"), "{error}");
assert_eq!(
std::fs::read_to_string(destination).unwrap(),
"existing destination"
);
std::fs::remove_dir_all(directory).unwrap();
}
fn mixed_canvas(caption: &str, replace_children: bool) -> Canvas {
let child = |name: &str| {
let plot = scatter()
.x_tick_format(NumericFormat::default().prefix(format!("{name}:")).unwrap())
.hue(
CategoryValues::new("treatment", ["Control", "Exposed", "Control", "Exposed"])
.unwrap(),
)
.title(format!("{name} panel title"))
.subtitle(format!("{name} panel subtitle"))
.caption(format!("{name} local caption"));
if replace_children {
plot.size(0, 0).width(0).max_width(0)
} else {
plot
}
};
Canvas::grid(2, 2)
.unwrap()
.panel(0, 0, child("First"))
.unwrap()
.panel_span(0, 1, 2, 1, child("Second"))
.unwrap()
.text_panel(
1,
0,
TextPanel::new(
"Interpretation",
"A complete prose cell alongside two scientific panels. 0.125% remains literal caller text.",
)
.unwrap(),
)
.unwrap()
.column_header(0, 2, "Shared scientific observations")
.unwrap()
.x_range_group([(0, 0), (0, 1)])
.unwrap()
.legend_policy(CanvasLegendPolicy::Shared)
.title("Canvas root title")
.subtitle("Independent Canvas subtitle")
.caption(caption)
}
#[test]
fn mixed_canvas_keeps_complete_content_and_ignores_standalone_child_requests() {
let caption = caption();
let scene = publish("public-mixed-canvas", |path| {
mixed_canvas(&caption, false)
.max_width(1101)
.svg_preserve_text(path)
});
let replaced = publish("public-mixed-canvas-child-requests", |path| {
mixed_canvas(&caption, true)
.max_width(1101)
.svg_preserve_text(path)
});
assert!(scene.dimensions.0 <= 1101.0);
assert_eq!(replaced.svg, scene.svg);
for source in [
"Canvas root title",
"Independent Canvas subtitle",
"First panel title",
"First panel subtitle",
"First local caption",
"Second panel title",
"Second panel subtitle",
"Second local caption",
"Interpretation",
"A complete prose cell alongside two scientific panels.",
"0.125% remains literal caller text.",
"Shared scientific observations",
"Treatment",
"Control",
"Exposed",
&caption,
] {
assert_complete_source(&scene.svg, source);
}
assert_eq!(scene.svg.matches("<clipPath ").count(), 2);
assert!(scene.svg.contains(">First:") && scene.svg.contains(">Second:"));
}