lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Canvas-level layout: canvas reservations and panel placement.
//!
//! `Layout` owns a plot panel's data range and projection. This module
//! owns the canvas geometry around that panel: title, subtitle, caption,
//! axis labels, tick labels, and future legend reservations.

use crate::layout::AxisSystemPlan;
#[cfg(test)]
use crate::layout::PhysicalTextAlignment;
#[cfg(test)]
use crate::theme::TextTheme;
#[cfg(test)]
use crate::Error;

/// The smallest positive canonical span when a real child supplies no larger
/// intrinsic. It represents one spatial quantum, never a compatibility floor.
pub(crate) const MINIMUM_PANEL_SPAN: f64 = 1.0 / 1024.0;

/// A plot panel rectangle in math-style pixel coordinates.
#[derive(Clone, Copy, PartialEq)]
pub struct PixelRect {
    /// Left edge of the plot panel.
    pub x0: f64,
    /// Right edge of the plot panel.
    pub x1: f64,
    /// Bottom edge of the plot panel.
    pub y0: f64,
    /// Top edge of the plot panel.
    pub y1: f64,
}

// This private type appears in existing diagnostics. Renaming its Rust symbol
// must not change those error bytes.
impl std::fmt::Debug for PixelRect {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PanelBox")
            .field("x0", &self.x0)
            .field("x1", &self.x1)
            .field("y0", &self.y0)
            .field("y1", &self.y1)
            .finish()
    }
}

impl PixelRect {
    /// Construct a panel box from math-style pixel coordinates.
    #[must_use]
    pub fn new(x0: f64, x1: f64, y0: f64, y1: f64) -> Self {
        Self { x0, x1, y0, y1 }
    }

    /// Return the tuple form expected by [`crate::layout::Projection`].
    #[must_use]
    pub fn as_tuple(self) -> (f64, f64, f64, f64) {
        (self.x0, self.x1, self.y0, self.y1)
    }

    /// Width in pixels.
    #[must_use]
    pub fn width(self) -> f64 {
        self.x1 - self.x0
    }

    /// Height in pixels.
    #[must_use]
    pub fn height(self) -> f64 {
        self.y1 - self.y0
    }
}

/// Space used by one panel's axes and compact text outside its data box.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct EdgeSpaceRequirements {
    pub(crate) left: f64,
    pub(crate) right: f64,
    pub(crate) bottom: f64,
    pub(crate) top: f64,
}

impl EdgeSpaceRequirements {
    pub(crate) fn measure_header(
        axes: &AxisSystemPlan,
        theme: &crate::text::TextRequestContext<'_, '_>,
    ) -> Result<Self, crate::layout::fit::PlanError> {
        let required = axes.requirements();

        let clearance = theme.panel_edge_lengths()?;
        Ok(Self {
            left: crate::theme::composition::hard(&clearance.left.add_pixels(required.left)?)?,
            right: crate::theme::composition::hard(&clearance.right.add_pixels(required.right)?)?,
            bottom: crate::theme::composition::hard(
                &clearance.bottom.add_pixels(required.bottom)?,
            )?,
            top: crate::theme::composition::hard(&clearance.top.add_pixels(required.top)?)?,
        })
    }
}

/// Reserved canvas margins around the plot panel.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CanvasInsets {
    /// Space reserved at the left of the canvas.
    pub left: f64,
    /// Space reserved at the right of the canvas.
    pub right: f64,
    /// Space reserved at the bottom of the canvas.
    pub bottom: f64,
    /// Space reserved at the top of the canvas.
    pub top: f64,
}

/// A resolved canvas layout for one chart canvas.
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct RootFramePlan {
    pub(crate) root_text: crate::decorations::title_block::plan::RootTitleBlockPlan,
    /// Root padding alone, before titles and shared scientific decorations.
    pub(crate) root_padding: [f64; 4],
    /// Plot panel available for data marks, axes, grid, and frame.
    pub panel_box: PixelRect,
    /// Resolved reserved margins.
    pub insets: CanvasInsets,
    pub(crate) native_preference:
        Option<crate::layout::interior::preference::CoordinateSizePreference>,
}

impl RootFramePlan {
    /// Recompose a selected scientific body with the same exact root chrome.
    /// Any added shared-axis bands are already canonical measured consequences.
    pub(crate) fn height_for_body(
        &self,
        body: f64,
        theme: &crate::text::TextRequestContext<'_, '_>,
    ) -> Result<f64, crate::Error> {
        let padding = theme.root_padding_lengths()?;
        let bottom = self
            .root_text
            .reserves
            .bottom
            .add_length(&padding.bottom)
            .after_pixels(0.0)?;
        let top = self
            .root_text
            .reserves
            .top
            .add_length(&padding.top)
            .pixels_rounded(crate::layout::kernel::SpatialRounding::NearestEven)?;
        let additional = (self.insets.bottom - bottom) + (self.insets.top - top);
        crate::theme::composition::hard(
            &self
                .root_text
                .reserves
                .height_with_body(body + additional)?
                .add_length(&padding.vertical()),
        )
    }

