lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Report the accepted grid without reconstructing positions from painted SVG.

use super::{Canvas, OwnedCanvasPlan, OwnedCanvasPlot};
use crate::layout::{
    GridCellReport, GridCellState, InkExtent, LayoutNode, LayoutRole, PanelPath, Rect, RectRef,
};
use crate::{Error, Result};

impl Canvas {
    #[expect(
        clippy::too_many_lines,
        reason = "one actual grid traversal retains all canonical cell and owner states"
    )]
    pub(crate) fn report_grid(
        &self,
        plan: &OwnedCanvasPlan,
        root_height: f64,
    ) -> Result<(LayoutNode, Vec<GridCellReport>)> {
        let mut grid = LayoutNode::new(
            PanelPath::root(),
            LayoutRole::Grid,
            Rect::from_panel(plan.grid.tracks.bounds(), root_height)?,
            None,
        );
        let mut cells = Vec::new();
        let count = self.placements.len();
        crate::data::source::reserve_source(&mut cells, count)?;
        crate::data::source::reserve_source(&mut grid.children, self.placements.slots().count())?;
        let mut plots = plan.plots.iter();
        let mut text_panels = plan.text_panels.iter();
        let mut fixed_panels = plan.fixed_panels.iter();
        for index in 0..count {
            let row = index / self.columns;
            let column = index % self.columns;
            let slot = self.placements.slot(index);
            let anchor = self
                .placements
                .anchor(row, column)
                .map(|owner| (owner / self.columns, owner % self.columns));
            let state = match &slot {
                Some(slot) if slot.is_filled() => GridCellState::Filled,
                Some(slot) if slot.reservation().is_some() => GridCellState::Reserved,
                Some(_) => GridCellState::Vacant,
                None if anchor.is_some() => GridCellState::Covered,
                None => GridCellState::Empty,
            };
            cells.push(GridCellReport {
                row,
                column,
                state,
                anchor,
                allocated: Rect::from_panel(plan.grid.tracks.cell(row, column), root_height)?,
                slot,
            });
            let Some(allocation) = plan.grid.owners[index] else {
                continue;
            };
            let owner = PanelPath::root().panel(row, column);
            let allocated = Rect::from_panel(allocation, root_height)?;
            let mut node = match state {
                GridCellState::Reserved | GridCellState::Vacant => {
                    let mut node = LayoutNode::new(
                        owner,
                        if state == GridCellState::Reserved {
                            LayoutRole::ReservedSlot
                        } else {
                            LayoutRole::VacantSlot
                        },
                        allocated,
                        Some(RectRef::slot(row, column)),
                    );
                    node.ink = InkExtent::Empty;
                    node
                }
                GridCellState::Filled => {
                    if let Some(source) = self.placements.plot(index) {
                        let plot = plots
                            .next()
                            .filter(|panel| panel.anchor.0 == index)
                            .ok_or_else(|| {
                                Error::Render("accepted Canvas Plot has no report owner".into())
                            })?;
                        report_plot(plot, source, allocated, root_height)?
                    } else if let Some(fixed) = self.placements.fixed(index) {
                        let (_, panel) = fixed_panels
                            .next()
                            .filter(|(anchor, _)| *anchor == index)
                            .ok_or_else(|| {
                                Error::Render("accepted Canvas image has no report owner".into())
                            })?;
                        let role = if fixed.is_frozen() {
                            LayoutRole::FrozenPanel
                        } else {
                            LayoutRole::ImagePanel
                        };
                        let mut node = LayoutNode::new(
                            owner.clone(),
                            role,
                            allocated,
                            Some(RectRef::panel(owner.clone())),
                        );
                        node.children.push(LayoutNode::new(
                            owner.clone(),
                            LayoutRole::ObjectFrame,
                            panel.frame,
                            Some(RectRef::decoration(&owner, LayoutRole::ObjectFrame, 0)),
                        ));
                        node
                    } else {
                        text_panels
                            .next()
                            .filter(|panel| panel.anchor == index)
                            .ok_or_else(|| {
                                Error::Render("accepted Canvas prose has no report owner".into())
                            })?;
                        LayoutNode::new(
                            owner.clone(),
                            LayoutRole::TextPanel,
                            allocated,
                            Some(RectRef::panel(owner)),
                        )
                    }
                }
                _ => {
                    return Err(Error::Render(
                        "nonanchor Canvas cell has an allocated owner".into(),
                    ))
                }
            };
            node.measured = plan.grid.owner_minima[index];
            grid.children.push(node);
        }
        if plots.next().is_some() || text_panels.next().is_some() || fixed_panels.next().is_some() {
            return Err(Error::Render(
                "accepted Canvas has unmatched report owners".into(),
            ));
        }
        append_grid_decorations(&mut grid, plan, root_height)?;
        Ok((grid, cells))
    }
}

fn report_plot(
    plot: &OwnedCanvasPlot,
    source: &crate::builder::PlotDescription,
    allocated: Rect,
    height: f64,
) -> Result<LayoutNode> {
    let mut node = LayoutNode::from_plot(&plot.plot, source, allocated, height)?;
    let owner = &plot.plot.panel_path;
    if let Some((_, legend)) = &plot.legend {
        node.children
            .push(legend.report_node(owner, height, false)?);
    }
    node.children
        .extend(plot.prose.report_nodes(owner, height)?);
    Ok(node)
}

fn append_grid_decorations(
    grid: &mut LayoutNode,
    plan: &OwnedCanvasPlan,
    height: f64,
) -> Result<()> {
    let owner = PanelPath::root();
    let count = plan
        .grid
        .headers
        .len()
        .checked_add(plan.grid.row_titles.len())
        .and_then(|count| count.checked_add(usize::from(plan.shared_guide.is_some())))
        .ok_or_else(|| Error::Render("Canvas decoration report count overflowed".into()))?;
    crate::data::source::reserve_source(&mut grid.children, count)?;
    for header in plan.grid.headers.iter().chain(&plan.grid.row_titles) {
        grid.children.push(LayoutNode::text_decoration(
            &owner,
            header.role,
            header.declaration,
            header.bounds,
            header.text.placement,
            &header.text.plan,
            height,
        )?);
    }
    if let Some(guide) = &plan.shared_guide {
        grid.children.push(guide.report_node(&owner, height, true)?);
    }
    Ok(())
}