use crate::builder::PlotDescription;
use crate::{
data::RawKey,
errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
kind::ExactFamily,
layout::{PanelStep, TextPanel},
Error, Plot,
};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Footprint {
pub row: usize,
pub column: usize,
pub row_span: usize,
pub column_span: usize,
}
#[derive(Clone)]
pub(super) enum Payload {
Plot(PlotDescription),
Text(TextPanel),
Fixed(crate::composition::FixedPanel),
Reserved((f64, f64)),
Vacant,
}
#[derive(Clone)]
pub struct PanelContent(pub(super) Payload);
impl<K: ExactFamily> From<Plot<K>> for PanelContent {
fn from(plot: Plot<K>) -> Self {
Self(Payload::Plot(plot.into_description()))
}
}
impl<K: ExactFamily> From<&Plot<K>> for PanelContent {
fn from(plot: &Plot<K>) -> Self {
Self(Payload::Plot(plot.description().clone()))
}
}
impl From<TextPanel> for PanelContent {
fn from(text: TextPanel) -> Self {
Self(Payload::Text(text))
}
}
impl From<&TextPanel> for PanelContent {
fn from(text: &TextPanel) -> Self {
Self(Payload::Text(text.clone()))
}
}
impl TryFrom<crate::composition::PanelImage> for PanelContent {
type Error = Error;
fn try_from(value: crate::composition::PanelImage) -> crate::Result<Self> {
Ok(Self(Payload::Fixed(value.admit()?)))
}
}
macro_rules! fixed_content {
($($ty:ty),+ $(,)?) => {$(
impl TryFrom<$ty> for PanelContent {
type Error = Error;
fn try_from(value: $ty) -> crate::Result<Self> {
crate::composition::PanelImage::from(value).try_into()
}
}
)+};
}
fixed_content!(
&str,
String,
&std::path::Path,
std::path::PathBuf,
&std::path::PathBuf,
crate::composition::ImageAsset,
&crate::composition::ImageAsset,
crate::Output,
&crate::Output,
crate::composition::Composite,
&crate::composition::Composite,
);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ReservedSlot {
minimum: (f64, f64),
row_span: usize,
column_span: usize,
}
impl ReservedSlot {
pub fn at_least(min_width: f64, min_height: f64) -> crate::Result<Self> {
if ![min_width, min_height]
.into_iter()
.all(|value| value.is_finite() && value >= 0.0 && value <= f64::from(u32::MAX))
{
return Err(Error::Data(
"reserved slot minimum dimensions must be finite nonnegative layout lengths".into(),
));
}
Ok(Self {
minimum: (min_width, min_height),
row_span: 1,
column_span: 1,
})
}
pub fn span(mut self, rows: usize, columns: usize) -> crate::Result<Self> {
if rows == 0 || columns == 0 {
return Err(Error::Data("reserved slot spans must be positive".into()));
}
self.row_span = rows;
self.column_span = columns;
Ok(self)
}
}
impl TryFrom<(f64, f64)> for ReservedSlot {
type Error = Error;
fn try_from((width, height): (f64, f64)) -> crate::Result<Self> {
Self::at_least(width, height)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PanelSlot {
name: Option<Arc<str>>,
footprint: Footprint,
reservation: Option<(f64, f64)>,
filled: bool,
}
impl PanelSlot {
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub const fn row(&self) -> usize {
self.footprint.row
}
pub const fn column(&self) -> usize {
self.footprint.column
}
pub const fn row_span(&self) -> usize {
self.footprint.row_span
}
pub const fn column_span(&self) -> usize {
self.footprint.column_span
}
pub const fn is_filled(&self) -> bool {
self.filled
}
pub const fn reservation(&self) -> Option<(f64, f64)> {
self.reservation
}
}
#[derive(Clone)]
struct Owner {
identity: crate::data::InstanceId,
footprint: Footprint,
payload: Payload,
content_origin: Option<crate::data::DataSourceInfo>,
name: Option<Arc<str>>,
}
impl Owner {
fn slot(&self) -> PanelSlot {
PanelSlot {
name: self.name.clone(),
footprint: self.footprint,
filled: !matches!(self.payload, Payload::Reserved(_) | Payload::Vacant),
reservation: match self.payload {
Payload::Reserved(minimum) => Some(minimum),
_ => None,
},
}
}
}
#[derive(Clone, Copy)]
enum Overlap {
Reject,
Replace,
}
#[derive(Clone)]
pub(super) struct Placements {
rows: usize,
columns: usize,
owners: Vec<Option<Owner>>,
occupancy: Vec<Option<usize>>,
}
impl Placements {
pub fn new(rows: usize, columns: usize) -> Result<Self, Error> {
let count = rows
.checked_mul(columns)
.ok_or_else(|| Error::Data("Canvas topology overflows storage".into()))?;
Ok(Self {
rows,
columns,
owners: crate::data::source::collect_source((0..count).map(|_| Ok(None)))?,
occupancy: crate::data::source::collect_source((0..count).map(|_| Ok(None)))?,
})
}
pub fn len(&self) -> usize {
self.owners.len()
}
pub fn shape(&self) -> (usize, usize) {
(self.rows, self.columns)
}
pub fn plot(&self, index: usize) -> Option<&PlotDescription> {
match &self.owners.get(index)?.as_ref()?.payload {
Payload::Plot(plot) => Some(plot),
_ => None,
}
}
pub fn plot_identity(&self, index: usize) -> Option<&crate::data::InstanceId> {
let owner = self.owners.get(index)?.as_ref()?;
matches!(owner.payload, Payload::Plot(_)).then_some(&owner.identity)
}
pub fn text(&self, index: usize) -> Option<&TextPanel> {
match &self.owners.get(index)?.as_ref()?.payload {
Payload::Text(text) => Some(text),
_ => None,
}
}
pub fn fixed(&self, index: usize) -> Option<&crate::composition::FixedPanel> {
match &self.owners.get(index)?.as_ref()?.payload {
Payload::Fixed(image) => Some(image),
_ => None,
}
}
pub(super) fn payload(&self, index: usize) -> Option<&Payload> {
self.owners.get(index)?.as_ref().map(|owner| &owner.payload)
}
pub(super) fn payload_mut(&mut self, index: usize) -> Option<&mut Payload> {
self.owners
.get_mut(index)?
.as_mut()
.map(|owner| &mut owner.payload)
}
pub(super) fn content_origin(&self, index: usize) -> Option<&crate::data::DataSourceInfo> {
self.owners.get(index)?.as_ref()?.content_origin.as_ref()
}
pub(super) fn set_content_origin(
&mut self,
index: usize,
origin: Option<crate::data::DataSourceInfo>,
) {
self.owners[index]
.as_mut()
.expect("actual content owner")
.content_origin = origin;
}
pub(super) fn vacant(&self, index: usize) -> bool {
matches!(self.payload(index), Some(Payload::Vacant))
}
pub fn reservation(&self, index: usize) -> Option<(f64, f64)> {
match self.owners.get(index)?.as_ref()?.payload {
Payload::Reserved(minimum) => Some(minimum),
_ => None,
}
}
pub fn plots(&self) -> impl ExactSizeIterator<Item = Option<&PlotDescription>> {
(0..self.len()).map(|index| self.plot(index))
}
pub fn texts(&self) -> impl ExactSizeIterator<Item = Option<&TextPanel>> {
(0..self.len()).map(|index| self.text(index))
}
pub fn footprint(&self, index: usize) -> Option<Footprint> {
self.owners
.get(index)?
.as_ref()
.map(|owner| owner.footprint)
}
pub fn anchor(&self, row: usize, column: usize) -> Option<usize> {
if row >= self.rows || column >= self.columns {
return None;
}
self.occupancy[row * self.columns + column]
}
pub fn slots(&self) -> impl Iterator<Item = PanelSlot> + '_ {
self.owners.iter().flatten().map(Owner::slot)
}
pub fn slot(&self, index: usize) -> Option<PanelSlot> {
self.owners.get(index)?.as_ref().map(Owner::slot)
}
fn find_named(&self, name: &str) -> Option<usize> {
self.owners
.iter()
.position(|owner| owner.as_ref().and_then(|owner| owner.name.as_deref()) == Some(name))
}
pub fn named_index(&self, name: &str) -> crate::Result<usize> {
self.find_named(name).ok_or_else(|| {
Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey {
key: Some(RawKey::from(name)),
},
format!("Canvas has no panel named {name:?}"),
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
)
})
}
pub fn anchor_index(&self, row: usize, column: usize) -> crate::Result<usize> {
let index = self.anchor(row, column).ok_or_else(|| {
Error::Data(format!("Canvas has no declared slot at ({row}, {column})").into())
})?;
let owner = self.owners[index].as_ref().expect("occupied anchor");
if (owner.footprint.row, owner.footprint.column) != (row, column) {
return Err(Error::Data(
format!(
"Canvas cell ({row}, {column}) is covered by anchor ({}, {})",
owner.footprint.row, owner.footprint.column
)
.into(),
));
}
Ok(index)
}
pub fn resolve_step(&self, step: &PanelStep) -> crate::Result<usize> {
match step {
PanelStep::Cell(row, column) => self.anchor_index(*row, *column),
PanelStep::Named(name) => self.named_index(name),
_ => Err(Error::Data(
format!("expected a direct Canvas grid anchor, got {step:?}").into(),
)),
}
}
pub fn name(&mut self, row: usize, column: usize, name: &str) -> crate::Result<()> {
let index = self.anchor_index(row, column)?;
if name.is_empty() {
return Err(Error::Data("Canvas panel name must not be empty".into()));
}
if let Some(other) = self.find_named(name) {
if other != index {
let footprint = self.footprint(other).expect("named owner");
return Err(Error::Data(
format!(
"Canvas panel name {name:?} already belongs to anchor ({}, {})",
footprint.row, footprint.column
)
.into(),
));
}
}
self.owners[index].as_mut().expect("declared anchor").name =
Some(Arc::from(crate::data::source::copy_source_string(name)?));
Ok(())
}
pub fn reserve(&mut self, row: usize, column: usize, slot: ReservedSlot) -> crate::Result<()> {
self.insert(
Footprint {
row,
column,
row_span: slot.row_span,
column_span: slot.column_span,
},
Payload::Reserved(slot.minimum),
)
}
pub fn insert(&mut self, footprint: Footprint, payload: Payload) -> Result<(), Error> {
self.place(footprint, payload, Overlap::Reject)
}
pub fn replace(&mut self, footprint: Footprint, payload: Payload) -> Result<(), Error> {
self.place(footprint, payload, Overlap::Replace)
}
fn place(
&mut self,
mut footprint: Footprint,
payload: Payload,
overlap: Overlap,
) -> Result<(), Error> {
let vacant = if matches!(overlap, Overlap::Reject)
&& !matches!(payload, Payload::Reserved(_) | Payload::Vacant)
{
self.anchor(footprint.row, footprint.column)
.filter(|&index| {
(self.reservation(index).is_some() || self.vacant(index))
&& self.footprint(index).is_some_and(|existing| {
(existing.row, existing.column) == (footprint.row, footprint.column)
&& (existing == footprint
|| (footprint.row_span, footprint.column_span) == (1, 1))
})
})
} else {
None
};
if let Some(index) = vacant {
footprint = self.footprint(index).expect("empty declared anchor");
}
let row_end = footprint
.row
.checked_add(footprint.row_span)
.filter(|&end| footprint.row_span > 0 && end <= self.rows);
let column_end = footprint
.column
.checked_add(footprint.column_span)
.filter(|&end| footprint.column_span > 0 && end <= self.columns);
let (Some(row_end), Some(column_end)) = (row_end, column_end) else {
return Err(Error::Data(
"Canvas footprint is empty, overflowing or outside its declared grid".into(),
));
};
if matches!(overlap, Overlap::Reject) {
for row in footprint.row..row_end {
for column in footprint.column..column_end {
let occupied = self.occupancy[row * self.columns + column];
if let Some(owner) = occupied.filter(|owner| Some(*owner) != vacant) {
let footprint = self.footprint(owner).expect("occupied anchor");
return Err(Error::Data(
format!(
"Canvas footprint overlaps occupied cell ({row}, {column}) owned by anchor ({}, {})",
footprint.row, footprint.column
).into(),
));
}
}
}
}
let anchor = footprint.row * self.columns + footprint.column;
let name = self.owners[anchor]
.as_ref()
.filter(|owner| owner.footprint == footprint)
.and_then(|owner| owner.name.clone());
if let Some(index) = vacant {
self.remove(index);
} else if matches!(overlap, Overlap::Replace) {
for row in footprint.row..row_end {
for column in footprint.column..column_end {
if let Some(owner) = self.occupancy[row * self.columns + column] {
self.remove(owner);
}
}
}
}
self.owners[anchor] = Some(Owner {
identity: crate::data::InstanceId::new(),
footprint,
payload,
content_origin: None,
name,
});
for row in footprint.row..row_end {
for column in footprint.column..column_end {
self.occupancy[row * self.columns + column] = Some(anchor);
}
}
Ok(())
}
fn remove(&mut self, anchor: usize) {
let owner = self.owners[anchor]
.take()
.expect("occupied slot has an owner");
let footprint = owner.footprint;
for row in footprint.row..footprint.row + footprint.row_span {
for column in footprint.column..footprint.column + footprint.column_span {
self.occupancy[row * self.columns + column] = None;
}
}
}
}