use super::*;
use crate::{output::RegionPlan, style::OpaqueColor};
pub(crate) fn frame_svg(
source: &str,
frame: RegionPlan,
paper: Option<Color>,
matte: Option<OpaqueColor>,
limit: Option<usize>,
) -> Result<Vec<u8>, Error> {
let document = roxmltree::Document::parse(source)
.map_err(|error| Error::Render(format!("publication frame SVG: {error}").into()))?;
let root = document.root_element();
let inner = root.first_child().map_or("", |first| {
&source[first.range().start..root.last_child().expect("nonempty SVG").range().end]
});
let mut count = CountBuffer {
limit,
..CountBuffer::default()
};
emit_frame(&mut count, inner, frame, paper, matte)?;
let mut output = WriteBuffer::default();
output
.text
.try_reserve_exact(count.len())
.map_err(|error| Error::Render(format!("publication SVG reservation: {error}").into()))?;
output.fixed = true;
emit_frame(&mut output, inner, frame, paper, matte)?;
if output.len() != count.len() {
return Err(Error::Render(
"publication frame differs from counted SVG".into(),
));
}
Ok(output.text.into_bytes())
}
fn paint_rect(output: &mut impl fmt::Write, rect: crate::layout::Rect, color: Color) {
if rect.width() > 0. && rect.height() > 0. && color.get_alpha() > 0. {
let paint = SvgPaint(color).attributes("fill");
let _ = writeln!(
output,
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" {paint}/>",
rect.left(),
rect.top(),
rect.width(),
rect.height()
);
}
}
fn emit_frame<S: SvgSink>(
output: &mut S,
inner: &str,
frame: RegionPlan,
paper: Option<Color>,
matte: Option<OpaqueColor>,
) -> Result<(), Error> {
use crate::layout::Rect;
emit_svg_root(output, frame.size)
.map_err(|_| Error::Render("publication frame SVG header".into()))?;
let (width, height) = frame.size.dimensions()?;
if let Some(matte) = matte {
paint_rect(output, Rect::new(0., 0., width, height)?, matte.into());
}
if frame.full_viewport() {
let _ = output.write_str(inner);
} else {
let [left, right, top, bottom] = frame.padding;
let rect = frame.selected;
if let Some(paper) = paper {
for pad in [
Rect::new(0., 0., width, top)?,
Rect::new(0., top + rect.height(), width, bottom)?,
Rect::new(0., top, left, rect.height())?,
Rect::new(left + rect.width(), top, right, rect.height())?,
] {
paint_rect(output, pad, paper);
}
}
let _=writeln!(output,
"<svg x=\"{left}\" y=\"{top}\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" preserveAspectRatio=\"none\" overflow=\"hidden\">",
rect.width(),rect.height(),rect.left(),rect.top(),rect.width(),rect.height());
let viewport = frame.viewport;
let _=writeln!(output,
"<svg x=\"0\" y=\"0\" width=\"{}\" height=\"{}\" viewBox=\"0 0 {} {}\" preserveAspectRatio=\"none\" overflow=\"hidden\">",
viewport.width(),viewport.height(),viewport.width(),viewport.height());
let _ = output.write_str(inner);
let _ = output.write_str("</svg>\n</svg>\n");
}
let _ = output.write_str("</svg>\n");
output.check()
}