use std::path::Path;
use crate::layout::{BoundaryRef, InkExtent, LayoutReport, Rect, RectRef, RootSize};
use crate::operation::{self, OperationOptions};
use crate::output::{PngOptions, PngSizing};
use crate::{Canvas, Error, Output, Plot, Result};
use super::fixed::FixedSource;
use super::{
CompositionSource, ImageAsset, ImageRendering, ObjectFit, ObjectPosition, PlacedContent,
Placement,
};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ComposeOptions {
pub expand_canvas: bool,
}
#[derive(Debug, Clone)]
pub struct Composite {
output: Output,
}
#[derive(Clone)]
pub(crate) enum FrozenBase {
Native(Output),
Image(PlacedContent),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct PaintCut {
pub(crate) buffer: usize,
pub(crate) offset: usize,
}
#[derive(Clone)]
pub(crate) struct FrozenPlacement {
pub(crate) content: PlacedContent,
pub(crate) cut: Option<PaintCut>,
pub(crate) clip: Rect,
}
#[derive(Clone)]
pub(crate) struct FrozenComposition {
pub(crate) base: FrozenBase,
pub(crate) original: Rect,
pub(crate) extent: Rect,
pub(crate) placements: Vec<FrozenPlacement>,
}
impl FrozenComposition {
fn new(source: FixedSource) -> Result<Self> {
let (base, original) = match source {
FixedSource::Frozen(output) => {
if let Some(composition) = output.scene().composition() {
return Ok(composition.clone());
}
let original = Rect::new(0., 0., output.width(), output.height())?;
(FrozenBase::Native(output), original)
}
FixedSource::Image(image) => {
let (width, height) = image.intrinsics().complete().ok_or_else(|| {
Error::Data("a flat base needs a definite intrinsic CSS viewport".into())
})?;
let original = Rect::new(0., 0., width, height)?;
let item = PlacedContent::boxed(
FixedSource::Image(image),
original,
ObjectFit::Fill,
ObjectPosition::top_left(),
ImageRendering::Auto,
)?;
item.prepare()?;
(FrozenBase::Image(item), original)
}
};
Ok(Self {
base,
original,
extent: original,
placements: Vec::new(),
})
}
pub(crate) fn report(&self) -> Option<&LayoutReport> {
match &self.base {
FrozenBase::Native(output) => output.layout_report().ok(),
FrozenBase::Image(_) => None,
}
}
pub(crate) fn rect(&self, reference: &RectRef) -> Result<Rect> {
if *reference == RectRef::viewport() {
return Ok(self.original);
}
self.report()
.ok_or_else(|| Error::Data("flat image base has no native layout rectangles".into()))?
.rect(reference)
}
fn boundary(&self, boundary: &BoundaryRef) -> Result<PaintCut> {
let report = self
.report()
.ok_or_else(|| Error::Data("flat image base has no native paint boundaries".into()))?;
if !report.boundaries().contains(boundary) {
return Err(Error::Data(
"paint boundary does not identify an actual unique adjacent pair in the base"
.into(),
));
}
let batch = if let Some(ahead) = boundary.ahead() {
report
.paint_order()
.iter()
.find(|batch| batch.reference() == ahead)
} else {
report
.paint_order()
.iter()
.find(|batch| Some(batch.reference()) == boundary.behind())
}
.ok_or_else(|| Error::Render("accepted paint boundary has no captured batch".into()))?;
Ok(PaintCut {
buffer: batch.buffer,
offset: if boundary.ahead().is_some() {
batch.range.start
} else {
batch.range.end
},
})
}
fn add(
&mut self,
items: impl IntoIterator<Item = Placement>,
expand: bool,
parent_theme: Option<&crate::Theme>,
) -> Result<()> {
let first = self.placements.len();
let mut extent = self.extent;
let mut unresolved = Vec::new();
for (index, item) in items.into_iter().enumerate() {
operation::checkpoint()?;
let prepared = (|| {
let cut = item
.boundary()
.map(|boundary| self.boundary(boundary))
.transpose()?;
let content = item.prepare(|reference| self.rect(reference), parent_theme)?;
if expand {
if let Some(possible) = content.object.intersection(content.frame) {
if !extent.contains(possible) {
match content.exact_ink(possible)? {
InkExtent::Empty => {}
InkExtent::Bounds(bounds) => extent = extent.union(bounds),
InkExtent::Unknown => {
crate::data::source::reserve_source(&mut unresolved, 1)?;
unresolved.push((index, possible));
}
}
}
}
}
Ok(FrozenPlacement {
content,
cut,
clip: self.extent,
})
})()
.map_err(|error: Error| error.with_prefix(&format!("placement {index}")))?;
crate::data::source::reserve_source(&mut self.placements, 1)?;
self.placements.push(prepared);
}
if let Some((index, _)) = unresolved
.into_iter()
.find(|(_, possible)| !extent.contains(*possible))
{
return Err(Error::Render(format!("placement {index}: cannot determine actual visible ink required to expand the canvas for this source").into()));
}
RootSize::new(extent.width(), extent.height()).dimensions()?;
self.extent = extent;
for item in &mut self.placements[first..] {
item.clip = extent;
}
Ok(())
}
pub(crate) fn size(&self) -> RootSize {
if self.extent == self.original {
if let FrozenBase::Native(output) = &self.base {
return output.scene().size();
}
}
RootSize::new(self.extent.width(), self.extent.height())
}
pub(crate) fn is_flat_base(&self) -> bool {
matches!(self.base, FrozenBase::Image(_))
}
pub(crate) fn origin(&self) -> (f64, f64) {
let positive = |value: f64| if value == 0. { 0. } else { -value };
(positive(self.extent.left()), positive(self.extent.top()))
}
pub(crate) fn validate_preserve_text(&self) -> Result<()> {
match &self.base {
FrozenBase::Native(output) => output.scene().validate_preserve_text()?,
FrozenBase::Image(content) => content.validate_preserve_text()?,
}
for item in &self.placements {
item.content.validate_preserve_text()?;
}
Ok(())
}
pub(crate) fn font_substitutions(&self, substitutions: &mut Vec<super::ImageFontSubstitution>) {
match &self.base {
FrozenBase::Native(output) => output
.scene()
.collect_image_font_substitutions(substitutions),
FrozenBase::Image(content) => content.font_substitutions(substitutions),
}
for item in &self.placements {
item.content.font_substitutions(substitutions);
}
}
pub(crate) fn exact_ink(&self, clip: Rect) -> Result<InkExtent> {
let clip = Rect::new(
clip.left() + self.extent.left(),
clip.top() + self.extent.top(),
clip.width(),
clip.height(),
)?;
let mut ink = match &self.base {
FrozenBase::Native(output) => output.scene().exact_ink(clip)?,
FrozenBase::Image(content) => content.exact_ink(clip)?,
};
let mut unresolved = if ink == InkExtent::Unknown {
ink = InkExtent::Empty;
self.original.intersection(clip)
} else {
None
};
for item in &self.placements {
operation::checkpoint()?;
let Some(local) = clip.intersection(item.clip) else {
continue;
};
let Some(possible) = item
.content
.frame
.intersection(item.content.object)
.and_then(|possible| possible.intersection(local))
else {
continue;
};
if let InkExtent::Bounds(known) = ink {
if known.contains(possible) {
continue;
}
}
match item.content.exact_ink(local)? {
InkExtent::Unknown => {
unresolved = Some(unresolved.map_or(possible, |prior| prior.union(possible)));
}
proven => ink = ink.union(proven),
}
}
if let Some(possible) = unresolved {
if !matches!(ink, InkExtent::Bounds(bounds) if bounds.contains(possible)) {
return Ok(InkExtent::Unknown);
}
}
match ink {
InkExtent::Bounds(rect) => Ok(InkExtent::Bounds(Rect::new(
rect.left() - self.extent.left(),
rect.top() - self.extent.top(),
rect.width(),
rect.height(),
)?)),
other => Ok(other),
}
}
}
impl Composite {
pub fn new(
base: impl TryInto<CompositionSource, Error: Into<Error>>,
items: impl IntoIterator<Item = Placement>,
) -> Result<Self> {
Self::with_options(base, items, ComposeOptions::default())
}
pub fn with_options(
base: impl TryInto<CompositionSource, Error: Into<Error>>,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
) -> Result<Self> {
Self::with_operation(base, items, options, &OperationOptions::default())
}
pub fn with_operation(
base: impl TryInto<CompositionSource, Error: Into<Error>>,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
operation_options: &OperationOptions,
) -> Result<Self> {
operation::run(operation_options, || {
let base = base.try_into().map_err(Into::into)?;
Self::prepare(base, items, options, None)
})
}
pub(crate) fn prepare(
base: CompositionSource,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
parent_theme: Option<&crate::Theme>,
) -> Result<Self> {
let base = base.prepare(None, None)?;
Ok(Self {
output: Output::new(prepare_scene(base, items, options, parent_theme)?),
})
}
pub fn in_slot(
base: impl TryInto<CompositionSource, Error: Into<Error>>,
item: impl TryInto<CompositionSource, Error: Into<Error>>,
row: usize,
column: usize,
) -> Result<Self> {
Self::new(base, [Placement::in_slot(item, row, column)?])
}
pub fn output(&self) -> &Output {
&self.output
}
pub fn width(&self) -> f64 {
self.output.width()
}
pub fn height(&self) -> f64 {
self.output.height()
}
pub fn layout_report(&self) -> Result<&LayoutReport> {
self.output.layout_report()
}
fn plan(&self) -> &FrozenComposition {
self.output.scene().composition().expect("composite scene")
}
pub fn base_origin_in_output(&self) -> (f64, f64) {
self.plan().origin()
}
pub fn default_png_sizing(&self) -> PngSizing {
if self.plan().is_flat_base() {
PngSizing::Source
} else {
PngOptions::default().sizing
}
}
pub fn svg(&self, path: impl AsRef<Path>) -> Result<Output> {
self.output.svg(path)
}
pub fn svg_with_operation(
&self,
path: impl AsRef<Path>,
options: &OperationOptions,
) -> Result<Output> {
self.output.svg_with_operation(path, options)
}
pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Output> {
self.output.svg_preserve_text(path)
}
pub fn svg_preserve_text_with_operation(
&self,
path: impl AsRef<Path>,
options: &OperationOptions,
) -> Result<Output> {
self.output.svg_preserve_text_with_operation(path, options)
}
pub fn png(&self, path: impl AsRef<Path>) -> Result<Output> {
self.png_with_operation(path, &OperationOptions::default())
}
pub fn png_with_operation(
&self,
path: impl AsRef<Path>,
options: &OperationOptions,
) -> Result<Output> {
self.save_with_operation(path, crate::output::Format::png(), options)
}
pub fn png_with_options(&self, path: impl AsRef<Path>, options: PngOptions) -> Result<Output> {
self.output.png_with_options(path, options)
}
pub fn png_with_options_with_operation(
&self,
path: impl AsRef<Path>,
options: PngOptions,
operation: &OperationOptions,
) -> Result<Output> {
self.output
.png_with_options_with_operation(path, options, operation)
}
pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Output> {
self.output.png_preview(path)
}
pub fn png_preview_with_operation(
&self,
path: impl AsRef<Path>,
options: &OperationOptions,
) -> Result<Output> {
self.output.png_preview_with_operation(path, options)
}
}
fn prepare_scene(
base: FixedSource,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
parent: Option<&crate::Theme>,
) -> Result<crate::scene::RenderedScene> {
operation::phase(crate::errors::OperationPhase::Prepare)?;
let mut plan = FrozenComposition::new(base)?;
plan.add(items, options.expand_canvas, parent)?;
let size = plan.size();
let report = plan.report().cloned();
operation::phase(crate::errors::OperationPhase::Freeze)?;
let finalized = crate::render::svg_backend::FinalizedSvgOutput::from_composition(size, plan)?;
let mut scene = crate::scene::RenderedScene::new(size, Some(finalized))?;
if let Some(report) = report {
scene = scene.with_layout_report(report);
}
operation::phase(crate::errors::OperationPhase::Publish)?;
Ok(scene)
}
pub(crate) fn append_slot_placements(
base: Output,
items: &[Placement],
parent: &crate::Theme,
) -> Result<crate::scene::RenderedScene> {
prepare_scene(
FixedSource::Frozen(base),
items.iter().cloned(),
ComposeOptions::default(),
Some(parent),
)
}
impl From<Composite> for CompositionSource {
fn from(composite: Composite) -> Self {
composite.output.into()
}
}
impl From<&Composite> for CompositionSource {
fn from(composite: &Composite) -> Self {
composite.output().into()
}
}
pub fn compose(
base: impl TryInto<CompositionSource, Error: Into<Error>>,
items: impl IntoIterator<Item = Placement>,
) -> Result<Composite> {
Composite::new(base, items)
}
macro_rules! compose_methods {
() => {
pub fn compose(&self, items: impl IntoIterator<Item = Placement>) -> Result<Composite> {
Composite::new(self, items)
}
pub fn compose_with_options(
&self,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
) -> Result<Composite> {
Composite::with_options(self, items, options)
}
pub fn compose_with_operation(
&self,
items: impl IntoIterator<Item = Placement>,
options: ComposeOptions,
operation: &OperationOptions,
) -> Result<Composite> {
Composite::with_operation(self, items, options, operation)
}
};
}
impl<K: crate::kind::Marker> Plot<K> {
compose_methods!();
}
impl Canvas {
compose_methods!();
}
impl crate::recipe::RecipeFigure {
compose_methods!();
}
impl Output {
compose_methods!();
}
impl ImageAsset {
compose_methods!();
}
impl Composite {
compose_methods!();
}