use crate::layout::{
BoundaryRef, PaintBatch, PaintRole, PanelPath, PanelSlot, PanelStep, PixelRect,
};
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
left: f64,
top: f64,
width: f64,
height: f64,
}
impl Rect {
pub fn new(left: f64, top: f64, width: f64, height: f64) -> Result<Self> {
if ![left, top, width, height, left + width, top + height]
.into_iter()
.all(f64::is_finite)
|| width < 0.0
|| height < 0.0
{
return Err(Error::Data(
"rectangle requires finite coordinates and nonnegative extents".into(),
));
}
Ok(Self {
left,
top,
width,
height,
})
}
pub const fn left(self) -> f64 {
self.left
}
pub const fn top(self) -> f64 {
self.top
}
pub const fn width(self) -> f64 {
self.width
}
pub const fn height(self) -> f64 {
self.height
}
pub(crate) fn from_panel(panel: PixelRect, root_height: f64) -> Result<Self> {
Self::new(
panel.x0,
root_height - panel.y1,
panel.width(),
panel.height(),
)
}
pub(crate) fn from_canonical(bounds: crate::render::coordinates::CanonicalBox) -> Result<Self> {
Self::new(
bounds.x.value(),
bounds.y.value(),
bounds.width.value(),
bounds.height.value(),
)
}
pub(crate) fn union(self, other: Self) -> Self {
let left = self.left.min(other.left);
let top = self.top.min(other.top);
let right = (self.left + self.width).max(other.left + other.width);
let bottom = (self.top + self.height).max(other.top + other.height);
Self {
left,
top,
width: right - left,
height: bottom - top,
}
}
pub(crate) fn intersection(self, other: Self) -> Option<Self> {
let left = self.left.max(other.left);
let top = self.top.max(other.top);
let right = (self.left + self.width).min(other.left + other.width);
let bottom = (self.top + self.height).min(other.top + other.height);
(left < right && top < bottom).then_some(Self {
left,
top,
width: right - left,
height: bottom - top,
})
}
pub(crate) fn contains(self, other: Self) -> bool {
self.left() <= other.left()
&& self.top() <= other.top()
&& self.left() + self.width() >= other.left() + other.width()
&& self.top() + self.height() >= other.top() + other.height()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RectRef(pub(super) RefKind);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) enum RefKind {
Viewport,
Slot(usize, usize),
Panel(PanelPath),
PlotArea(PanelPath),
Decoration(PanelPath, LayoutRole, usize),
}
impl RectRef {
pub fn x(&self, fraction: f64) -> Result<super::RectAxisPosition> {
super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::X, fraction)
}
pub fn y(&self, fraction: f64) -> Result<super::RectAxisPosition> {
super::RectAxisPosition::new(self.clone(), crate::coordinates::AxisRef::Y, fraction)
}
pub fn reservation_anchor(&self) -> Option<(usize, usize)> {
match self.0 {
RefKind::Slot(row, column) => Some((row, column)),
_ => None,
}
}
pub const fn viewport() -> Self {
Self(RefKind::Viewport)
}
pub const fn slot(row: usize, column: usize) -> Self {
Self(RefKind::Slot(row, column))
}
pub fn panel(path: impl Into<PanelPath>) -> Self {
Self(RefKind::Panel(path.into()))
}
pub fn plot_area(path: impl Into<PanelPath>) -> Self {
Self(RefKind::PlotArea(path.into()))
}
pub(crate) fn decoration(path: &PanelPath, role: LayoutRole, index: usize) -> Self {
Self(RefKind::Decoration(path.clone(), role, index))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LayoutRole {
Viewport,
Grid,
Panel,
PlotArea,
TextPanel,
ImagePanel,
FrozenPanel,
ObjectFrame,
ReservedSlot,
VacantSlot,
Title,
Subtitle,
Caption,
Legend,
SharedLegend,
ColumnHeader,
RowHeader,
RowTitle,
FacetStrip,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum InkExtent {
Empty,
Bounds(Rect),
Unknown,
}
impl InkExtent {
pub(crate) fn union(self, other: Self) -> Self {
match (self, other) {
(Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
(Self::Empty, value) | (value, Self::Empty) => value,
(Self::Bounds(a), Self::Bounds(b)) => Self::Bounds(a.union(b)),
}
}
pub(crate) fn clipped(self, clip: Rect) -> Self {
match self {
Self::Bounds(bounds) => bounds.intersection(clip).map_or(Self::Empty, Self::Bounds),
other => other,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayoutNode {
pub(crate) owner: PanelPath,
pub(crate) role: LayoutRole,
pub(crate) measured: Option<(f64, f64)>,
pub(crate) allocated: Rect,
pub(crate) ink: InkExtent,
pub(crate) clips: Vec<Rect>,
pub(crate) rect_ref: Option<RectRef>,
pub(crate) children: Vec<Self>,
}
impl LayoutNode {
pub(crate) fn new(
owner: PanelPath,
role: LayoutRole,
allocated: Rect,
rect_ref: Option<RectRef>,
) -> Self {
Self {
owner,
role,
measured: None,
allocated,
ink: InkExtent::Unknown,
clips: Vec::new(),
rect_ref,
children: Vec::new(),
}
}
pub fn owner(&self) -> &PanelPath {
&self.owner
}
pub const fn role(&self) -> LayoutRole {
self.role
}
pub const fn measured(&self) -> Option<(f64, f64)> {
self.measured
}
pub const fn allocated(&self) -> Rect {
self.allocated
}
pub const fn ink(&self) -> InkExtent {
self.ink
}
pub fn clips(&self) -> &[Rect] {
&self.clips
}
pub fn rect_ref(&self) -> Option<&RectRef> {
self.rect_ref.as_ref()
}
pub fn children(&self) -> &[Self] {
&self.children
}
fn find(&self, reference: &RectRef) -> Option<Rect> {
if self.rect_ref.as_ref() == Some(reference) {
return Some(self.allocated);
}
self.children.iter().find_map(|child| child.find(reference))
}
fn accept_paint(
&mut self,
batches: &[PaintBatch],
owners: &std::collections::HashMap<PanelPath, Vec<usize>>,
) -> Result<()> {
if !matches!(
self.role,
LayoutRole::ReservedSlot
| LayoutRole::VacantSlot
| LayoutRole::Title
| LayoutRole::Subtitle
| LayoutRole::Caption
| LayoutRole::ColumnHeader
| LayoutRole::RowHeader
| LayoutRole::RowTitle
| LayoutRole::FacetStrip
) {
self.ink = InkExtent::Empty;
if let Some(indices) = owners.get(&self.owner) {
for &index in indices {
let batch = &batches[index];
if self.owns_paint(batch) {
self.ink = self.ink.union(batch.ink());
crate::data::source::reserve_source(&mut self.clips, batch.clips().len())?;
self.clips.extend_from_slice(batch.clips());
}
}
}
}
for child in &mut self.children {
child.accept_paint(batches, owners)?;
}
Ok(())
}
fn owns_paint(&self, batch: &PaintBatch) -> bool {
use PaintRole::{
Annotation, Body, Grid, Headers, Overlay, PanelSurface, Primary, RootProse,
RootSurface, RowTitles, SharedAxes, SharedLegend,
};
match self.role {
LayoutRole::Viewport => true,
LayoutRole::Grid => {
!batch.owner().is_root()
|| matches!(
batch.role(),
Headers | RowTitles | SharedAxes | SharedLegend
)
}
LayoutRole::Panel => !matches!(
batch.role(),
RootSurface | RootProse | SharedAxes | SharedLegend | Headers | RowTitles
),
LayoutRole::PlotArea => {
batch.owner() == &self.owner
&& matches!(
batch.role(),
Primary | Overlay | Body | PanelSurface | Grid | Annotation
)
}
LayoutRole::TextPanel => {
batch.owner() == &self.owner && batch.role() == PaintRole::TextPanel
}
LayoutRole::ImagePanel => {
batch.owner() == &self.owner && batch.role() == PaintRole::ImagePanel
}
LayoutRole::FrozenPanel => {
batch.owner() == &self.owner && batch.role() == PaintRole::FrozenPanel
}
LayoutRole::ObjectFrame => {
batch.owner() == &self.owner
&& matches!(batch.role(), PaintRole::ImagePanel | PaintRole::FrozenPanel)
}
LayoutRole::Legend => batch.owner() == &self.owner && batch.role() == PaintRole::Legend,
LayoutRole::SharedLegend => {
batch.owner() == &self.owner && batch.role() == PaintRole::SharedLegend
}
LayoutRole::ReservedSlot
| LayoutRole::VacantSlot
| LayoutRole::Title
| LayoutRole::Subtitle
| LayoutRole::Caption
| LayoutRole::ColumnHeader
| LayoutRole::RowHeader
| LayoutRole::RowTitle
| LayoutRole::FacetStrip => false,
}
}
pub(crate) fn text_decoration(
owner: &PanelPath,
role: LayoutRole,
index: usize,
bounds: PixelRect,
placement: crate::render::backend::PlannedTextPlacement,
plan: &crate::layout::ResolvedTextPlan,
root_height: f64,
) -> Result<Self> {
let mut node = Self::new(
owner.clone(),
role,
Rect::from_panel(bounds, root_height)?,
Some(RectRef::decoration(owner, role, index)),
);
node.measured = Some(plan.occupied_size());
node.ink = if plan.style.paint.get_alpha() == 0.0 {
InkExtent::Empty
} else {
crate::render::geometry::planned_text_ink_bounds(
plan,
placement.position,
placement.anchor,
placement.rotation,
placement.origin,
placement.reverse_lines,
)
.map(|ink| {
Rect::from_panel(
PixelRect::new(ink.left, ink.right, ink.bottom, ink.top),
root_height,
)
})
.transpose()?
.map_or(InkExtent::Empty, InkExtent::Bounds)
};
if let Some(clip) = crate::layout::text::placement::paint_clip(placement, plan)? {
if clip.width() > 0. && clip.height() > 0. {
node.clips.push(Rect::from_panel(clip, root_height)?);
}
}
Ok(node)
}
pub(crate) fn from_plot(
plot: &crate::decorations::plan::MeasuredPlotPlan,
source: &crate::builder::PlotDescription,
allocated: Rect,
root_height: f64,
) -> Result<Self> {
use crate::layout::interior::MarkPayload;
let owner = plot.panel_path.clone();
let mut node = Self::new(
owner.clone(),
LayoutRole::Panel,
allocated,
Some(RectRef::panel(owner.clone())),
);
let marks = plot.result.marks.as_ref().expect("accepted plot has marks");
match &marks.payload {
MarkPayload::Matrix(payload) => {
let variables = source
.matrix_variables()
.expect("accepted matrix variables");
crate::data::source::reserve_source(
&mut node.children,
variables
.len()
.checked_mul(variables.len())
.ok_or_else(|| Error::Render("matrix report shape overflowed".into()))?,
)?;
for (index, allocation, area) in payload.layout_regions() {
let x = &variables.variables()[index % variables.len()].key;
let y = &variables.variables()[index / variables.len()].key;
node.children.push(Self::region(
owner.clone().matrix(x.clone(), y.clone()),
allocation,
area,
root_height,
)?);
}
}
MarkPayload::Marginal(payload) => {
for (region, area) in payload.layout_regions() {
node.children.push(Self::region(
owner.clone().marginal(region),
area,
area,
root_height,
)?);
}
}
_ => node.children.push(Self::plot_area(
owner.clone(),
plot.result.layout.projection.panel_box(),
root_height,
)?),
}
let guide = match &marks.payload {
MarkPayload::Matrix(payload) => payload.legend_draw(),
MarkPayload::Heatmap(payload) => payload.legend_draw(),
MarkPayload::Beeswarm(payload) => payload.legend_draw(),
_ => None,
};
if let Some(guide) = guide {
node.children
.push(guide.report_node(&owner, root_height, false)?);
}
Ok(node)
}
fn region(
owner: PanelPath,
allocation: PixelRect,
area: PixelRect,
height: f64,
) -> Result<Self> {
let mut node = Self::new(
owner.clone(),
LayoutRole::Panel,
Rect::from_panel(allocation, height)?,
Some(RectRef::panel(owner.clone())),
);
node.children.push(Self::plot_area(owner, area, height)?);
Ok(node)
}
fn plot_area(owner: PanelPath, area: PixelRect, height: f64) -> Result<Self> {
Ok(Self::new(
owner.clone(),
LayoutRole::PlotArea,
Rect::from_panel(area, height)?,
Some(RectRef::plot_area(owner)),
))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GridCellState {
Empty,
Filled,
Reserved,
Vacant,
Covered,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GridCellReport {
pub(crate) row: usize,
pub(crate) column: usize,
pub(crate) state: GridCellState,
pub(crate) anchor: Option<(usize, usize)>,
pub(crate) slot: Option<PanelSlot>,
pub(crate) allocated: Rect,
}
impl GridCellReport {
pub const fn row(&self) -> usize {
self.row
}
pub const fn column(&self) -> usize {
self.column
}
pub const fn state(&self) -> GridCellState {
self.state
}
pub const fn anchor(&self) -> Option<(usize, usize)> {
self.anchor
}
pub fn slot(&self) -> Option<&PanelSlot> {
self.slot.as_ref()
}
pub const fn allocated(&self) -> Rect {
self.allocated
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayoutReport {
viewport: Rect,
root_padding: [f64; 4],
root_paper: crate::Color,
nodes: std::sync::Arc<[LayoutNode]>,
grid_cells: std::sync::Arc<[GridCellReport]>,
paint_order: std::sync::Arc<[PaintBatch]>,
boundaries: std::sync::Arc<[BoundaryRef]>,
}
impl LayoutReport {
pub(crate) fn new(
viewport: Rect,
root: LayoutNode,
grid_cells: Vec<GridCellReport>,
root_padding: [f64; 4],
root_paper: crate::Color,
) -> Self {
Self {
viewport,
root_padding,
root_paper,
nodes: std::sync::Arc::from([root]),
grid_cells: grid_cells.into(),
paint_order: std::sync::Arc::from([]),
boundaries: std::sync::Arc::from([]),
}
}
pub(crate) fn capture(
root: &crate::orchestrator::root::Root<'_>,
plan: &crate::orchestrator::plan::MeasuredOwnedPlan,
) -> Result<Self> {
use crate::orchestrator::{plan::MeasuredRootContent, root::RootSource};
let (width, viewport_height) = plan.size.dimensions()?;
let (_, height) = plan.size.layout_dimensions()?;
let viewport = Rect::new(0., 0., width, viewport_height)?;
let mut node = LayoutNode::new(
PanelPath::root(),
LayoutRole::Viewport,
viewport,
Some(RectRef::viewport()),
);
let mut cells = Vec::new();
match (&plan.content, root.source) {
(MeasuredRootContent::Single { plot, legend }, RootSource::Plot(source)) => {
let mut panel = LayoutNode::from_plot(
plot,
source,
Rect::from_panel(plot.selected.cell, height)?,
height,
)?;
if plot.result.decoration_mode == crate::spec::DecorationMode::Standard {
if let Some((_, guide)) = legend {
panel
.children
.push(guide.report_node(&plot.panel_path, height, false)?);
}
}
node.children.push(panel);
}
(MeasuredRootContent::Facets(plan), RootSource::Plot(_)) => {
node.children.push(plan.report_grid(root, height)?);
}
(MeasuredRootContent::Canvas(plan), RootSource::Canvas(source)) => {
let (grid, grid_cells) = source.report_grid(plan, height)?;
node.children.push(grid);
cells = grid_cells;
}
_ => {
return Err(Error::Render(
"accepted layout does not match its native root".into(),
))
}
}
node.children.extend(
plan.frame
.root_text
.report_nodes(&PanelPath::root(), height)?,
);
Ok(Self::new(
viewport,
node,
cells,
plan.frame.root_padding,
plan.root_paint,
))
}
pub const fn viewport(&self) -> Rect {
self.viewport
}
pub(crate) const fn root_padding(&self) -> [f64; 4] {
self.root_padding
}
pub(crate) const fn root_paper(&self) -> crate::Color {
self.root_paper
}
pub fn nodes(&self) -> &[LayoutNode] {
&self.nodes
}
pub fn grid_cells(&self) -> &[GridCellReport] {
&self.grid_cells
}
pub fn paint_order(&self) -> &[PaintBatch] {
&self.paint_order
}
pub fn boundaries(&self) -> &[BoundaryRef] {
&self.boundaries
}
pub(crate) fn accept_paint(&mut self, mut batches: Vec<PaintBatch>) -> Result<()> {
batches.sort_by_key(|batch| (batch.buffer, batch.range.start));
for pair in batches.windows(2) {
if pair[0].buffer == pair[1].buffer && pair[0].range.end > pair[1].range.start {
return Err(Error::Render("native paint batches overlap".into()));
}
}
let mut counts = std::collections::HashMap::new();
counts.try_reserve(batches.len()).map_err(|error| {
Error::Render(format!("paint identity reservation: {error}").into())
})?;
for batch in &batches {
*counts.entry(batch.reference()).or_insert(0usize) += 1;
}
let unique = |batch: &PaintBatch| counts.get(batch.reference()) == Some(&1);
let mut boundaries = Vec::new();
crate::data::source::reserve_source(&mut boundaries, batches.len().saturating_add(1))?;
if let Some(first) = batches.first().filter(|batch| unique(batch)) {
boundaries.push(BoundaryRef::between(None, Some(first)));
}
for pair in batches.windows(2) {
if unique(&pair[0]) && unique(&pair[1]) {
boundaries.push(BoundaryRef::between(Some(&pair[0]), Some(&pair[1])));
}
}
if let Some(last) = batches.last().filter(|batch| unique(batch)) {
boundaries.push(BoundaryRef::between(Some(last), None));
}
drop(counts);
let mut owners = std::collections::HashMap::new();
for (index, batch) in batches.iter().enumerate() {
let steps = batch.owner().steps();
for depth in 0..=steps.len() {
owners.try_reserve(1).map_err(|error| {
Error::Render(format!("paint owner reservation: {error}").into())
})?;
let indices = owners
.entry(PanelPath::from_steps(&steps[..depth]))
.or_insert_with(Vec::new);
crate::data::source::reserve_source(indices, 1)?;
indices.push(index);
}
}
for node in std::sync::Arc::make_mut(&mut self.nodes) {
node.accept_paint(&batches, &owners)?;
}
self.paint_order = batches.into();
self.boundaries = boundaries.into();
Ok(())
}
fn canonical_panel(&self, panel: &PanelPath) -> Result<PanelPath> {
if let Some(PanelStep::Cell(row, column)) = panel.steps().first() {
self.check_coverage(*row, *column)?;
}
let Some(PanelStep::Named(name)) = panel.steps().first() else {
return Ok(panel.clone());
};
let cell = self
.grid_cells
.iter()
.find(|cell| cell.slot.as_ref().and_then(PanelSlot::name) == Some(name))
.ok_or_else(|| {
crate::errors::Diagnostic::new(
crate::errors::DiagnosticKind::UnknownKey {
key: Some(crate::data::RawKey::from(name.as_str())),
},
format!("frozen Canvas has no panel named {name:?}"),
)
})
.map_err(Error::Data)?;
let mut steps = vec![PanelStep::Cell(cell.row, cell.column)];
steps.extend_from_slice(&panel.steps()[1..]);
Ok(PanelPath::from_steps(&steps))
}
fn check_coverage(&self, row: usize, column: usize) -> Result<()> {
if let Some(cell) = self
.grid_cells
.iter()
.find(|cell| cell.row == row && cell.column == column)
{
if cell.state == GridCellState::Covered {
let (r, c) = cell.anchor.expect("covered cell has an anchor");
return Err(Error::Data(
format!("Canvas cell ({row}, {column}) is covered by anchor ({r}, {c})").into(),
));
}
}
Ok(())
}
pub fn rect(&self, reference: &RectRef) -> Result<Rect> {
let reference = match &reference.0 {
RefKind::Slot(row, column) => {
self.check_coverage(*row, *column)?;
reference.clone()
}
RefKind::Panel(panel) => RectRef::panel(self.canonical_panel(panel)?),
RefKind::PlotArea(panel) => RectRef::plot_area(self.canonical_panel(panel)?),
RefKind::Decoration(panel, role, index) => {
RectRef::decoration(&self.canonical_panel(panel)?, *role, *index)
}
RefKind::Viewport => reference.clone(),
};
self.nodes
.iter()
.find_map(|node| node.find(&reference))
.ok_or_else(|| {
Error::Data(format!("no actual allocated rectangle for {reference:?}").into())
})
}
}