lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Call-local output framing. Rectangles and references have different
//! coordinate frames once a composite has expanded its original viewport.

use crate::{
    layout::{InkExtent, Insets, Length, LengthUnit, PaintBatchRef, Rect, RectRef, RootSize},
    scene::RenderedScene,
    Error, Result,
};

use super::PngSizing;
mod recipe;
pub(super) use recipe::pad_schema;

/// An absolute rectangle in the current output, or a rectangle selected from
/// the actual original native layout and translated once into the output.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RegionTarget {
    /// Current output CSS coordinates.
    Rect(Rect),
    /// Actual frozen layout reference.
    Reference(RectRef),
}
impl From<Rect> for RegionTarget {
    fn from(rect: Rect) -> Self {
        Self::Rect(rect)
    }
}
impl From<RectRef> for RegionTarget {
    fn from(reference: RectRef) -> Self {
        Self::Reference(reference)
    }
}
impl From<&RectRef> for RegionTarget {
    fn from(reference: &RectRef) -> Self {
        Self::Reference(reference.clone())
    }
}

#[derive(Debug, Clone, PartialEq)]
enum Selection {
    Full,
    Rect(RegionTarget),
    Tight,
}

#[derive(Debug, Clone, PartialEq)]
enum Padding {
    Fixed(Insets),
    Layout,
}

/// A publication-only frame, optionally derived from actual visible ink.
/// The selected picture is clipped before its empty padding is added.
#[derive(Debug, Clone, PartialEq)]
#[must_use]
pub struct ExportRegion {
    selection: Selection,
    padding: Option<Padding>,
    include: Vec<RectRef>,
    exclude: Vec<PaintBatchRef>,
    within: Option<RegionTarget>,
    coverage: Option<PngSizing>,
}

impl Default for ExportRegion {
    fn default() -> Self {
        Self::full()
    }
}

impl ExportRegion {
    /// Keep the complete frozen viewport.
    pub const fn full() -> Self {
        Self {
            selection: Selection::Full,
            padding: None,
            include: Vec::new(),
            exclude: Vec::new(),
            within: None,
            coverage: None,
        }
    }
    /// Select a positive CSS rectangle or an actual frozen layout reference.
    pub fn rect(target: impl Into<RegionTarget>) -> Self {
        Self {
            selection: Selection::Rect(target.into()),
            ..Self::full()
        }
    }
    /// Compute the visible content bounds, excluding structural native paper.
    pub const fn tight() -> Self {
        Self {
            selection: Selection::Tight,
            padding: None,
            include: Vec::new(),
            exclude: Vec::new(),
            within: None,
            coverage: None,
        }
    }
    /// Add four absolute CSS-pixel padding lengths.
    pub fn pad(mut self, insets: Insets) -> Self {
        self.padding = Some(Padding::Fixed(insets));
        self
    }
    /// Use the four actually resolved root-layout padding lengths.
    pub fn pad_layout(mut self) -> Self {
        self.padding = Some(Padding::Layout);
        self
    }
    /// Add the selected actual allocation to the tight boundary.
    /// This can deliberately retain a reserved slot that has no ink.
    pub fn include(mut self, reference: RectRef) -> Self {
        self.include.push(reference);
        self
    }
    /// Exclude one actual closed native batch from the boundary computation,
    /// while retaining its paint in the selected publication.
    pub fn exclude(mut self, reference: PaintBatchRef) -> Self {
        self.exclude.push(reference);
        self
    }
    /// Restrict the search for tight bounds to this actual rectangle.
    pub fn within(mut self, target: impl Into<RegionTarget>) -> Self {
        self.within = Some(target.into());
        self
    }
    /// Use explicit sampled alpha support rather than continuous vector ink
    /// for the tight frame, at this independently selected resolution.
    pub fn pixel_coverage(mut self, sizing: PngSizing) -> Self {
        self.coverage = Some(sizing);
        self
    }
    /// Whether the author already selected a padding policy.
    pub fn has_padding(&self) -> bool {
        self.padding.is_some()
    }