    pub(crate) fn into_shared(self) -> std::sync::Arc<Self> {
        std::sync::Arc::new(self)
    }
    pub(crate) fn measure(
        canvas_size: (f64, f64),
        theme: &crate::text::TextRequestContext<'_, '_>,
        text: [Option<&crate::Text>; 3],
        alignments: crate::decorations::title_block::plan::RootAlignments,
        minimum_body: (f64, f64),
    ) -> Result<Self, crate::layout::fit::PlanError> {
        let (canvas_width, canvas_height) = canvas_size;

        let outer = PixelRect::new(0.0, canvas_width, 0.0, canvas_height);
        let padding = theme.root_padding_lengths()?;
        let plan = crate::decorations::title_block::plan::RootTitleBlockPlan::measure(
            theme,
            text,
            outer,
            &padding,
            theme.root_inner_width(canvas_width)?,
            alignments,
            minimum_body.1,
            &crate::layout::fit::FitScope::root(),
        )?;
        if theme.root_outer_width(minimum_body.0)? > canvas_width {
            return Err(crate::layout::fit::FitScope::root()
                .failure(
                    crate::layout::kernel::FitKind::TrackOrResidual,
                    "root padding and complete content exceed the assigned root",
                )
                .into());
        }
        let panel_box = plan.reserves.body(outer, &padding)?;
        let padding_box = padding.inset(outer)?;
        let root_padding = [
            padding_box.x0,
            outer.x1 - padding_box.x1,
            outer.y1 - padding_box.y1,
            padding_box.y0,
        ];
        let insets = CanvasInsets {
            left: panel_box.x0,
            right: outer.x1 - panel_box.x1,
            bottom: panel_box.y0,
            top: outer.y1 - panel_box.y1,
        };
        crate::layout::fit::measured(
            crate::layout::kernel::FrameRequirements {
                minimum_body,
                natural_insets: [0.0; 4],
            }
            .assign_fit(panel_box, [0.0; 4], &crate::layout::fit::FitScope::root()),
        )?;
        Ok(Self {
            panel_box,
            root_padding,
            insets,
            root_text: plan,
            native_preference: None,
        })
    }
}

#[cfg(test)]
fn try_wrap_text(
    theme: &crate::text::TextRequestContext<'_, '_>,
    text: &str,
    appearance: &TextTheme,
    maximum_width: f64,
    alignment: PhysicalTextAlignment,
    role: &str,
) -> Result<Vec<String>, Error> {
    theme
        .plan_text(text, appearance, maximum_width, alignment, role, false)
        .and_then(|plan| plan.into_line_texts().map_err(Error::from))
}

#[cfg(test)]
fn wrap_text(
    theme: &crate::text::TextRequestContext<'_, '_>,
    text: &str,
    appearance: &TextTheme,
    maximum_width: f64,
) -> Vec<String> {
    try_wrap_text(
        theme,
        text,
        appearance,
        maximum_width,
        PhysicalTextAlignment::Start,
        "test text",
    )
    .unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::Theme;

    #[test]
    fn measured_caption_wraps_without_shortening_and_rejects_impossible_fit() {
        let theme = Theme::publication().resolve().unwrap();
        let text = crate::text::TextService::default();
        let theme = crate::text::TextRequestContext::new(&theme, &text);
        let caption =
            "diagnostic provenance with a deliberately long model and adjustment description";
        let alignments = crate::decorations::title_block::plan::RootAlignments::resolve(
            &theme, [None; 3], [None; 2],
        );
        let layout = RootFramePlan::measure(
            (360.0, 240.0),
            &theme,
            [None, None, Some(&crate::Text::new(caption))],
            alignments,
            (MINIMUM_PANEL_SPAN, MINIMUM_PANEL_SPAN),
        )
        .unwrap();
        let lines = wrap_text(&theme, caption, &theme.typography.root.caption, 328.0);

        assert!(lines.len() > 1);
        assert_eq!(lines.concat(), caption);
        let plan = &layout.root_text;
        assert!(
            crate::theme::composition::hard(&plan.reserves.bottom).unwrap()
                > theme.typography.root.caption.line_pitch_pixels()
        );
        assert!(RootFramePlan::measure(
            (160.0, 120.0),
            &theme,
            [None, None, Some(&crate::Text::new(caption.repeat(8)))],
            alignments,
            (MINIMUM_PANEL_SPAN, MINIMUM_PANEL_SPAN),
        )
        .is_err());
    }
}