    pub(super) fn validate(&self) -> Result<()> {
        if !matches!(self.selection, Selection::Tight)
            && (!self.include.is_empty()
                || !self.exclude.is_empty()
                || self.within.is_some()
                || self.coverage.is_some())
        {
            return Err(Error::Data(
                "include, exclude, within and pixel coverage require a tight region".into(),
            ));
        }
        if let Some(Padding::Fixed(insets)) = &self.padding {
            absolute_insets(insets)?;
        }
        if let Some(sizing) = self.coverage {
            crate::render::svg_backend::validate_png_sizing(sizing)?;
        }
        Ok(())
    }

    pub(crate) fn resolve(&self, scene: &RenderedScene) -> Result<RegionPlan> {
        self.validate()?;
        let viewport = scene.viewport()?;
        let selected = match &self.selection {
            Selection::Full => viewport,
            Selection::Rect(target) => resolve_target(scene, target)?,
            Selection::Tight => self.tight_bounds(scene, viewport)?,
        };
        if selected.width() <= 0. || selected.height() <= 0. {
            return Err(Error::Data(
                "publication region must have positive dimensions".into(),
            ));
        }
        let padding = match &self.padding {
            Some(Padding::Fixed(insets)) => absolute_insets(insets)?,
            Some(Padding::Layout) => scene.layout_report()?.root_padding(),
            None if matches!(self.selection, Selection::Tight) => [9.6; 4],
            None => [0.; 4],
        };
        let size = if selected == viewport && padding.iter().all(|&value| value == 0.) {
            scene.size()
        } else {
            RootSize::new(
                selected.width() + padding[0] + padding[1],
                selected.height() + padding[2] + padding[3],
            )
        };
        size.dimensions()?;
        Ok(RegionPlan {
            selected,
            padding,
            size,
            viewport,
        })
    }

    fn tight_bounds(&self, scene: &RenderedScene, viewport: Rect) -> Result<Rect> {
        let scope = self
            .within
            .as_ref()
            .map(|target| resolve_target(scene, target))
            .transpose()?
            .unwrap_or(viewport);
        let Some(clip) = scope.intersection(viewport) else {
            return Err(Error::Data(
                "tight search region has no intersection with the output viewport".into(),
            ));
        };
        let mut included = InkExtent::Empty;
        for reference in &self.include {
            if let Some(rect) = scene.resolve_rect(reference)?.intersection(clip) {
                included = included.union(InkExtent::Bounds(rect));
            }
        }
        let ink = scene.tight_ink(clip, &self.exclude, self.coverage, included)?;
        match ink {
            InkExtent::Empty=>Ok(clip),
            InkExtent::Bounds(bounds)=>outward(bounds),
            InkExtent::Unknown=>Err(Error::Render("cannot determine actual visible ink for a tight region; use an explicit rectangle or pixel coverage".into())),
        }
    }
}

fn resolve_target(scene: &RenderedScene, target: &RegionTarget) -> Result<Rect> {
    match target {
        RegionTarget::Rect(rect) => Ok(*rect),
        RegionTarget::Reference(reference) => scene.resolve_rect(reference),
    }
}

pub(crate) fn absolute_insets(insets: &Insets) -> Result<[f64; 4]> {
    let pixels = |length: &Length| {
        let value = length.value().as_f64();
        if length.unit() == LengthUnit::Px || value == 0. {
            Ok(value)
        } else {
            Err(Error::Data(
                "publication padding requires absolute CSS-pixel lengths".into(),
            ))
        }
    };
    Ok([
        pixels(insets.get_left())?,
        pixels(insets.get_right())?,
        pixels(insets.get_top())?,
        pixels(insets.get_bottom())?,
    ])
}

pub(crate) fn outward(bounds: Rect) -> Result<Rect> {
    let left = (bounds.left() * 1024.).floor() / 1024.;
    let top = (bounds.top() * 1024.).floor() / 1024.;
    let right = ((bounds.left() + bounds.width()) * 1024.).ceil() / 1024.;
    let bottom = ((bounds.top() + bounds.height()) * 1024.).ceil() / 1024.;
    Rect::new(left, top, right - left, bottom - top)
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct RegionPlan {
    pub(crate) selected: Rect,
    /// left, right, top, bottom
    pub(crate) padding: [f64; 4],
    pub(crate) size: RootSize,
    pub(crate) viewport: Rect,
}

impl RegionPlan {
    pub(crate) fn full_viewport(self) -> bool {
        self.selected == self.viewport && self.padding.iter().all(|&value| value == 0.)
    }
}